@tanstack/query-core 5.105.1 → 5.105.2
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/build/legacy/{hydration-DdkP3REv.d.cts → hydration-BXjqUj_D.d.cts} +25 -14
- package/build/legacy/hydration-BXjqUj_D.d.cts.map +1 -0
- package/build/legacy/{hydration-gHEs4kLM.d.ts → hydration-vgIjIhk6.d.ts} +25 -14
- package/build/legacy/hydration-vgIjIhk6.d.ts.map +1 -0
- package/build/legacy/hydration.d.cts +1 -1
- package/build/legacy/hydration.d.ts +1 -1
- package/build/legacy/index.d.cts +1 -1
- package/build/legacy/index.d.ts +1 -1
- package/build/legacy/infiniteQueryBehavior.cjs +2 -1
- package/build/legacy/infiniteQueryBehavior.cjs.map +1 -1
- package/build/legacy/infiniteQueryBehavior.d.cts +1 -1
- package/build/legacy/infiniteQueryBehavior.d.cts.map +1 -1
- package/build/legacy/infiniteQueryBehavior.d.ts +1 -1
- package/build/legacy/infiniteQueryBehavior.d.ts.map +1 -1
- package/build/legacy/infiniteQueryBehavior.js +3 -2
- package/build/legacy/infiniteQueryBehavior.js.map +1 -1
- package/build/legacy/infiniteQueryObserver.d.cts +1 -1
- package/build/legacy/infiniteQueryObserver.d.ts +1 -1
- package/build/legacy/mutation.cjs +1 -0
- package/build/legacy/mutation.cjs.map +1 -1
- package/build/legacy/mutation.d.cts +1 -1
- package/build/legacy/mutation.d.ts +1 -1
- package/build/legacy/mutation.js +1 -0
- package/build/legacy/mutation.js.map +1 -1
- package/build/legacy/mutationCache.d.cts +1 -1
- package/build/legacy/mutationCache.d.ts +1 -1
- package/build/legacy/mutationObserver.d.cts +1 -1
- package/build/legacy/mutationObserver.d.ts +1 -1
- package/build/legacy/queriesObserver.d.cts +1 -1
- package/build/legacy/queriesObserver.d.ts +1 -1
- package/build/legacy/query.cjs +54 -36
- package/build/legacy/query.cjs.map +1 -1
- package/build/legacy/query.d.cts +1 -1
- package/build/legacy/query.d.ts +1 -1
- package/build/legacy/query.js +55 -37
- package/build/legacy/query.js.map +1 -1
- package/build/legacy/queryCache.d.cts +1 -1
- package/build/legacy/queryCache.d.ts +1 -1
- package/build/legacy/queryClient.cjs +11 -6
- package/build/legacy/queryClient.cjs.map +1 -1
- package/build/legacy/queryClient.d.cts +1 -1
- package/build/legacy/queryClient.d.ts +1 -1
- package/build/legacy/queryClient.js +11 -6
- package/build/legacy/queryClient.js.map +1 -1
- package/build/legacy/queryObserver.d.cts +1 -1
- package/build/legacy/queryObserver.d.ts +1 -1
- package/build/legacy/retryer.d.cts +1 -1
- package/build/legacy/retryer.d.ts +1 -1
- package/build/legacy/streamedQuery.cjs +10 -4
- package/build/legacy/streamedQuery.cjs.map +1 -1
- package/build/legacy/streamedQuery.d.cts +3 -1
- package/build/legacy/streamedQuery.d.cts.map +1 -1
- package/build/legacy/streamedQuery.d.ts +3 -1
- package/build/legacy/streamedQuery.d.ts.map +1 -1
- package/build/legacy/streamedQuery.js +11 -5
- package/build/legacy/streamedQuery.js.map +1 -1
- package/build/legacy/types.d.cts +1 -1
- package/build/legacy/types.d.ts +1 -1
- package/build/legacy/utils.cjs +23 -19
- package/build/legacy/utils.cjs.map +1 -1
- package/build/legacy/utils.d.cts +2 -2
- package/build/legacy/utils.d.ts +2 -2
- package/build/legacy/utils.js +23 -20
- package/build/legacy/utils.js.map +1 -1
- package/build/modern/{hydration-DdkP3REv.d.cts → hydration-BXjqUj_D.d.cts} +25 -14
- package/build/modern/hydration-BXjqUj_D.d.cts.map +1 -0
- package/build/modern/{hydration-gHEs4kLM.d.ts → hydration-vgIjIhk6.d.ts} +25 -14
- package/build/modern/hydration-vgIjIhk6.d.ts.map +1 -0
- package/build/modern/hydration.d.cts +1 -1
- package/build/modern/hydration.d.ts +1 -1
- package/build/modern/index.d.cts +1 -1
- package/build/modern/index.d.ts +1 -1
- package/build/modern/infiniteQueryBehavior.cjs +2 -1
- package/build/modern/infiniteQueryBehavior.cjs.map +1 -1
- package/build/modern/infiniteQueryBehavior.d.cts +1 -1
- package/build/modern/infiniteQueryBehavior.d.cts.map +1 -1
- package/build/modern/infiniteQueryBehavior.d.ts +1 -1
- package/build/modern/infiniteQueryBehavior.d.ts.map +1 -1
- package/build/modern/infiniteQueryBehavior.js +3 -2
- package/build/modern/infiniteQueryBehavior.js.map +1 -1
- package/build/modern/infiniteQueryObserver.d.cts +1 -1
- package/build/modern/infiniteQueryObserver.d.ts +1 -1
- package/build/modern/mutation.cjs +1 -0
- package/build/modern/mutation.cjs.map +1 -1
- package/build/modern/mutation.d.cts +1 -1
- package/build/modern/mutation.d.ts +1 -1
- package/build/modern/mutation.js +1 -0
- package/build/modern/mutation.js.map +1 -1
- package/build/modern/mutationCache.d.cts +1 -1
- package/build/modern/mutationCache.d.ts +1 -1
- package/build/modern/mutationObserver.d.cts +1 -1
- package/build/modern/mutationObserver.d.ts +1 -1
- package/build/modern/queriesObserver.d.cts +1 -1
- package/build/modern/queriesObserver.d.ts +1 -1
- package/build/modern/query.cjs +51 -34
- package/build/modern/query.cjs.map +1 -1
- package/build/modern/query.d.cts +1 -1
- package/build/modern/query.d.ts +1 -1
- package/build/modern/query.js +52 -35
- package/build/modern/query.js.map +1 -1
- package/build/modern/queryCache.d.cts +1 -1
- package/build/modern/queryCache.d.ts +1 -1
- package/build/modern/queryClient.cjs +11 -6
- package/build/modern/queryClient.cjs.map +1 -1
- package/build/modern/queryClient.d.cts +1 -1
- package/build/modern/queryClient.d.ts +1 -1
- package/build/modern/queryClient.js +11 -6
- package/build/modern/queryClient.js.map +1 -1
- package/build/modern/queryObserver.d.cts +1 -1
- package/build/modern/queryObserver.d.ts +1 -1
- package/build/modern/retryer.d.cts +1 -1
- package/build/modern/retryer.d.ts +1 -1
- package/build/modern/streamedQuery.cjs +10 -4
- package/build/modern/streamedQuery.cjs.map +1 -1
- package/build/modern/streamedQuery.d.cts +3 -1
- package/build/modern/streamedQuery.d.cts.map +1 -1
- package/build/modern/streamedQuery.d.ts +3 -1
- package/build/modern/streamedQuery.d.ts.map +1 -1
- package/build/modern/streamedQuery.js +11 -5
- package/build/modern/streamedQuery.js.map +1 -1
- package/build/modern/types.d.cts +1 -1
- package/build/modern/types.d.ts +1 -1
- package/build/modern/utils.cjs +23 -19
- package/build/modern/utils.cjs.map +1 -1
- package/build/modern/utils.d.cts +2 -2
- package/build/modern/utils.d.ts +2 -2
- package/build/modern/utils.js +23 -20
- package/build/modern/utils.js.map +1 -1
- package/package.json +1 -1
- package/src/infiniteQueryBehavior.ts +5 -1
- package/src/mutation.ts +4 -0
- package/src/query.ts +78 -64
- package/src/queryClient.ts +16 -10
- package/src/streamedQuery.ts +14 -3
- package/src/utils.ts +39 -26
- package/build/legacy/hydration-DdkP3REv.d.cts.map +0 -1
- package/build/legacy/hydration-gHEs4kLM.d.ts.map +0 -1
- package/build/modern/hydration-DdkP3REv.d.cts.map +0 -1
- package/build/modern/hydration-gHEs4kLM.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../../src/utils.ts"],"sourcesContent":["import { timeoutManager } from './timeoutManager'\nimport type {\n DefaultError,\n FetchStatus,\n MutationKey,\n MutationStatus,\n QueryFunction,\n QueryKey,\n QueryOptions,\n} from './types'\nimport type { Mutation } from './mutation'\nimport type { FetchOptions, Query } from './query'\n\n// TYPES\n\ntype DropLast<T extends ReadonlyArray<unknown>> = T extends readonly [\n ...infer R,\n unknown,\n]\n ? readonly [...R]\n : never\n\ntype TuplePrefixes<T extends ReadonlyArray<unknown>> = T extends readonly []\n ? readonly []\n : TuplePrefixes<DropLast<T>> | T\n\n/**\n * Filters used to select queries, for example in `queryClient.getQueriesData` or `queryClient.invalidateQueries`.\n * All provided filters must match; filters that are left unspecified are ignored.\n */\nexport interface QueryFilters<TQueryKey extends QueryKey = QueryKey> {\n /**\n * Filter to active queries, inactive queries or all queries\n * @defaultValue 'all'\n */\n type?: QueryTypeFilter\n /**\n * Match query key exactly\n */\n exact?: boolean\n /**\n * Include queries matching this predicate function\n */\n predicate?: (query: Query) => boolean\n /**\n * Include queries matching this query key\n */\n queryKey?: TQueryKey | TuplePrefixes<TQueryKey>\n /**\n * Include or exclude stale queries\n */\n stale?: boolean\n /**\n * Include queries matching their fetchStatus\n */\n fetchStatus?: FetchStatus\n}\n\n/**\n * Filters used to select mutations, for example in `mutationCache.findAll` or `queryClient.isMutating`.\n * All provided filters must match; filters that are left unspecified are ignored.\n */\nexport interface MutationFilters<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> {\n /**\n * Match mutation key exactly\n */\n exact?: boolean\n /**\n * Include mutations matching this predicate function\n */\n predicate?: (\n mutation: Mutation<TData, TError, TVariables, TOnMutateResult>,\n ) => boolean\n /**\n * Include mutations matching this mutation key\n */\n mutationKey?: TuplePrefixes<MutationKey>\n /**\n * Filter by mutation status\n */\n status?: MutationStatus\n}\n\n/**\n * Either a plain value of type `TOutput`, or a function that receives `TInput` and returns `TOutput`.\n * Used for example by `setQueryData`-style updaters, which accept either the new data directly or a\n * function that computes it from the previous data. See {@link functionalUpdate}.\n * @example\n * ```ts\n * queryClient.setQueryData(['posts'], newPosts)\n *\n * // Or, using an updater function that receives the current data:\n * queryClient.setQueryData(['posts'], (oldPosts) =>\n * oldPosts ? [...oldPosts, newPost] : oldPosts,\n * )\n * ```\n */\nexport type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)\n\n/**\n * Which queries a filter matches: all of them, only active ones (with enabled observers), or only\n * inactive ones.\n */\nexport type QueryTypeFilter = 'all' | 'active' | 'inactive'\n\n// UTILS\n\n/**\n * @deprecated use `environmentManager.isServer()` instead.\n */\nexport const isServer = typeof window === 'undefined' || 'Deno' in globalThis\n\n/**\n * A function that does nothing.\n */\nexport function noop(): void\nexport function noop(): undefined\nexport function noop() {}\n\n/**\n * Resolves an {@link Updater}: calls it with `input` if it is a function, otherwise returns it as\n * is.\n * @param updater - The new value, or a function that receives `input` and returns the new value.\n * @param input - The current value, passed to `updater` if it is a function.\n * @returns The new value.\n */\nexport function functionalUpdate<TInput, TOutput>(\n updater: Updater<TInput, TOutput>,\n input: TInput,\n): TOutput {\n return typeof updater === 'function'\n ? (updater as (_: TInput) => TOutput)(input)\n : updater\n}\n\n/**\n * Checks whether a value can be used as a timeout: a non-negative, finite number.\n * @param value - The value to check.\n * @returns `true` if `value` is a number that is `>= 0` and not `Infinity`.\n */\nexport function isValidTimeout(value: unknown): value is number {\n return typeof value === 'number' && value >= 0 && value !== Infinity\n}\n\n/**\n * Calculates how long until data updated at `updatedAt` becomes stale.\n * @param updatedAt - The timestamp, in milliseconds, at which the data was last updated.\n * @param staleTime - The time, in milliseconds, after which data is considered stale. Defaults to\n * `0`.\n * @returns The remaining time in milliseconds, or `0` if the data is already stale.\n */\nexport function timeUntilStale(updatedAt: number, staleTime?: number): number {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)\n}\n\n/**\n * Resolves an option that can be given either as a value or as a function of the query, such as\n * `staleTime`.\n * @param value - The option value, or a function that receives `query` and returns the value.\n * @param query - The query passed to `value` if it is a function.\n * @returns The resolved value, or `undefined` if `value` is `undefined`.\n */\nexport function resolveQueryValue<\n TValue,\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n value:\n | undefined\n | TValue\n | ((query: Query<TQueryFnData, TError, TData, TQueryKey>) => TValue),\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): TValue | undefined {\n return typeof value === 'function'\n ? (\n value as (\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n ) => TValue\n )(query)\n : value\n}\n\n/**\n * Checks whether a query matches the given {@link QueryFilters}.\n * Every filter that is specified must match; filters that are left unspecified are ignored.\n * @param filters - The filters to check the query against.\n * @param query - The query to check.\n * @returns `true` if the query matches every specified filter.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const matchingQueries = queryCache\n * .getAll()\n * .filter((query) => matchQuery({ queryKey: ['posts'] }, query))\n * ```\n */\nexport function matchQuery(\n filters: QueryFilters,\n query: Query<any, any, any, any>,\n): boolean {\n const {\n type = 'all',\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale,\n } = filters\n\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false\n }\n }\n\n if (type !== 'all') {\n const isActive = query.isActive()\n if (type === 'active' && !isActive) {\n return false\n }\n if (type === 'inactive' && isActive) {\n return false\n }\n }\n\n if (typeof stale === 'boolean' && query.isStale() !== stale) {\n return false\n }\n\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false\n }\n\n if (predicate && !predicate(query)) {\n return false\n }\n\n return true\n}\n\n/**\n * Checks whether a mutation matches the given {@link MutationFilters}.\n * Every filter that is specified must match; filters that are left unspecified are ignored.\n * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match.\n * @param filters - The filters to check the mutation against.\n * @param mutation - The mutation to check.\n * @returns `true` if the mutation matches every specified filter.\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const matchingMutations = mutationCache\n * .getAll()\n * .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation))\n * ```\n */\nexport function matchMutation(\n filters: MutationFilters,\n mutation: Mutation<any, any>,\n): boolean {\n const { exact, status, predicate, mutationKey } = filters\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false\n }\n }\n\n if (status && mutation.state.status !== status) {\n return false\n }\n\n if (predicate && !predicate(mutation)) {\n return false\n }\n\n return true\n}\n\n/**\n * Hashes a query key with the query's `queryKeyHashFn` option, falling back to {@link hashKey}.\n * @param queryKey - The query key to hash.\n * @param options - The query options that may provide a custom `queryKeyHashFn`.\n * @returns The query hash, a string that identifies the query in the cache.\n */\nexport function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,\n): string {\n const hashFn = options?.queryKeyHashFn || hashKey\n return hashFn(queryKey)\n}\n\n/**\n * Default query & mutation keys hash function.\n * Hashes the value into a stable hash.\n * @param queryKey - The query or mutation key to hash.\n * @returns The stable hash of the key, as a JSON string.\n * @example\n * ```ts\n * // Object keys are sorted, so key order doesn't affect the hash:\n * hashKey(['todos', { page: 1, filter: 'done' }]) // === '[\"todos\",{\"filter\":\"done\",\"page\":1}]'\n * ```\n */\nexport function hashKey(queryKey: QueryKey | MutationKey): string {\n return JSON.stringify(queryKey, (_, val) =>\n isPlainObject(val)\n ? Object.keys(val)\n .sort()\n .reduce((result, key) => {\n result[key] = val[key]\n return result\n }, {} as any)\n : val,\n )\n}\n\n/**\n * Checks if key `b` partially matches with key `a`.\n * @param a - The key to check, e.g. a query's own key.\n * @param b - The (partial) key to match against `a`.\n * @returns `true` if every array element or object property in `b` matches the one at the same\n * position in `a`.\n */\nexport function partialMatchKey(a: QueryKey, b: QueryKey): boolean\nexport function partialMatchKey(a: any, b: any): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n if (Array.isArray(a) && Array.isArray(b)) {\n if (b.length > a.length) return false\n for (let i = 0; i < b.length; i++) {\n if (!partialMatchKey(a[i], b[i])) {\n return false\n }\n }\n return true\n }\n\n const bKeys = Object.keys(b)\n for (const key of bKeys) {\n if (!partialMatchKey(a[key], b[key])) {\n return false\n }\n }\n return true\n }\n\n return false\n}\n\nconst hasOwn = Object.prototype.hasOwnProperty\n\n/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n * @param a - The previous value, whose deeply equal parts are reused.\n * @param b - The new value.\n * @param depth - The current recursion depth. Past a depth of `500`, `b` is returned as is.\n * @returns `a` if `b` is deeply equal to it, otherwise `b` with its deeply equal parts replaced by\n * those of `a`.\n */\nexport function replaceEqualDeep<T>(a: unknown, b: T, depth?: number): T\nexport function replaceEqualDeep(a: any, b: any, depth = 0): any {\n if (a === b) {\n return a\n }\n\n if (depth > 500) return b\n\n const array = isPlainArray(a) && isPlainArray(b)\n\n if (!array && !(isPlainObject(a) && isPlainObject(b))) return b\n\n const aItems = array ? a : Object.keys(a)\n const aSize = aItems.length\n const bItems = array ? b : Object.keys(b)\n const bSize = bItems.length\n const copy: any = array ? new Array(bSize) : {}\n\n let equalItems = 0\n\n for (let i = 0; i < bSize; i++) {\n const key: any = array ? i : bItems[i]\n const aItem = a[key]\n const bItem = b[key]\n\n if (aItem === bItem) {\n copy[key] = aItem\n if (array ? i < aSize : hasOwn.call(a, key)) equalItems++\n continue\n }\n\n if (\n aItem === null ||\n bItem === null ||\n typeof aItem !== 'object' ||\n typeof bItem !== 'object'\n ) {\n copy[key] = bItem\n continue\n }\n\n const v = replaceEqualDeep(aItem, bItem, depth + 1)\n copy[key] = v\n if (v === aItem) equalItems++\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy\n}\n\n/**\n * Shallow compare objects.\n * @param a - The first object.\n * @param b - The second object, or `undefined`.\n * @returns `true` if both objects have the same keys, with strictly equal values for each key.\n */\nexport function shallowEqualObjects<T extends Record<string, any>>(\n a: T,\n b: T | undefined,\n): boolean {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false\n }\n\n for (const key in a) {\n if (a[key] !== b[key]) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * Checks whether a value is an array with no holes and no extra properties.\n * @param value - The value to check.\n * @returns `true` if `value` is an array whose number of own keys equals its `length`.\n */\nexport function isPlainArray(value: unknown): value is Array<unknown> {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\n/**\n * Checks whether a value is a plain object, e.g. created with an object literal or\n * `Object.create(null)`.\n * @param o - The value to check.\n * @returns `true` if `o` is a plain object.\n */\nexport function isPlainObject(o: any): o is Record<PropertyKey, unknown> {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has no constructor\n const objectPrototype = Object.getPrototypeOf(o)\n const ctor = objectPrototype?.constructor\n if (ctor === undefined) {\n return true\n }\n\n if (typeof ctor !== 'function') {\n return false\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Handles Objects created by Object.create(<arbitrary prototype>)\n if (objectPrototype !== Object.prototype) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\n/**\n * Checks whether a value's `Object.prototype.toString` tag is `[object Object]`.\n * @param o - The value to check.\n * @returns `true` if the tag is `[object Object]`.\n */\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\n/**\n * Waits for the given time, using the configured {@link timeoutManager}.\n * @param timeout - The time to wait, in milliseconds.\n * @returns A promise that resolves after `timeout` milliseconds.\n */\nexport function sleep(timeout: number): Promise<void> {\n return new Promise((resolve) => {\n timeoutManager.setTimeout(resolve, timeout)\n })\n}\n\n/**\n * Applies a query's `structuralSharing` option when writing new data.\n * @param prevData - The previously cached data.\n * @param data - The new data.\n * @param options - The query options, whose `structuralSharing` decides how the data is merged.\n * @returns The result of a custom `structuralSharing` function, `data` with its unchanged parts\n * replaced by those of `prevData` by default, or `data` as is if `structuralSharing` is `false`.\n * @throws {Error} The error from the default structural sharing, e.g. when the data is not JSON serializable.\n * Outside production, it is also logged to the console.\n */\nexport function replaceData<\n TData,\n TOptions extends QueryOptions<any, any, any, any>,\n>(prevData: TData | undefined, data: TData, options: TOptions): TData {\n if (typeof options.structuralSharing === 'function') {\n return options.structuralSharing(prevData, data) as TData\n } else if (options.structuralSharing !== false) {\n if (process.env.NODE_ENV !== 'production') {\n try {\n return replaceEqualDeep(prevData, data)\n } catch (error) {\n console.error(\n `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`,\n )\n\n // Prevent the replaceEqualDeep from being called again down below.\n throw error\n }\n }\n // Structurally share data between prev and new data if needed\n return replaceEqualDeep(prevData, data)\n }\n return data\n}\n\n/**\n * Intended to be passed as a query's `placeholderData` option, for example\n * `placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new\n * query key is fetching, it keeps displaying the previously fetched data until the new data arrives.\n * @param previousData - The data of the previous query key, passed by the observer.\n * @returns The previous data, unchanged.\n * @example\n * ```ts\n * new QueryObserver(queryClient, {\n * queryKey: ['posts', page],\n * queryFn: () => fetchPosts(page),\n * placeholderData: keepPreviousData,\n * })\n * ```\n */\nexport function keepPreviousData<T>(\n previousData: T | undefined,\n): T | undefined {\n return previousData\n}\n\n/**\n * Returns a new array with `item` added at the end. If that makes the array longer than `max`,\n * the first item is dropped. Only one item is dropped, so the result can still exceed `max` if\n * `items` already did.\n * @param items - The current items.\n * @param item - The value to append.\n * @param max - The length above which an item is dropped. `0` (the default) means no limit.\n * @returns A new array with `item` added.\n */\nexport function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [...items, item]\n return max && newItems.length > max ? newItems.slice(1) : newItems\n}\n\n/**\n * Returns a new array with `item` added at the start. If that makes the array longer than `max`,\n * the last item is dropped. Only one item is dropped, so the result can still exceed `max` if\n * `items` already did.\n * @param items - The current items.\n * @param item - The value to prepend.\n * @param max - The length above which an item is dropped. `0` (the default) means no limit.\n * @returns A new array with `item` added.\n */\nexport function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [item, ...items]\n return max && newItems.length > max ? newItems.slice(0, -1) : newItems\n}\n\n/**\n * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent\n * to `enabled: false`) while preserving full type inference for the query's data. Unlike `enabled: false`,\n * a query disabled via `skipToken` cannot be triggered with `refetch`.\n * @example\n * ```ts\n * new QueryObserver(queryClient, {\n * queryKey: ['post', postId],\n * queryFn: postId != null ? () => fetchPost(postId) : skipToken,\n * })\n * ```\n */\nexport const skipToken = Symbol()\n/**\n * The type of the {@link skipToken} sentinel value.\n */\nexport type SkipToken = typeof skipToken\n\n/**\n * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from\n * an `initialPromise`, that promise is returned instead. If there is no usable `queryFn` (missing or\n * {@link skipToken}), the returned function rejects with a `Missing queryFn` error.\n * @param options - The query options with the `queryFn`, and the `queryHash` used in error messages.\n * @param fetchOptions - The fetch options, which may carry an `initialPromise`.\n * @returns The function to call for the fetch.\n */\nexport function ensureQueryFn<\n TQueryFnData = unknown,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: {\n queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken\n queryHash?: string\n },\n fetchOptions?: FetchOptions<TQueryFnData>,\n): QueryFunction<TQueryFnData, TQueryKey> {\n if (process.env.NODE_ENV !== 'production') {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,\n )\n }\n }\n\n // if we attempt to retry a fetch that was triggered from an initialPromise\n // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise\n // if an observer has already mounted, we will be able to retry with that queryFn\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise!\n }\n\n if (!options.queryFn || options.queryFn === skipToken) {\n return () =>\n Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))\n }\n\n return options.queryFn\n}\n\n/**\n * Resolves a `throwOnError` option to a boolean.\n * If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller,\n * additional context such as the query or mutation) and its result is returned, allowing the throwing\n * behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined`\n * resolves to `false`).\n * @param throwOnError - The `throwOnError` option: a boolean, a function that decides per error, or\n * `undefined`.\n * @param params - The arguments passed to `throwOnError` if it is a function.\n * @returns Whether the error should be thrown.\n * @example\n * ```ts\n * const throwOnError =\n * query.state.error && typeof options.throwOnError === 'function'\n * ? shouldThrowError(options.throwOnError, [query.state.error, query])\n * : options.throwOnError\n * ```\n */\nexport function shouldThrowError<T extends (...args: Array<any>) => boolean>(\n throwOnError: boolean | T | undefined,\n params: Parameters<T>,\n): boolean {\n // Allow throwOnError function to override throwing behavior on a per-error basis\n if (typeof throwOnError === 'function') {\n return throwOnError(...params)\n }\n\n return !!throwOnError\n}\n\n/**\n * Adds a lazy `signal` getter to an object, such as a query function context. The first time\n * `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right\n * away if it is already aborted), so cancellation is only tracked when the signal is actually used.\n * @param object - The object to add the `signal` property to.\n * @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read.\n * @param onCancelled - Called when the signal is aborted, if `signal` was read.\n * @returns The same object, with the `signal` property added.\n */\nexport function addConsumeAwareSignal<T>(\n object: T,\n getSignal: () => AbortSignal,\n onCancelled: VoidFunction,\n): T & { signal: AbortSignal } {\n let consumed = false\n let signal: AbortSignal | undefined\n\n Object.defineProperty(object, 'signal', {\n enumerable: true,\n get: () => {\n signal ??= getSignal()\n if (consumed) {\n return signal\n }\n\n consumed = true\n if (signal.aborted) {\n onCancelled()\n } else {\n signal.addEventListener('abort', onCancelled, { once: true })\n }\n\n return signal\n },\n })\n\n return object as T & { signal: AbortSignal }\n}\n"],"mappings":";;;;;AAmHA,MAAa,WAAW,OAAO,WAAW,eAAe,UAAU;AAOnE,SAAgB,OAAO,CAAC;;;;;;;;AASxB,SAAgB,iBACd,SACA,OACS;CACT,OAAO,OAAO,YAAY,aACrB,QAAmC,KAAK,IACzC;AACN;;;;;;AAOA,SAAgB,eAAe,OAAiC;CAC9D,OAAO,OAAO,UAAU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MAAA,QAAQ,YAAY,WACtB,QAAQ,MACN,yGAAyG,QAAQ,UAAU,EAC7H;CAAA;CAOJ,IAAI,CAAC,QAAQ,WAAW,cAAc,gBACpC,aAAa,aAAa;CAG5B,IAAI,CAAC,QAAQ,WAAW,QAAQ,YAAY,WAC1C,aACE,QAAQ,uBAAO,IAAI,MAAM,qBAAqB,QAAQ,UAAU,EAAE,CAAC;CAGvE,OAAO,QAAQ;AACjB;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,iBACd,cACA,QACS;CAET,IAAI,OAAO,iBAAiB,YAC1B,OAAO,aAAa,GAAG,MAAM;CAG/B,OAAO,CAAC,CAAC;AACX;;;;;;;;;;AAWA,SAAgB,sBACd,QACA,WACA,aAC6B;CAC7B,IAAI,WAAW;CACf,IAAI;CAEJ,OAAO,eAAe,QAAQ,UAAU;EACtC,YAAY;EACZ,WAAW;GACT,WAAW,UAAU;GACrB,IAAI,UACF,OAAO;GAGT,WAAW;GACX,IAAI,OAAO,SACT,YAAY;QAEZ,OAAO,iBAAiB,SAAS,aAAa,EAAE,MAAM,KAAK,CAAC;GAG9D,OAAO;EACT;CACF,CAAC;CAED,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../src/utils.ts"],"sourcesContent":["import { timeoutManager } from './timeoutManager'\nimport type {\n DefaultError,\n FetchStatus,\n MutationKey,\n MutationStatus,\n QueryFunction,\n QueryKey,\n QueryOptions,\n} from './types'\nimport type { Mutation } from './mutation'\nimport type { FetchOptions, Query } from './query'\n\n// TYPES\n\ntype DropLast<T extends ReadonlyArray<unknown>> = T extends readonly [\n ...infer R,\n unknown,\n]\n ? readonly [...R]\n : never\n\ntype TuplePrefixes<T extends ReadonlyArray<unknown>> = T extends readonly []\n ? readonly []\n : TuplePrefixes<DropLast<T>> | T\n\n/**\n * Filters used to select queries, for example in `queryClient.getQueriesData` or `queryClient.invalidateQueries`.\n * All provided filters must match; filters that are left unspecified are ignored.\n */\nexport interface QueryFilters<TQueryKey extends QueryKey = QueryKey> {\n /**\n * Filter to active queries, inactive queries or all queries\n * @defaultValue 'all'\n */\n type?: QueryTypeFilter\n /**\n * Match query key exactly\n */\n exact?: boolean\n /**\n * Include queries matching this predicate function\n */\n predicate?: (query: Query) => boolean\n /**\n * Include queries matching this query key\n */\n queryKey?: TQueryKey | TuplePrefixes<TQueryKey>\n /**\n * Include or exclude stale queries\n */\n stale?: boolean\n /**\n * Include queries matching their fetchStatus\n */\n fetchStatus?: FetchStatus\n}\n\n/**\n * Filters used to select mutations, for example in `mutationCache.findAll` or `queryClient.isMutating`.\n * All provided filters must match; filters that are left unspecified are ignored.\n */\nexport interface MutationFilters<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> {\n /**\n * Match mutation key exactly\n */\n exact?: boolean\n /**\n * Include mutations matching this predicate function\n */\n predicate?: (\n mutation: Mutation<TData, TError, TVariables, TOnMutateResult>,\n ) => boolean\n /**\n * Include mutations matching this mutation key\n */\n mutationKey?: TuplePrefixes<MutationKey>\n /**\n * Filter by mutation status\n */\n status?: MutationStatus\n}\n\n/**\n * Either a plain value of type `TOutput`, or a function that receives `TInput` and returns `TOutput`.\n * Used for example by `setQueryData`-style updaters, which accept either the new data directly or a\n * function that computes it from the previous data. See {@link functionalUpdate}.\n * @example\n * ```ts\n * queryClient.setQueryData(['posts'], newPosts)\n *\n * // Or, using an updater function that receives the current data:\n * queryClient.setQueryData(['posts'], (oldPosts) =>\n * oldPosts ? [...oldPosts, newPost] : oldPosts,\n * )\n * ```\n */\nexport type Updater<TInput, TOutput> = TOutput | ((input: TInput) => TOutput)\n\n/**\n * Which queries a filter matches: all of them, only active ones (with enabled observers), or only\n * inactive ones.\n */\nexport type QueryTypeFilter = 'all' | 'active' | 'inactive'\n\n// UTILS\n\n/**\n * @deprecated use `environmentManager.isServer()` instead.\n */\nexport const isServer = typeof window === 'undefined' || 'Deno' in globalThis\n\n/**\n * A function that does nothing.\n */\nexport function noop(): void\nexport function noop(): undefined\nexport function noop() {}\n\n/**\n * Resolves an {@link Updater}: calls it with `input` if it is a function, otherwise returns it as\n * is.\n * @param updater - The new value, or a function that receives `input` and returns the new value.\n * @param input - The current value, passed to `updater` if it is a function.\n * @returns The new value.\n */\nexport function functionalUpdate<TInput, TOutput>(\n updater: Updater<TInput, TOutput>,\n input: TInput,\n): TOutput {\n return typeof updater === 'function'\n ? (updater as (_: TInput) => TOutput)(input)\n : updater\n}\n\n/**\n * Checks whether a value can be used as a timeout: a non-negative, finite number.\n * @param value - The value to check.\n * @returns `true` if `value` is a number that is `>= 0` and not `Infinity`.\n */\nexport function isValidTimeout(value: unknown): value is number {\n return typeof value === 'number' && value >= 0 && value !== Infinity\n}\n\n/**\n * Calculates how long until data updated at `updatedAt` becomes stale.\n * @param updatedAt - The timestamp, in milliseconds, at which the data was last updated.\n * @param staleTime - The time, in milliseconds, after which data is considered stale. Defaults to\n * `0`.\n * @returns The remaining time in milliseconds, or `0` if the data is already stale.\n */\nexport function timeUntilStale(updatedAt: number, staleTime?: number): number {\n return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0)\n}\n\n/**\n * Resolves an option that can be given either as a value or as a function of the query, such as\n * `staleTime`.\n * @param value - The option value, or a function that receives `query` and returns the value.\n * @param query - The query passed to `value` if it is a function.\n * @returns The resolved value, or `undefined` if `value` is `undefined`.\n */\nexport function resolveQueryValue<\n TValue,\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n value:\n | undefined\n | TValue\n | ((query: Query<TQueryFnData, TError, TData, TQueryKey>) => TValue),\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n): TValue | undefined {\n return typeof value === 'function'\n ? (\n value as (\n query: Query<TQueryFnData, TError, TData, TQueryKey>,\n ) => TValue\n )(query)\n : value\n}\n\n/**\n * Checks whether a query matches the given {@link QueryFilters}.\n * Every filter that is specified must match; filters that are left unspecified are ignored.\n * @param filters - The filters to check the query against.\n * @param query - The query to check.\n * @returns `true` if the query matches every specified filter.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const matchingQueries = queryCache\n * .getAll()\n * .filter((query) => matchQuery({ queryKey: ['posts'] }, query))\n * ```\n */\nexport function matchQuery(\n filters: QueryFilters,\n query: Query<any, any, any, any>,\n): boolean {\n const {\n type = 'all',\n exact,\n fetchStatus,\n predicate,\n queryKey,\n stale,\n } = filters\n\n if (queryKey) {\n if (exact) {\n if (query.queryHash !== hashQueryKeyByOptions(queryKey, query.options)) {\n return false\n }\n } else if (!partialMatchKey(query.queryKey, queryKey)) {\n return false\n }\n }\n\n if (type !== 'all') {\n const isActive = query.isActive()\n if (type === 'active' && !isActive) {\n return false\n }\n if (type === 'inactive' && isActive) {\n return false\n }\n }\n\n if (typeof stale === 'boolean' && query.isStale() !== stale) {\n return false\n }\n\n if (fetchStatus && fetchStatus !== query.state.fetchStatus) {\n return false\n }\n\n if (predicate && !predicate(query)) {\n return false\n }\n\n return true\n}\n\n/**\n * Checks whether a mutation matches the given {@link MutationFilters}.\n * Every filter that is specified must match; filters that are left unspecified are ignored.\n * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match.\n * @param filters - The filters to check the mutation against.\n * @param mutation - The mutation to check.\n * @returns `true` if the mutation matches every specified filter.\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const matchingMutations = mutationCache\n * .getAll()\n * .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation))\n * ```\n */\nexport function matchMutation(\n filters: MutationFilters,\n mutation: Mutation<any, any>,\n): boolean {\n const { exact, status, predicate, mutationKey } = filters\n if (mutationKey) {\n if (!mutation.options.mutationKey) {\n return false\n }\n if (exact) {\n if (hashKey(mutation.options.mutationKey) !== hashKey(mutationKey)) {\n return false\n }\n } else if (!partialMatchKey(mutation.options.mutationKey, mutationKey)) {\n return false\n }\n }\n\n if (status && mutation.state.status !== status) {\n return false\n }\n\n if (predicate && !predicate(mutation)) {\n return false\n }\n\n return true\n}\n\n/**\n * Hashes a query key with the query's `queryKeyHashFn` option, falling back to {@link hashKey}.\n * @param queryKey - The query key to hash.\n * @param options - The query options that may provide a custom `queryKeyHashFn`.\n * @returns The query hash, a string that identifies the query in the cache.\n */\nexport function hashQueryKeyByOptions<TQueryKey extends QueryKey = QueryKey>(\n queryKey: TQueryKey,\n options?: Pick<QueryOptions<any, any, any, any>, 'queryKeyHashFn'>,\n): string {\n const hashFn = options?.queryKeyHashFn || hashKey\n return hashFn(queryKey)\n}\n\n/**\n * Default query & mutation keys hash function.\n * Hashes the value into a stable hash.\n * @param queryKey - The query or mutation key to hash.\n * @returns The stable hash of the key, as a JSON string.\n * @example\n * ```ts\n * // Object keys are sorted, so key order doesn't affect the hash:\n * hashKey(['todos', { page: 1, filter: 'done' }]) // === '[\"todos\",{\"filter\":\"done\",\"page\":1}]'\n * ```\n */\nexport function hashKey(queryKey: QueryKey | MutationKey): string {\n return JSON.stringify(queryKey, (_, val) =>\n isPlainObject(val)\n ? Object.keys(val)\n .sort()\n .reduce((result, key) => {\n result[key] = val[key]\n return result\n }, {} as any)\n : val,\n )\n}\n\n/**\n * Checks if key `b` partially matches with key `a`.\n * @param a - The key to check, e.g. a query's own key.\n * @param b - The (partial) key to match against `a`.\n * @returns `true` if every array element or object property in `b` matches the one at the same\n * position in `a`.\n */\nexport function partialMatchKey(a: QueryKey, b: QueryKey): boolean\nexport function partialMatchKey(a: any, b: any): boolean {\n if (a === b) {\n return true\n }\n\n if (typeof a !== typeof b) {\n return false\n }\n\n if (a && b && typeof a === 'object' && typeof b === 'object') {\n if (Array.isArray(a) && Array.isArray(b)) {\n if (b.length > a.length) return false\n for (let i = 0; i < b.length; i++) {\n if (!partialMatchKey(a[i], b[i])) {\n return false\n }\n }\n return true\n }\n\n const bKeys = Object.keys(b)\n for (const key of bKeys) {\n if (!partialMatchKey(a[key], b[key])) {\n return false\n }\n }\n return true\n }\n\n return false\n}\n\nconst hasOwn = Object.prototype.hasOwnProperty\n\n/**\n * This function returns `a` if `b` is deeply equal.\n * If not, it will replace any deeply equal children of `b` with those of `a`.\n * This can be used for structural sharing between JSON values for example.\n * @param a - The previous value, whose deeply equal parts are reused.\n * @param b - The new value.\n * @param depth - The current recursion depth. Past a depth of `500`, `b` is returned as is.\n * @returns `a` if `b` is deeply equal to it, otherwise `b` with its deeply equal parts replaced by\n * those of `a`.\n */\nexport function replaceEqualDeep<T>(a: unknown, b: T, depth?: number): T\nexport function replaceEqualDeep(a: any, b: any, depth = 0): any {\n if (a === b) {\n return a\n }\n\n if (depth > 500) return b\n\n const array = isPlainArray(a) && isPlainArray(b)\n\n if (!array && !(isPlainObject(a) && isPlainObject(b))) return b\n\n const aItems = array ? a : Object.keys(a)\n const aSize = aItems.length\n const bItems = array ? b : Object.keys(b)\n const bSize = bItems.length\n const copy: any = array ? new Array(bSize) : {}\n\n let equalItems = 0\n\n for (let i = 0; i < bSize; i++) {\n const key: any = array ? i : bItems[i]\n const aItem = a[key]\n const bItem = b[key]\n\n if (aItem === bItem) {\n copy[key] = aItem\n if (array ? i < aSize : hasOwn.call(a, key)) equalItems++\n continue\n }\n\n if (\n aItem === null ||\n bItem === null ||\n typeof aItem !== 'object' ||\n typeof bItem !== 'object'\n ) {\n copy[key] = bItem\n continue\n }\n\n const v = replaceEqualDeep(aItem, bItem, depth + 1)\n copy[key] = v\n if (v === aItem) equalItems++\n }\n\n return aSize === bSize && equalItems === aSize ? a : copy\n}\n\n/**\n * Shallow compare objects.\n * @param a - The first object.\n * @param b - The second object, or `undefined`.\n * @returns `true` if both objects have the same keys, with strictly equal values for each key.\n */\nexport function shallowEqualObjects<T extends Record<string, any>>(\n a: T,\n b: T | undefined,\n): boolean {\n if (!b || Object.keys(a).length !== Object.keys(b).length) {\n return false\n }\n\n for (const key of Object.keys(a)) {\n if (!hasOwn.call(b, key) || a[key] !== b[key]) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * Checks whether a value is an array with no holes and no extra properties.\n * @param value - The value to check.\n * @returns `true` if `value` is an array whose number of own keys equals its `length`.\n */\nexport function isPlainArray(value: unknown): value is Array<unknown> {\n return Array.isArray(value) && value.length === Object.keys(value).length\n}\n\n// Copied from: https://github.com/jonschlinkert/is-plain-object\n/**\n * Checks whether a value is a plain object, e.g. created with an object literal or\n * `Object.create(null)`.\n * @param o - The value to check.\n * @returns `true` if `o` is a plain object.\n */\nexport function isPlainObject(o: any): o is Record<PropertyKey, unknown> {\n if (!hasObjectPrototype(o)) {\n return false\n }\n\n // If has no constructor\n const objectPrototype = Object.getPrototypeOf(o)\n const ctor = objectPrototype?.constructor\n if (ctor === undefined) {\n return true\n }\n\n if (typeof ctor !== 'function') {\n return false\n }\n\n // If has modified prototype\n const prot = ctor.prototype\n if (!hasObjectPrototype(prot)) {\n return false\n }\n\n // If constructor does not have an Object-specific method\n if (!prot.hasOwnProperty('isPrototypeOf')) {\n return false\n }\n\n // Handles Objects created by Object.create(<arbitrary prototype>)\n if (objectPrototype !== Object.prototype) {\n return false\n }\n\n // Most likely a plain Object\n return true\n}\n\n/**\n * Checks whether a value's `Object.prototype.toString` tag is `[object Object]`.\n * @param o - The value to check.\n * @returns `true` if the tag is `[object Object]`.\n */\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === '[object Object]'\n}\n\n/**\n * Waits for the given time, using the configured {@link timeoutManager}.\n * @param timeout - The time to wait, in milliseconds.\n * @returns A promise that resolves after `timeout` milliseconds.\n */\nexport function sleep(timeout: number): Promise<void> {\n return new Promise((resolve) => {\n timeoutManager.setTimeout(resolve, timeout)\n })\n}\n\n/**\n * Applies a query's `structuralSharing` option when writing new data.\n * @param prevData - The previously cached data.\n * @param data - The new data.\n * @param options - The query options, whose `structuralSharing` decides how the data is merged.\n * @returns The result of a custom `structuralSharing` function, `data` with its unchanged parts\n * replaced by those of `prevData` by default, or `data` as is if `structuralSharing` is `false`.\n * @throws {Error} The error from the default structural sharing, e.g. when the data is not JSON serializable.\n * Outside production, it is also logged to the console.\n */\nexport function replaceData<\n TData,\n TOptions extends QueryOptions<any, any, any, any>,\n>(prevData: TData | undefined, data: TData, options: TOptions): TData {\n if (typeof options.structuralSharing === 'function') {\n return options.structuralSharing(prevData, data) as TData\n } else if (options.structuralSharing !== false) {\n if (process.env.NODE_ENV !== 'production') {\n try {\n return replaceEqualDeep(prevData, data)\n } catch (error) {\n console.error(\n `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`,\n )\n\n // Prevent the replaceEqualDeep from being called again down below.\n throw error\n }\n }\n // Structurally share data between prev and new data if needed\n return replaceEqualDeep(prevData, data)\n }\n return data\n}\n\n/**\n * Intended to be passed as a query's `placeholderData` option, for example\n * `placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new\n * query key is fetching, it keeps displaying the previously fetched data until the new data arrives.\n * @param previousData - The data of the previous query key, passed by the observer.\n * @returns The previous data, unchanged.\n * @example\n * ```ts\n * new QueryObserver(queryClient, {\n * queryKey: ['posts', page],\n * queryFn: () => fetchPosts(page),\n * placeholderData: keepPreviousData,\n * })\n * ```\n */\nexport function keepPreviousData<T>(\n previousData: T | undefined,\n): T | undefined {\n return previousData\n}\n\n/**\n * Returns a new array with `item` added at the end. If that makes the array longer than `max`,\n * excess items are removed from the start.\n * @param items - The current items.\n * @param item - The value to append.\n * @param max - The maximum number of items to keep. `0` (the default) means no limit.\n * @returns A new array with `item` added.\n */\nexport function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [...items, item]\n return max && newItems.length > max ? newItems.slice(-max) : newItems\n}\n\n/**\n * Returns a new array with `item` added at the start. If that makes the array longer than `max`,\n * excess items are removed from the end.\n * @param items - The current items.\n * @param item - The value to prepend.\n * @param max - The maximum number of items to keep. `0` (the default) means no limit.\n * @returns A new array with `item` added.\n */\nexport function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n const newItems = [item, ...items]\n return max && newItems.length > max ? newItems.slice(0, max) : newItems\n}\n\n/**\n * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent\n * to `enabled: false`) while preserving full type inference for the query's data. Unlike `enabled: false`,\n * a query disabled via `skipToken` cannot be triggered with `refetch`.\n * @example\n * ```ts\n * new QueryObserver(queryClient, {\n * queryKey: ['post', postId],\n * queryFn: postId != null ? () => fetchPost(postId) : skipToken,\n * })\n * ```\n */\nexport const skipToken = Symbol()\n/**\n * The type of the {@link skipToken} sentinel value.\n */\nexport type SkipToken = typeof skipToken\n\n/**\n * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from\n * an `initialPromise`, that promise is returned instead. If there is no usable `queryFn` (missing or\n * {@link skipToken}), the returned function rejects with a `Missing queryFn` error.\n * @param options - The query options with the `queryFn`, and the `queryHash` used in error messages.\n * @param fetchOptions - The fetch options, which may carry an `initialPromise`.\n * @returns The function to call for the fetch.\n */\nexport function ensureQueryFn<\n TQueryFnData = unknown,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: {\n queryFn?: QueryFunction<TQueryFnData, TQueryKey> | SkipToken\n queryHash?: string\n },\n fetchOptions?: FetchOptions<TQueryFnData>,\n): QueryFunction<TQueryFnData, TQueryKey> {\n if (process.env.NODE_ENV !== 'production') {\n if (options.queryFn === skipToken) {\n console.error(\n `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`,\n )\n }\n }\n\n // if we attempt to retry a fetch that was triggered from an initialPromise\n // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise\n // if an observer has already mounted, we will be able to retry with that queryFn\n if (!options.queryFn && fetchOptions?.initialPromise) {\n return () => fetchOptions.initialPromise!\n }\n\n if (!options.queryFn || options.queryFn === skipToken) {\n return () =>\n Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`))\n }\n\n return options.queryFn\n}\n\n/**\n * Resolves a `throwOnError` option to a boolean.\n * If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller,\n * additional context such as the query or mutation) and its result is returned, allowing the throwing\n * behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined`\n * resolves to `false`).\n * @param throwOnError - The `throwOnError` option: a boolean, a function that decides per error, or\n * `undefined`.\n * @param params - The arguments passed to `throwOnError` if it is a function.\n * @returns Whether the error should be thrown.\n * @example\n * ```ts\n * const throwOnError =\n * query.state.error && typeof options.throwOnError === 'function'\n * ? shouldThrowError(options.throwOnError, [query.state.error, query])\n * : options.throwOnError\n * ```\n */\nexport function shouldThrowError<T extends (...args: Array<any>) => boolean>(\n throwOnError: boolean | T | undefined,\n params: Parameters<T>,\n): boolean {\n // Allow throwOnError function to override throwing behavior on a per-error basis\n if (typeof throwOnError === 'function') {\n return throwOnError(...params)\n }\n\n return !!throwOnError\n}\n\nexport const fetchSignal = Symbol()\n\n/** Internal view of a context that can expose its signal without consuming it. */\nexport type FetchSignalContext = {\n /** The public signal, whose getter can mark it consumed. */\n readonly signal: AbortSignal\n /** The original fetch signal, absent on application-created contexts. */\n readonly [fetchSignal]?: AbortSignal\n}\n\n/**\n * Adds a lazy `signal` getter to an object, such as a query function context. The first time\n * `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right\n * away if it is already aborted), so cancellation is only tracked when the signal is actually used.\n * @param object - The object to add the `signal` property to.\n * @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read.\n * @param onCancelled - Called when the signal is aborted, if `signal` was read.\n * @param internalSignal - The fetch signal to forward without consuming the getter.\n * @returns The same object, with the `signal` property added.\n */\nexport function addConsumeAwareSignal<T extends object>(\n object: T,\n getSignal: () => AbortSignal,\n onCancelled: () => void,\n internalSignal?: AbortSignal,\n): T & { signal: AbortSignal } {\n let consumed = false\n let signal: AbortSignal | undefined\n\n Object.defineProperties(object, {\n [fetchSignal]: { value: internalSignal },\n signal: {\n enumerable: true,\n get: () => {\n signal ??= getSignal()\n if (consumed) {\n return signal\n }\n\n consumed = true\n if (signal.aborted) {\n onCancelled()\n } else {\n signal.addEventListener('abort', onCancelled, { once: true })\n }\n\n return signal\n },\n },\n })\n\n return object as T & { signal: AbortSignal }\n}\n"],"mappings":";;;;;AAmHA,MAAa,WAAW,OAAO,WAAW,eAAe,UAAU;AAOnE,SAAgB,OAAO,CAAC;;;;;;;;AASxB,SAAgB,iBACd,SACA,OACS;CACT,OAAO,OAAO,YAAY,aACrB,QAAmC,KAAK,IACzC;AACN;;;;;;AAOA,SAAgB,eAAe,OAAiC;CAC9D,OAAO,OAAO,UAAU,YAAY,SAAS,KAAK,UAAU;AAC9D;;;;;;;;AASA,SAAgB,eAAe,WAAmB,WAA4B;CAC5E,OAAO,KAAK,IAAI,aAAa,aAAa,KAAK,KAAK,IAAI,GAAG,CAAC;AAC9D;;;;;;;;AASA,SAAgB,kBAOd,OAIA,OACoB;CACpB,OAAO,OAAO,UAAU,aAElB,MAGA,KAAK,IACP;AACN;;;;;;;;;;;;;;;;AAiBA,SAAgB,WACd,SACA,OACS;CACT,MAAM,EACJ,OAAO,OACP,OACA,aACA,WACA,UACA,UACE;CAEJ,IAAI,UAAU;EACZ,IAAI,OACE;OAAA,MAAM,cAAc,sBAAsB,UAAU,MAAM,OAAO,GACnE,OAAO;EAAA,OAEJ,IAAI,CAAC,gBAAgB,MAAM,UAAU,QAAQ,GAClD,OAAO;CAEX;CAEA,IAAI,SAAS,OAAO;EAClB,MAAM,WAAW,MAAM,SAAS;EAChC,IAAI,SAAS,YAAY,CAAC,UACxB,OAAO;EAET,IAAI,SAAS,cAAc,UACzB,OAAO;CAEX;CAEA,IAAI,OAAO,UAAU,aAAa,MAAM,QAAQ,MAAM,OACpD,OAAO;CAGT,IAAI,eAAe,gBAAgB,MAAM,MAAM,aAC7C,OAAO;CAGT,IAAI,aAAa,CAAC,UAAU,KAAK,GAC/B,OAAO;CAGT,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,SAAgB,cACd,SACA,UACS;CACT,MAAM,EAAE,OAAO,QAAQ,W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+3,9 @@ import {
|
|
|
3
3
|
addToEnd,
|
|
4
4
|
addToStart,
|
|
5
5
|
ensureQueryFn,
|
|
6
|
+
fetchSignal,
|
|
6
7
|
} from './utils'
|
|
8
|
+
import type { FetchSignalContext } from './utils'
|
|
7
9
|
import type { QueryBehavior } from './query'
|
|
8
10
|
import type {
|
|
9
11
|
InfiniteData,
|
|
@@ -35,11 +37,13 @@ export function infiniteQueryBehavior<TQueryFnData, TError, TData, TPageParam>(
|
|
|
35
37
|
|
|
36
38
|
const fetchFn = async () => {
|
|
37
39
|
let cancelled = false
|
|
38
|
-
const
|
|
40
|
+
const signalContext: FetchSignalContext = context
|
|
41
|
+
const addSignalProperty = (object: object) => {
|
|
39
42
|
addConsumeAwareSignal(
|
|
40
43
|
object,
|
|
41
44
|
() => context.signal,
|
|
42
45
|
() => (cancelled = true),
|
|
46
|
+
signalContext[fetchSignal],
|
|
43
47
|
)
|
|
44
48
|
}
|
|
45
49
|
|
package/src/mutation.ts
CHANGED
|
@@ -360,6 +360,10 @@ export class Mutation<
|
|
|
360
360
|
})
|
|
361
361
|
}
|
|
362
362
|
}
|
|
363
|
+
// Unpause a mutation that became able to start while onMutate was running
|
|
364
|
+
if (this.state.isPaused && retryer.canStart()) {
|
|
365
|
+
onContinue()
|
|
366
|
+
}
|
|
363
367
|
const data = await retryer.start()
|
|
364
368
|
|
|
365
369
|
// Notify cache callback
|
package/src/query.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
ensureQueryFn,
|
|
3
|
+
fetchSignal,
|
|
3
4
|
noop,
|
|
4
5
|
replaceData,
|
|
5
6
|
resolveQueryValue,
|
|
@@ -297,6 +298,7 @@ export class Query<
|
|
|
297
298
|
#cache: QueryCache
|
|
298
299
|
#client: QueryClient
|
|
299
300
|
#retryer?: Retryer<TData>
|
|
301
|
+
#fetchPromise?: Promise<TData>
|
|
300
302
|
observers: Array<QueryObserver<any, any, any, any, any>>
|
|
301
303
|
#defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
|
|
302
304
|
#abortSignalConsumed: boolean
|
|
@@ -714,11 +716,11 @@ export class Query<
|
|
|
714
716
|
if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {
|
|
715
717
|
// Silently cancel current fetch if the user wants to cancel refetch
|
|
716
718
|
this.cancel({ silent: true })
|
|
717
|
-
} else if (this.#retryer) {
|
|
719
|
+
} else if (this.#retryer && this.#fetchPromise) {
|
|
718
720
|
// make sure that retries that were potentially cancelled due to unmounts can continue
|
|
719
721
|
this.#retryer.continueRetry()
|
|
720
722
|
// Return current promise if we are already fetching
|
|
721
|
-
return this.#
|
|
723
|
+
return this.#fetchPromise
|
|
722
724
|
}
|
|
723
725
|
}
|
|
724
726
|
|
|
@@ -749,12 +751,15 @@ export class Query<
|
|
|
749
751
|
// Adds an enumerable signal property to the object that
|
|
750
752
|
// which sets abortSignalConsumed to true when the signal
|
|
751
753
|
// is read.
|
|
752
|
-
const addSignalProperty = (object:
|
|
753
|
-
Object.
|
|
754
|
-
enumerable: true,
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
754
|
+
const addSignalProperty = (object: object) => {
|
|
755
|
+
Object.defineProperties(object, {
|
|
756
|
+
[fetchSignal]: { value: abortController.signal, enumerable: true },
|
|
757
|
+
signal: {
|
|
758
|
+
enumerable: true,
|
|
759
|
+
get: () => {
|
|
760
|
+
this.#abortSignalConsumed = true
|
|
761
|
+
return abortController.signal
|
|
762
|
+
},
|
|
758
763
|
},
|
|
759
764
|
})
|
|
760
765
|
}
|
|
@@ -865,70 +870,79 @@ export class Query<
|
|
|
865
870
|
canRun: () => true,
|
|
866
871
|
}))
|
|
867
872
|
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
if (
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
873
|
+
const fetchPromise = (async () => {
|
|
874
|
+
try {
|
|
875
|
+
const data = await retryer.promise
|
|
876
|
+
// this is more of a runtime guard
|
|
877
|
+
if (data === undefined) {
|
|
878
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
879
|
+
console.error(
|
|
880
|
+
`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,
|
|
881
|
+
)
|
|
882
|
+
}
|
|
883
|
+
throw new Error(`${this.queryHash} data is undefined`)
|
|
876
884
|
}
|
|
877
|
-
throw new Error(`${this.queryHash} data is undefined`)
|
|
878
|
-
}
|
|
879
885
|
|
|
880
|
-
|
|
886
|
+
this.setData(data)
|
|
881
887
|
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
// if the initial fetch was cancelled, we have no data, so we have
|
|
899
|
-
// to get reject with a CancelledError
|
|
900
|
-
if (this.state.data === undefined) {
|
|
888
|
+
// Notify cache callback
|
|
889
|
+
this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
|
|
890
|
+
this.#cache.config.onSettled?.(
|
|
891
|
+
data,
|
|
892
|
+
this.state.error as any,
|
|
893
|
+
this as Query<any, any, any, any>,
|
|
894
|
+
)
|
|
895
|
+
return data
|
|
896
|
+
} catch (error) {
|
|
897
|
+
if (error instanceof CancelledError) {
|
|
898
|
+
if (error.silent) {
|
|
899
|
+
if (this.#retryer !== retryer && this.#fetchPromise) {
|
|
900
|
+
// A new fetch replaced the silently cancelled one,
|
|
901
|
+
// so we piggyback onto that promise.
|
|
902
|
+
return this.#fetchPromise
|
|
903
|
+
}
|
|
901
904
|
throw error
|
|
905
|
+
} else if (error.revert) {
|
|
906
|
+
// transform error into reverted state data
|
|
907
|
+
// if the initial fetch was cancelled, we have no data, so we have
|
|
908
|
+
// to get reject with a CancelledError
|
|
909
|
+
if (this.state.data === undefined) {
|
|
910
|
+
throw error
|
|
911
|
+
}
|
|
912
|
+
return this.state.data
|
|
902
913
|
}
|
|
903
|
-
return this.state.data
|
|
904
914
|
}
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
)
|
|
915
|
+
this.#dispatch({
|
|
916
|
+
type: 'error',
|
|
917
|
+
error: error as TError,
|
|
918
|
+
})
|
|
919
|
+
|
|
920
|
+
// Notify cache callback
|
|
921
|
+
this.#cache.config.onError?.(
|
|
922
|
+
error as any,
|
|
923
|
+
this as Query<any, any, any, any>,
|
|
924
|
+
)
|
|
925
|
+
this.#cache.config.onSettled?.(
|
|
926
|
+
this.state.data,
|
|
927
|
+
error as any,
|
|
928
|
+
this as Query<any, any, any, any>,
|
|
929
|
+
)
|
|
921
930
|
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
931
|
+
throw error // rethrow the error for further handling
|
|
932
|
+
} finally {
|
|
933
|
+
// The settled retryer's promise would otherwise pin this fetch's raw
|
|
934
|
+
// result (a second copy after structural sharing) for the query's lifetime
|
|
935
|
+
if (this.#retryer === retryer) {
|
|
936
|
+
this.#retryer = undefined
|
|
937
|
+
this.#fetchPromise = undefined
|
|
938
|
+
}
|
|
939
|
+
// Schedule query gc after fetching
|
|
940
|
+
this.scheduleGc()
|
|
928
941
|
}
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
942
|
+
})()
|
|
943
|
+
this.#fetchPromise = fetchPromise
|
|
944
|
+
retryer.start()
|
|
945
|
+
return fetchPromise
|
|
932
946
|
}
|
|
933
947
|
|
|
934
948
|
#dispatch(action: Action<TData, TError>): void {
|
package/src/queryClient.ts
CHANGED
|
@@ -167,8 +167,11 @@ export class QueryClient {
|
|
|
167
167
|
* ```
|
|
168
168
|
*/
|
|
169
169
|
isMutating<
|
|
170
|
-
TMutationFilters extends MutationFilters<any, any> = MutationFilters
|
|
171
|
-
|
|
170
|
+
TMutationFilters extends MutationFilters<any, any> = MutationFilters<
|
|
171
|
+
any,
|
|
172
|
+
any
|
|
173
|
+
>,
|
|
174
|
+
>(filters?: NoInfer<Omit<TMutationFilters, 'status'>>): number {
|
|
172
175
|
return this.#mutationCache.findAll({ ...filters, status: 'pending' }).length
|
|
173
176
|
}
|
|
174
177
|
|
|
@@ -517,13 +520,17 @@ export class QueryClient {
|
|
|
517
520
|
* have observers with a static `staleTime`), are never refetched.
|
|
518
521
|
*
|
|
519
522
|
* By default (`cancelRefetch: true`), a currently running fetch is cancelled before the new
|
|
520
|
-
* one starts. The returned promise
|
|
521
|
-
*
|
|
523
|
+
* one starts. The returned promise does not reject on individual query failures unless
|
|
524
|
+
* `throwOnError` is `true`.
|
|
525
|
+
*
|
|
526
|
+
* Initially paused fetches do not delay the returned promise. Their later errors are handled
|
|
527
|
+
* even when `throwOnError` is `true`.
|
|
522
528
|
* @param filters - The filters that select which queries to refetch. Without filters, every query
|
|
523
529
|
* in the cache is included.
|
|
524
530
|
* @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling
|
|
525
|
-
* it, and `throwOnError` to `true` to reject when a refetch fails.
|
|
526
|
-
* @returns A promise that resolves once
|
|
531
|
+
* it, and `throwOnError` to `true` to reject when a refetch that was not initially paused fails.
|
|
532
|
+
* @returns A promise that resolves once all matching refetches that were not initially paused
|
|
533
|
+
* have settled.
|
|
527
534
|
* @example
|
|
528
535
|
* ```ts
|
|
529
536
|
* // refetch all active queries partially matching a query key:
|
|
@@ -544,12 +551,11 @@ export class QueryClient {
|
|
|
544
551
|
.filter((query) => !query.isDisabled() && !query.isStatic())
|
|
545
552
|
.map((query) => {
|
|
546
553
|
let promise = query.fetch(undefined, fetchOptions)
|
|
547
|
-
|
|
554
|
+
const isPaused = query.state.fetchStatus === 'paused'
|
|
555
|
+
if (!fetchOptions.throwOnError || isPaused) {
|
|
548
556
|
promise = promise.catch(noop)
|
|
549
557
|
}
|
|
550
|
-
return
|
|
551
|
-
? Promise.resolve()
|
|
552
|
-
: promise
|
|
558
|
+
return isPaused ? Promise.resolve() : promise
|
|
553
559
|
}),
|
|
554
560
|
)
|
|
555
561
|
|
package/src/streamedQuery.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { addConsumeAwareSignal, addToEnd } from './utils'
|
|
1
|
+
import { addConsumeAwareSignal, addToEnd, fetchSignal } from './utils'
|
|
2
|
+
import type { FetchSignalContext } from './utils'
|
|
2
3
|
import type {
|
|
3
4
|
OmitKeyof,
|
|
4
5
|
QueryFunction,
|
|
@@ -54,6 +55,8 @@ type StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> =
|
|
|
54
55
|
* Data will be an Array of all the chunks received.
|
|
55
56
|
* The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
|
|
56
57
|
* The query will stay in fetchStatus 'fetching' until the stream ends.
|
|
58
|
+
* Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`.
|
|
59
|
+
* If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes.
|
|
57
60
|
* @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional
|
|
58
61
|
* `refetchMode`, `reducer`, and `initialValue` options.
|
|
59
62
|
* @returns A query function to pass as `queryFn`.
|
|
@@ -82,6 +85,12 @@ export function streamedQuery<
|
|
|
82
85
|
TQueryKey
|
|
83
86
|
> {
|
|
84
87
|
return async (context) => {
|
|
88
|
+
const signalContext: FetchSignalContext = context
|
|
89
|
+
const signal = signalContext[fetchSignal]
|
|
90
|
+
if (signal?.aborted) {
|
|
91
|
+
return initialValue
|
|
92
|
+
}
|
|
93
|
+
|
|
85
94
|
const query = context.client
|
|
86
95
|
.getQueryCache()
|
|
87
96
|
.find({ queryKey: context.queryKey, exact: true })
|
|
@@ -108,14 +117,16 @@ export function streamedQuery<
|
|
|
108
117
|
},
|
|
109
118
|
() => context.signal,
|
|
110
119
|
() => (cancelled = true),
|
|
120
|
+
signal,
|
|
111
121
|
)
|
|
112
122
|
|
|
123
|
+
const isStreamInactive = () => cancelled || signal?.aborted === true
|
|
113
124
|
const stream = await streamFn(streamFnContext)
|
|
114
125
|
|
|
115
126
|
const isReplaceRefetch = isRefetch && refetchMode === 'replace'
|
|
116
127
|
|
|
117
128
|
for await (const chunk of stream) {
|
|
118
|
-
if (
|
|
129
|
+
if (isStreamInactive()) {
|
|
119
130
|
break
|
|
120
131
|
}
|
|
121
132
|
|
|
@@ -130,7 +141,7 @@ export function streamedQuery<
|
|
|
130
141
|
}
|
|
131
142
|
|
|
132
143
|
// finalize result: replace-refetching needs to write to the cache
|
|
133
|
-
if (isReplaceRefetch && !
|
|
144
|
+
if (isReplaceRefetch && !isStreamInactive()) {
|
|
134
145
|
context.client.setQueryData<TData>(context.queryKey, result)
|
|
135
146
|
}
|
|
136
147
|
|
package/src/utils.ts
CHANGED
|
@@ -448,8 +448,8 @@ export function shallowEqualObjects<T extends Record<string, any>>(
|
|
|
448
448
|
return false
|
|
449
449
|
}
|
|
450
450
|
|
|
451
|
-
for (const key
|
|
452
|
-
if (a[key] !== b[key]) {
|
|
451
|
+
for (const key of Object.keys(a)) {
|
|
452
|
+
if (!hasOwn.call(b, key) || a[key] !== b[key]) {
|
|
453
453
|
return false
|
|
454
454
|
}
|
|
455
455
|
}
|
|
@@ -587,30 +587,28 @@ export function keepPreviousData<T>(
|
|
|
587
587
|
|
|
588
588
|
/**
|
|
589
589
|
* Returns a new array with `item` added at the end. If that makes the array longer than `max`,
|
|
590
|
-
*
|
|
591
|
-
* `items` already did.
|
|
590
|
+
* excess items are removed from the start.
|
|
592
591
|
* @param items - The current items.
|
|
593
592
|
* @param item - The value to append.
|
|
594
|
-
* @param max - The
|
|
593
|
+
* @param max - The maximum number of items to keep. `0` (the default) means no limit.
|
|
595
594
|
* @returns A new array with `item` added.
|
|
596
595
|
*/
|
|
597
596
|
export function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {
|
|
598
597
|
const newItems = [...items, item]
|
|
599
|
-
return max && newItems.length > max ? newItems.slice(
|
|
598
|
+
return max && newItems.length > max ? newItems.slice(-max) : newItems
|
|
600
599
|
}
|
|
601
600
|
|
|
602
601
|
/**
|
|
603
602
|
* Returns a new array with `item` added at the start. If that makes the array longer than `max`,
|
|
604
|
-
*
|
|
605
|
-
* `items` already did.
|
|
603
|
+
* excess items are removed from the end.
|
|
606
604
|
* @param items - The current items.
|
|
607
605
|
* @param item - The value to prepend.
|
|
608
|
-
* @param max - The
|
|
606
|
+
* @param max - The maximum number of items to keep. `0` (the default) means no limit.
|
|
609
607
|
* @returns A new array with `item` added.
|
|
610
608
|
*/
|
|
611
609
|
export function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {
|
|
612
610
|
const newItems = [item, ...items]
|
|
613
|
-
return max && newItems.length > max ? newItems.slice(0,
|
|
611
|
+
return max && newItems.length > max ? newItems.slice(0, max) : newItems
|
|
614
612
|
}
|
|
615
613
|
|
|
616
614
|
/**
|
|
@@ -702,6 +700,16 @@ export function shouldThrowError<T extends (...args: Array<any>) => boolean>(
|
|
|
702
700
|
return !!throwOnError
|
|
703
701
|
}
|
|
704
702
|
|
|
703
|
+
export const fetchSignal = Symbol()
|
|
704
|
+
|
|
705
|
+
/** Internal view of a context that can expose its signal without consuming it. */
|
|
706
|
+
export type FetchSignalContext = {
|
|
707
|
+
/** The public signal, whose getter can mark it consumed. */
|
|
708
|
+
readonly signal: AbortSignal
|
|
709
|
+
/** The original fetch signal, absent on application-created contexts. */
|
|
710
|
+
readonly [fetchSignal]?: AbortSignal
|
|
711
|
+
}
|
|
712
|
+
|
|
705
713
|
/**
|
|
706
714
|
* Adds a lazy `signal` getter to an object, such as a query function context. The first time
|
|
707
715
|
* `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right
|
|
@@ -709,32 +717,37 @@ export function shouldThrowError<T extends (...args: Array<any>) => boolean>(
|
|
|
709
717
|
* @param object - The object to add the `signal` property to.
|
|
710
718
|
* @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read.
|
|
711
719
|
* @param onCancelled - Called when the signal is aborted, if `signal` was read.
|
|
720
|
+
* @param internalSignal - The fetch signal to forward without consuming the getter.
|
|
712
721
|
* @returns The same object, with the `signal` property added.
|
|
713
722
|
*/
|
|
714
|
-
export function addConsumeAwareSignal<T>(
|
|
723
|
+
export function addConsumeAwareSignal<T extends object>(
|
|
715
724
|
object: T,
|
|
716
725
|
getSignal: () => AbortSignal,
|
|
717
|
-
onCancelled:
|
|
726
|
+
onCancelled: () => void,
|
|
727
|
+
internalSignal?: AbortSignal,
|
|
718
728
|
): T & { signal: AbortSignal } {
|
|
719
729
|
let consumed = false
|
|
720
730
|
let signal: AbortSignal | undefined
|
|
721
731
|
|
|
722
|
-
Object.
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
732
|
+
Object.defineProperties(object, {
|
|
733
|
+
[fetchSignal]: { value: internalSignal },
|
|
734
|
+
signal: {
|
|
735
|
+
enumerable: true,
|
|
736
|
+
get: () => {
|
|
737
|
+
signal ??= getSignal()
|
|
738
|
+
if (consumed) {
|
|
739
|
+
return signal
|
|
740
|
+
}
|
|
729
741
|
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
742
|
+
consumed = true
|
|
743
|
+
if (signal.aborted) {
|
|
744
|
+
onCancelled()
|
|
745
|
+
} else {
|
|
746
|
+
signal.addEventListener('abort', onCancelled, { once: true })
|
|
747
|
+
}
|
|
736
748
|
|
|
737
|
-
|
|
749
|
+
return signal
|
|
750
|
+
},
|
|
738
751
|
},
|
|
739
752
|
})
|
|
740
753
|
|