@tanstack/query-core 5.107.0 → 5.107.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.
Files changed (179) hide show
  1. package/build/legacy/{hydration-BIRJt69T.d.cts → hydration-24GwbSaU.d.cts} +3178 -3178
  2. package/build/legacy/hydration-24GwbSaU.d.cts.map +1 -0
  3. package/build/legacy/{hydration-9_kOYxJM.d.ts → hydration-Cbq_heQS.d.ts} +3178 -3178
  4. package/build/legacy/hydration-Cbq_heQS.d.ts.map +1 -0
  5. package/build/legacy/hydration.cjs.map +1 -1
  6. package/build/legacy/hydration.d.cts +1 -1
  7. package/build/legacy/hydration.d.ts +1 -1
  8. package/build/legacy/hydration.js.map +1 -1
  9. package/build/legacy/index.cjs.map +1 -1
  10. package/build/legacy/index.d.cts +2 -2
  11. package/build/legacy/index.d.ts +2 -2
  12. package/build/legacy/index.js.map +1 -1
  13. package/build/legacy/infiniteQueryBehavior.cjs.map +1 -1
  14. package/build/legacy/infiniteQueryBehavior.d.cts +1 -1
  15. package/build/legacy/infiniteQueryBehavior.d.ts +1 -1
  16. package/build/legacy/infiniteQueryBehavior.js.map +1 -1
  17. package/build/legacy/infiniteQueryObserver.cjs.map +1 -1
  18. package/build/legacy/infiniteQueryObserver.d.cts +1 -1
  19. package/build/legacy/infiniteQueryObserver.d.ts +1 -1
  20. package/build/legacy/infiniteQueryObserver.js.map +1 -1
  21. package/build/legacy/mutation.cjs +1 -1
  22. package/build/legacy/mutation.cjs.map +1 -1
  23. package/build/legacy/mutation.d.cts +1 -1
  24. package/build/legacy/mutation.d.ts +1 -1
  25. package/build/legacy/mutation.js +1 -1
  26. package/build/legacy/mutation.js.map +1 -1
  27. package/build/legacy/mutationCache.cjs.map +1 -1
  28. package/build/legacy/mutationCache.d.cts +1 -1
  29. package/build/legacy/mutationCache.d.ts +1 -1
  30. package/build/legacy/mutationCache.js.map +1 -1
  31. package/build/legacy/mutationObserver.cjs.map +1 -1
  32. package/build/legacy/mutationObserver.d.cts +1 -1
  33. package/build/legacy/mutationObserver.d.ts +1 -1
  34. package/build/legacy/mutationObserver.js.map +1 -1
  35. package/build/legacy/queriesObserver.cjs.map +1 -1
  36. package/build/legacy/queriesObserver.d.cts +1 -1
  37. package/build/legacy/queriesObserver.d.ts +1 -1
  38. package/build/legacy/queriesObserver.js.map +1 -1
  39. package/build/legacy/query.cjs +6 -4
  40. package/build/legacy/query.cjs.map +1 -1
  41. package/build/legacy/query.d.cts +1 -1
  42. package/build/legacy/query.d.ts +1 -1
  43. package/build/legacy/query.js +6 -4
  44. package/build/legacy/query.js.map +1 -1
  45. package/build/legacy/queryCache.cjs.map +1 -1
  46. package/build/legacy/queryCache.d.cts +1 -1
  47. package/build/legacy/queryCache.d.ts +1 -1
  48. package/build/legacy/queryCache.js.map +1 -1
  49. package/build/legacy/queryClient.cjs.map +1 -1
  50. package/build/legacy/queryClient.d.cts +1 -1
  51. package/build/legacy/queryClient.d.ts +1 -1
  52. package/build/legacy/queryClient.js.map +1 -1
  53. package/build/legacy/queryObserver.cjs.map +1 -1
  54. package/build/legacy/queryObserver.d.cts +1 -1
  55. package/build/legacy/queryObserver.d.ts +1 -1
  56. package/build/legacy/queryObserver.js.map +1 -1
  57. package/build/legacy/removable.cjs.map +1 -1
  58. package/build/legacy/removable.js.map +1 -1
  59. package/build/legacy/retryer.cjs.map +1 -1
  60. package/build/legacy/retryer.d.cts +1 -1
  61. package/build/legacy/retryer.d.ts +1 -1
  62. package/build/legacy/retryer.js.map +1 -1
  63. package/build/legacy/streamedQuery.cjs.map +1 -1
  64. package/build/legacy/streamedQuery.d.cts +1 -1
  65. package/build/legacy/streamedQuery.d.ts +1 -1
  66. package/build/legacy/streamedQuery.js.map +1 -1
  67. package/build/legacy/subscribable-D2lAzdDi.d.cts.map +1 -1
  68. package/build/legacy/subscribable-D2lAzdDi.d.ts.map +1 -1
  69. package/build/legacy/subscribable.cjs.map +1 -1
  70. package/build/legacy/subscribable.js.map +1 -1
  71. package/build/legacy/types.cjs.map +1 -1
  72. package/build/legacy/types.d.cts +1 -1
  73. package/build/legacy/types.d.ts +1 -1
  74. package/build/legacy/types.js.map +1 -1
  75. package/build/legacy/utils.cjs.map +1 -1
  76. package/build/legacy/utils.d.cts +1 -1
  77. package/build/legacy/utils.d.ts +1 -1
  78. package/build/legacy/utils.js.map +1 -1
  79. package/build/modern/{hydration-BIRJt69T.d.cts → hydration-24GwbSaU.d.cts} +3178 -3178
  80. package/build/modern/hydration-24GwbSaU.d.cts.map +1 -0
  81. package/build/modern/{hydration-9_kOYxJM.d.ts → hydration-Cbq_heQS.d.ts} +3178 -3178
  82. package/build/modern/hydration-Cbq_heQS.d.ts.map +1 -0
  83. package/build/modern/hydration.cjs.map +1 -1
  84. package/build/modern/hydration.d.cts +1 -1
  85. package/build/modern/hydration.d.ts +1 -1
  86. package/build/modern/hydration.js.map +1 -1
  87. package/build/modern/index.cjs.map +1 -1
  88. package/build/modern/index.d.cts +2 -2
  89. package/build/modern/index.d.ts +2 -2
  90. package/build/modern/index.js.map +1 -1
  91. package/build/modern/infiniteQueryBehavior.cjs.map +1 -1
  92. package/build/modern/infiniteQueryBehavior.d.cts +1 -1
  93. package/build/modern/infiniteQueryBehavior.d.ts +1 -1
  94. package/build/modern/infiniteQueryBehavior.js.map +1 -1
  95. package/build/modern/infiniteQueryObserver.cjs.map +1 -1
  96. package/build/modern/infiniteQueryObserver.d.cts +1 -1
  97. package/build/modern/infiniteQueryObserver.d.ts +1 -1
  98. package/build/modern/infiniteQueryObserver.js.map +1 -1
  99. package/build/modern/mutation.cjs +1 -1
  100. package/build/modern/mutation.cjs.map +1 -1
  101. package/build/modern/mutation.d.cts +1 -1
  102. package/build/modern/mutation.d.ts +1 -1
  103. package/build/modern/mutation.js +1 -1
  104. package/build/modern/mutation.js.map +1 -1
  105. package/build/modern/mutationCache.cjs.map +1 -1
  106. package/build/modern/mutationCache.d.cts +1 -1
  107. package/build/modern/mutationCache.d.ts +1 -1
  108. package/build/modern/mutationCache.js.map +1 -1
  109. package/build/modern/mutationObserver.cjs.map +1 -1
  110. package/build/modern/mutationObserver.d.cts +1 -1
  111. package/build/modern/mutationObserver.d.ts +1 -1
  112. package/build/modern/mutationObserver.js.map +1 -1
  113. package/build/modern/queriesObserver.cjs.map +1 -1
  114. package/build/modern/queriesObserver.d.cts +1 -1
  115. package/build/modern/queriesObserver.d.ts +1 -1
  116. package/build/modern/queriesObserver.js.map +1 -1
  117. package/build/modern/query.cjs +6 -4
  118. package/build/modern/query.cjs.map +1 -1
  119. package/build/modern/query.d.cts +1 -1
  120. package/build/modern/query.d.ts +1 -1
  121. package/build/modern/query.js +6 -4
  122. package/build/modern/query.js.map +1 -1
  123. package/build/modern/queryCache.cjs.map +1 -1
  124. package/build/modern/queryCache.d.cts +1 -1
  125. package/build/modern/queryCache.d.ts +1 -1
  126. package/build/modern/queryCache.js.map +1 -1
  127. package/build/modern/queryClient.cjs.map +1 -1
  128. package/build/modern/queryClient.d.cts +1 -1
  129. package/build/modern/queryClient.d.ts +1 -1
  130. package/build/modern/queryClient.js.map +1 -1
  131. package/build/modern/queryObserver.cjs.map +1 -1
  132. package/build/modern/queryObserver.d.cts +1 -1
  133. package/build/modern/queryObserver.d.ts +1 -1
  134. package/build/modern/queryObserver.js.map +1 -1
  135. package/build/modern/removable.cjs.map +1 -1
  136. package/build/modern/removable.js.map +1 -1
  137. package/build/modern/retryer.cjs.map +1 -1
  138. package/build/modern/retryer.d.cts +1 -1
  139. package/build/modern/retryer.d.ts +1 -1
  140. package/build/modern/retryer.js.map +1 -1
  141. package/build/modern/streamedQuery.cjs.map +1 -1
  142. package/build/modern/streamedQuery.d.cts +1 -1
  143. package/build/modern/streamedQuery.d.ts +1 -1
  144. package/build/modern/streamedQuery.js.map +1 -1
  145. package/build/modern/subscribable-D2lAzdDi.d.cts.map +1 -1
  146. package/build/modern/subscribable-D2lAzdDi.d.ts.map +1 -1
  147. package/build/modern/subscribable.cjs.map +1 -1
  148. package/build/modern/subscribable.js.map +1 -1
  149. package/build/modern/types.cjs.map +1 -1
  150. package/build/modern/types.d.cts +1 -1
  151. package/build/modern/types.d.ts +1 -1
  152. package/build/modern/types.js.map +1 -1
  153. package/build/modern/utils.cjs.map +1 -1
  154. package/build/modern/utils.d.cts +1 -1
  155. package/build/modern/utils.d.ts +1 -1
  156. package/build/modern/utils.js.map +1 -1
  157. package/package.json +1 -1
  158. package/src/hydration.ts +3 -3
  159. package/src/index.ts +98 -1
  160. package/src/infiniteQueryBehavior.ts +1 -1
  161. package/src/infiniteQueryObserver.ts +3 -3
  162. package/src/mutation.ts +4 -4
  163. package/src/mutationCache.ts +4 -4
  164. package/src/mutationObserver.ts +1 -1
  165. package/src/queriesObserver.ts +1 -1
  166. package/src/query.ts +10 -8
  167. package/src/queryCache.ts +5 -5
  168. package/src/queryClient.ts +6 -6
  169. package/src/queryObserver.ts +3 -3
  170. package/src/removable.ts +1 -1
  171. package/src/retryer.ts +1 -1
  172. package/src/streamedQuery.ts +1 -1
  173. package/src/subscribable.ts +4 -1
  174. package/src/types.ts +57 -56
  175. package/src/utils.ts +2 -2
  176. package/build/legacy/hydration-9_kOYxJM.d.ts.map +0 -1
  177. package/build/legacy/hydration-BIRJt69T.d.cts.map +0 -1
  178. package/build/modern/hydration-9_kOYxJM.d.ts.map +0 -1
  179. package/build/modern/hydration-BIRJt69T.d.cts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"query.cjs","names":["Removable","replaceData","noop","resolveQueryValue","skipToken","timeUntilStale","fetchSignal","ensureQueryFn","infiniteQueryBehavior","createRetryer","CancelledError","canFetch"],"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n fetchSignal,\n noop,\n replaceData,\n resolveQueryValue,\n skipToken,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { CancelledError, canFetch, createRetryer } from './retryer'\nimport { Removable } from './removable'\nimport { infiniteQueryBehavior } from './infiniteQueryBehavior'\nimport type { QueryCache } from './queryCache'\nimport type { QueryClient } from './queryClient'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n StaleTime,\n} from './types'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n client: QueryClient\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state?: QueryState<TData, TError>\n}\n\n/**\n * The raw state stored on a `Query` instance. This is the underlying state\n * that observer results (e.g. `QueryObserverResult`) are derived from.\n */\nexport interface QueryState<TData = unknown, TError = DefaultError> {\n /**\n * The last successfully resolved data for the query.\n */\n data: TData | undefined\n /**\n * The number of times the query has successfully resolved.\n */\n dataUpdateCount: number\n /**\n * The timestamp for when the query most recently returned the `status` as `\"success\"`.\n */\n dataUpdatedAt: number\n /**\n * The error object for the query, if the last attempt resulted in an error.\n * - Defaults to `null`.\n */\n error: TError | null\n /**\n * The sum of all errors, incremented every time the query resolves with an error.\n */\n errorUpdateCount: number\n /**\n * The timestamp for when the query most recently returned the `status` as `\"error\"`.\n */\n errorUpdatedAt: number\n /**\n * The failure count for the current fetch.\n * - Incremented every time the fetch fails.\n * - Reset to `0` when the fetch succeeds.\n */\n fetchFailureCount: number\n /**\n * The reason the current fetch failed, as reported by the retryer.\n * - Reset to `null` when the fetch succeeds.\n */\n fetchFailureReason: TError | null\n /**\n * Metadata passed to the currently in-flight (or most recent) fetch, e.g. the\n * `fetchMore` direction for infinite queries.\n */\n fetchMeta: FetchMeta | null\n /**\n * Whether the query has been marked as invalidated via `invalidate()`.\n * - Reset to `false` whenever the query resolves successfully.\n */\n isInvalidated: boolean\n /**\n * The status of the query.\n * - `pending` if there's no cached data and no attempt was finished yet.\n * - `error` if the last attempt resulted in an error.\n * - `success` if the query has data.\n */\n status: QueryStatus\n /**\n * The fetch status of the query.\n * - `fetching`: the `queryFn` is currently executing.\n * - `paused`: a fetch wanted to run but has been paused (see network mode).\n * - `idle`: the query is not fetching.\n */\n fetchStatus: FetchStatus\n}\n\n/**\n * The context passed to a {@link QueryBehavior}'s `onFetch`, which can replace `fetchFn` to change\n * how the query fetches (e.g. to fetch pages for an infinite query).\n */\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n /**\n * The function that runs the fetch. By default it calls `queryFn`; `onFetch` can replace it.\n */\n fetchFn: () => unknown | Promise<unknown>\n /**\n * The options of this fetch.\n */\n fetchOptions?: FetchOptions\n /**\n * The `AbortSignal` that aborts when the fetch is cancelled.\n */\n signal: AbortSignal\n /**\n * The options of the query.\n */\n options: QueryOptions<TQueryFnData, TError, TData, any>\n /**\n * The `QueryClient` the query belongs to.\n */\n client: QueryClient\n /**\n * The key of the query.\n */\n queryKey: TQueryKey\n /**\n * The state of the query when the fetch starts.\n */\n state: QueryState<TData, TError>\n}\n\n/**\n * Customizes how a query fetches, e.g. the behavior that fetches the pages of an infinite query.\n */\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n /**\n * Called before each fetch of the query, e.g. to replace `fetchFn` in the context.\n */\n onFetch: (\n context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n query: Query,\n ) => void\n}\n\n/**\n * The direction an infinite query fetches in: `'forward'` for the next page, `'backward'` for the\n * previous one.\n */\nexport type FetchDirection = 'forward' | 'backward'\n\n/**\n * Metadata for a fetch, e.g. the direction when an infinite query fetches more pages.\n */\nexport interface FetchMeta {\n /**\n * Set when an infinite query fetches another page, with the direction to fetch in.\n */\n fetchMore?: { direction: FetchDirection }\n}\n\n/**\n * Options for a single fetch of a query.\n */\nexport interface FetchOptions<TData = unknown> {\n /**\n * If `true`, an in-flight fetch is cancelled before starting a new one, when the query already\n * has data. Otherwise, the in-flight fetch is reused.\n */\n cancelRefetch?: boolean\n /**\n * Metadata of the fetch, stored in the query's `fetchMeta` state.\n */\n meta?: FetchMeta\n /**\n * A promise to use for the first attempt instead of calling `fetchFn`, e.g. a pending promise\n * restored by `hydrate`.\n */\n initialPromise?: Promise<TData>\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction<TData> {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction<TData, TError> {\n type: 'setState'\n state: Partial<QueryState<TData, TError>>\n}\n\n/**\n * The actions a query dispatches to update its state, e.g. when it starts fetching, fails, or\n * succeeds.\n */\nexport type Action<TData, TError> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction<TData, TError>\n | SuccessAction<TData>\n\n// CLASS\n\n/**\n * Represents a single cached query. A `Query` holds the query's key, options,\n * state (data/error/status), and the observers currently subscribed to it.\n *\n * Instances are created and managed internally by `QueryCache`; application\n * code typically interacts with queries indirectly through `QueryClient` or\n * a framework hook like `useQuery`. Direct access to a `Query` instance is\n * possible via `queryCache.find()`/`findAll()` for inspecting cache state.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n * const query = queryCache.find({ queryKey: ['posts'] })\n *\n * if (query) {\n * console.log(query.state.dataUpdatedAt)\n * }\n * ```\n */\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state: QueryState<TData, TError>\n #queryType?: 'infinite'\n\n #initialState: QueryState<TData, TError>\n #revertState?: QueryState<TData, TError>\n #cache: QueryCache\n #client: QueryClient\n #retryer?: Retryer<TData>\n #fetchPromise?: Promise<TData>\n observers: Array<QueryObserver<any, any, any, any, any>>\n #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#client = config.client\n this.#cache = this.#client.getQueryCache()\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n /**\n * The `meta` object passed in the query's options, if any.\n * @returns The query's `meta`, or `undefined` if none was set.\n */\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n /**\n * `'infinite'` for an infinite query, otherwise `undefined`.\n * @internal\n * @returns The type of the query, set from the `_type` option (e.g. `'infinite'`).\n */\n get queryType() {\n return this.#queryType\n }\n\n /**\n * The promise for the currently in-flight fetch, if the query is fetching.\n * `undefined` when the query is not fetching.\n * @returns The promise of the in-flight fetch, or `undefined`.\n */\n get promise(): Promise<TData> | undefined {\n return this.#retryer?.promise\n }\n\n /**\n * Replaces the query's options and applies their `gcTime`. If the query has no data yet, it gets\n * the `initialData` from the new options, if any.\n * @internal\n * @param options - The new query options, merged on top of the query's default options.\n */\n setOptions(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n if (options?._type) {\n this.#queryType = options._type\n }\n\n this.updateGcTime(this.options.gcTime)\n\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- the constructor calls 'setOptions' before it assigns 'state'\n if (this.state && this.state.data === undefined) {\n const defaultState = getDefaultState(this.options)\n if (defaultState.data !== undefined) {\n this.setState(\n successState(defaultState.data, defaultState.dataUpdatedAt),\n )\n this.#initialState = defaultState\n }\n }\n }\n\n protected override optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n /**\n * Writes new data to the query and marks it as successfully fetched.\n * @internal\n * @param newData - The data to write. Structural sharing with the current data is applied.\n * @param options - Set `updatedAt` to override the timestamp, and `manual` to mark the write as\n * manual (e.g. from `queryClient.setQueryData`).\n * @returns The data that was written.\n */\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n /**\n * Merges the given partial state directly into this query's state, notifying observers. Used\n * by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a\n * user manually trigger a loading/error state or edit the cached data.\n * @param state - The partial state to merge into the query's state.\n */\n setState(state: Partial<QueryState<TData, TError>>): void {\n this.#dispatch({ type: 'setState', state })\n }\n\n /**\n * Cancels the query's currently in-flight fetch, if any.\n * - Returns a promise that resolves once the cancellation has settled.\n * - If no fetch is in progress, resolves immediately.\n * @param options - Set `revert` to restore the state from before the fetch started, and `silent`\n * to suppress the cancellation error when a new fetch replaces the cancelled one.\n * @returns A promise that resolves once the cancellation has settled.\n * @example\n * ```ts\n * await query.cancel()\n * ```\n */\n cancel(options?: CancelOptions): Promise<void> {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n /**\n * Clears the query's garbage collection timeout and silently cancels any\n * in-flight fetch. Called by `QueryCache` when the query is removed from\n * the cache.\n * @see {@link Query#cancel}\n */\n override destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n /**\n * The state the query was created with.\n * @internal\n * @returns The state the query had when it was first created, used by {@link Query#reset}.\n */\n get resetState(): QueryState<TData, TError> {\n return this.#initialState\n }\n\n /**\n * Resets the query back to its initial state (the state it had when it was\n * first created, e.g. any `initialData`), destroying it first to cancel any\n * in-flight fetch.\n */\n reset(): void {\n this.destroy()\n this.setState(this.resetState)\n }\n\n /**\n * Returns `true` if the query has at least one observer for which `enabled`\n * does not resolve to `false`.\n * @returns `true` if the query has an enabled observer.\n */\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveQueryValue(observer.options.enabled, this) !== false,\n )\n }\n\n /**\n * Returns `true` if the query is disabled, meaning it will not fetch\n * automatically.\n * - If the query has observers, it is disabled when none of them are active\n * (see `isActive`).\n * - If the query has no observers, it is disabled when its `queryFn` is\n * `skipToken` or it has never been fetched.\n * @returns `true` if the query is disabled.\n */\n isDisabled(): boolean {\n if (this.getObserversCount() > 0) {\n return !this.isActive()\n }\n // if a query has no observers, it should still be considered disabled if it never attempted a fetch\n return this.options.queryFn === skipToken || !this.isFetched()\n }\n\n /**\n * Returns `true` if the query has been fetched, i.e. it has resolved with\n * either data or an error at least once.\n * @returns `true` if the query has been fetched.\n */\n isFetched() {\n return this.state.dataUpdateCount + this.state.errorUpdateCount > 0\n }\n\n /**\n * Returns `true` if the query has data and at least one observer configured with\n * `staleTime: 'static'`, meaning it is treated as never stale.\n * @returns `true` if the query is static.\n */\n isStatic(): boolean {\n if (this.state.data === undefined) {\n return false\n }\n\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) =>\n resolveQueryValue(observer.options.staleTime, this) === 'static',\n )\n }\n\n return false\n }\n\n /**\n * Returns `true` if the query is stale.\n * - If the query has observers, defers to whether any observer's current\n * result reports `isStale` (which accounts for each observer's own\n * `staleTime` and `enabled` state).\n * - If the query has no observers, it is considered stale when it has no\n * data or has been invalidated.\n * @returns `true` if the query is stale.\n * @see {@link Query#isStaleByTime}\n * @example\n * ```ts\n * if (query.isStale()) {\n * // refetch or otherwise treat the cached data as outdated\n * }\n * ```\n */\n isStale(): boolean {\n // check observers first, their `isStale` has the source of truth\n // calculated with `isStaleByTime` and it takes `enabled` into account\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined || this.state.isInvalidated\n }\n\n /**\n * Returns `true` if the query's data is stale relative to the given\n * `staleTime` (defaults to `0`).\n * - A query with no data is always stale.\n * - `staleTime: 'static'` is never stale.\n * - An invalidated query is always stale.\n * - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`.\n * @param staleTime - The time, in milliseconds, after which data is considered stale, or\n * `'static'` to never treat existing data as stale. A query without data is stale either way.\n * @returns `true` if the query's data is stale.\n * @see {@link Query#isStale}\n * @example\n * ```ts\n * const isStale = query.isStaleByTime(60 * 1000)\n * ```\n */\n isStaleByTime(staleTime: StaleTime = 0): boolean {\n // no data is always stale\n if (this.state.data === undefined) {\n return true\n }\n // static is never stale\n if (staleTime === 'static') {\n return false\n }\n // if the query is invalidated, it is stale\n if (this.state.isInvalidated) {\n return true\n }\n\n return !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n }\n\n /**\n * Refetches the query when the window regains focus, if an observer wants that, and continues a\n * paused fetch.\n * @internal\n */\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n /**\n * Refetches the query when the app reconnects, if an observer wants that, and continues a paused\n * fetch.\n * @internal\n */\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n /**\n * Subscribes an observer to the query and stops its garbage collection.\n * @internal\n * @param observer - The observer to add. Adding an observer that is already subscribed does\n * nothing.\n */\n addObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n /**\n * Unsubscribes an observer from the query.\n * @internal\n * @param observer - The observer to remove. When the last observer is removed, the in-flight\n * fetch is cancelled if its abort signal was consumed (otherwise only its retries are stopped),\n * and garbage collection is scheduled.\n */\n removeObserver(observer: QueryObserver<any, any, any, any, any>): void {\n const index = this.observers.indexOf(observer)\n if (index !== -1) {\n this.observers.splice(index, 1)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (\n this.#abortSignalConsumed ||\n (this.state.fetchStatus === 'paused' &&\n this.state.status === 'pending')\n ) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n /**\n * Returns the number of observers currently subscribed to this query.\n * @returns The number of observers.\n * @example\n * ```ts\n * if (query.getObserversCount() === 0) {\n * // no component is currently watching this query\n * }\n * ```\n */\n getObserversCount(): number {\n return this.observers.length\n }\n\n /**\n * Marks the query as invalidated, unless it is already invalidated. This\n * updates `state.isInvalidated` and notifies observers, but does not by\n * itself trigger a refetch.\n * @example\n * ```ts\n * query.invalidate()\n * ```\n */\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n /**\n * Fetches the query, i.e. runs its `queryFn` (through any configured\n * retryer/behavior) and updates the query's state with the result.\n * - If a fetch is already in flight, returns its promise instead of\n * starting a new one, unless `fetchOptions.cancelRefetch` is set and the\n * query already has data, in which case the current fetch is silently\n * cancelled first.\n * - If `options` is passed, it replaces the query's current options\n * before fetching.\n * @param options - Query options that replace the query's current options before fetching. They\n * are not applied when an in-flight fetch is reused.\n * @param fetchOptions - Set `cancelRefetch` to cancel an in-flight fetch first (only if the query\n * already has data), and `meta` to pass extra information to the query's behavior.\n * @returns A promise that resolves with the fetched data, or rejects with the fetch error. If the\n * fetch is cancelled with `revert` while the query has data, it resolves with the restored data\n * instead.\n */\n async fetch(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n fetchOptions?: FetchOptions<TQueryFnData>,\n ): Promise<TData> {\n if (\n this.state.fetchStatus !== 'idle' &&\n // If the promise in the retryer is already rejected, we have to definitely\n // re-start the fetch; there is a chance that the query is still in a\n // pending state when that happens\n this.#retryer?.status() !== 'rejected'\n ) {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer && this.#fetchPromise) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#fetchPromise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: object) => {\n Object.defineProperties(object, {\n [fetchSignal]: { value: abortController.signal, enumerable: true },\n signal: {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const createQueryFnContext = (): QueryFunctionContext<TQueryKey> => {\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<TQueryKey>,\n 'signal'\n > = {\n client: this.#client,\n queryKey: this.queryKey,\n meta: this.meta,\n }\n addSignalProperty(queryFnContext)\n return queryFnContext as QueryFunctionContext<TQueryKey>\n }\n\n const queryFnContext = createQueryFnContext()\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn,\n queryFnContext,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext)\n }\n\n // Trigger behavior hook\n const createFetchContext = (): FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n > => {\n const context: OmitKeyof<\n FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n client: this.#client,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n return context as FetchContext<TQueryFnData, TError, TData, TQueryKey>\n }\n\n const context = createFetchContext()\n\n const behavior =\n this.#queryType === 'infinite'\n ? (infiniteQueryBehavior(\n (this.options as { pages?: number }).pages,\n ) as QueryBehavior<TQueryFnData, TError, TData, TQueryKey>)\n : this.options.behavior\n behavior?.onFetch(context, this as unknown as Query)\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n // Try to fetch the data\n const retryer = (this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise<TData>\n | undefined,\n fn: context.fetchFn as () => Promise<TData>,\n onCancel: (error) => {\n if (error instanceof CancelledError && error.revert) {\n this.setState({\n ...this.#revertState,\n fetchStatus: 'idle' as const,\n })\n }\n abortController.abort()\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n }))\n\n const fetchPromise = (async () => {\n try {\n const data = await retryer.promise\n // this is more of a runtime guard\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n throw new Error(`${this.queryHash} data is undefined`)\n }\n\n this.setData(data)\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query<any, any, any, any>,\n )\n return data\n } catch (error) {\n if (error instanceof CancelledError) {\n if (error.silent) {\n if (this.#retryer !== retryer && this.#fetchPromise) {\n // A new fetch replaced the silently cancelled one,\n // so we piggyback onto that promise.\n return this.#fetchPromise\n }\n throw error\n } else if (error.revert) {\n // transform error into reverted state data\n // if the initial fetch was cancelled, we have no data, so we have\n // to get reject with a CancelledError\n if (this.state.data === undefined) {\n throw error\n }\n return this.state.data\n }\n }\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query<any, any, any, any>,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query<any, any, any, any>,\n )\n\n throw error // rethrow the error for further handling\n } finally {\n // The settled retryer's promise would otherwise pin this fetch's raw\n // result (a second copy after structural sharing) for the query's lifetime\n if (this.#retryer === retryer) {\n this.#retryer = undefined\n this.#fetchPromise = undefined\n }\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n })()\n this.#fetchPromise = fetchPromise\n retryer.start()\n return fetchPromise\n }\n\n #dispatch(action: Action<TData, TError>): void {\n const reducer = (\n state: QueryState<TData, TError>,\n ): QueryState<TData, TError> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success':\n const newState = {\n ...state,\n ...successState(action.data, action.dataUpdatedAt),\n dataUpdateCount: state.dataUpdateCount + 1,\n ...(!action.manual && {\n fetchStatus: 'idle' as const,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n // If fetching ends successfully, we don't need revertState as a fallback anymore.\n // For manual updates, capture the state to revert to it in case of a cancellation.\n this.#revertState = action.manual ? newState : undefined\n\n return newState\n case 'error':\n const error = action.error\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n // flag existing data as invalidated if we get a background error\n // note that \"no data\" always means stale so we can set unconditionally here\n isInvalidated: true,\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n // Keep the current iteration stable if an observer unsubscribes\n // synchronously while it is being notified.\n this.observers.slice().forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\n/**\n * Returns the state changes applied when a query starts fetching.\n * @param data - The query's current data. If it is `undefined`, the query is also reset to\n * `'pending'` with no error.\n * @param options - The query options, whose `networkMode` decides whether the query is `'fetching'`\n * or `'paused'`.\n * @returns The partial query state for a starting fetch.\n */\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\n/**\n * Returns the state changes applied when a query receives data.\n * @param data - The new data.\n * @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to the current time.\n * @returns The partial query state for a successful update.\n */\nfunction successState<TData>(data: TData | undefined, dataUpdatedAt?: number) {\n return {\n data,\n dataUpdatedAt: dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success' as const,\n }\n}\n\n/**\n * Returns the initial state of a query, based on its `initialData` and `initialDataUpdatedAt`\n * options.\n * @param options - The query options.\n * @returns The initial query state: `'success'` if `initialData` is set, otherwise `'pending'`.\n */\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): QueryState<TData, TError> {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction<TData>)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? options.initialDataUpdatedAt()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2RA,IAAa,QAAb,cAKUA,kBAAAA,UAAU;CAiBlB,YAAY,QAA6D;EACvE,MAAM;;;;;;;;;;;EAEN,8BAAA,uBAAA,sBAAA,MAA4B,KAAA;EAC5B,8BAAA,uBAAA,iBAAA,MAAuB,OAAO,cAAA;EAC9B,KAAK,WAAW,OAAO,OA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,UAAW,wBAAwB,KAAK,IAAI,IAAK;EAChE,OAAO;EACP,kBAAkB;EAClB,gBAAgB;EAChB,mBAAmB;EACnB,oBAAoB;EACpB,WAAW;EACX,eAAe;EACf,QAAQ,UAAU,YAAY;EAC9B,aAAa;CACf;AACF"}
1
+ {"version":3,"file":"query.cjs","names":["Removable","replaceData","noop","resolveQueryValue","skipToken","timeUntilStale","fetchSignal","ensureQueryFn","infiniteQueryBehavior","createRetryer","CancelledError","canFetch"],"sources":["../../src/query.ts"],"sourcesContent":["import { infiniteQueryBehavior } from './infiniteQueryBehavior'\nimport { notifyManager } from './notifyManager'\nimport { Removable } from './removable'\nimport { CancelledError, canFetch, createRetryer } from './retryer'\nimport {\n ensureQueryFn,\n fetchSignal,\n noop,\n replaceData,\n resolveQueryValue,\n skipToken,\n timeUntilStale,\n} from './utils'\nimport type { QueryCache } from './queryCache'\nimport type { QueryClient } from './queryClient'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n StaleTime,\n} from './types'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n client: QueryClient\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state?: QueryState<TData, TError>\n}\n\n/**\n * The raw state stored on a `Query` instance. This is the underlying state\n * that observer results (e.g. `QueryObserverResult`) are derived from.\n */\nexport interface QueryState<TData = unknown, TError = DefaultError> {\n /**\n * The last successfully resolved data for the query.\n */\n data: TData | undefined\n /**\n * The number of times the query has successfully resolved.\n */\n dataUpdateCount: number\n /**\n * The timestamp for when the query most recently returned the `status` as `\"success\"`.\n */\n dataUpdatedAt: number\n /**\n * The error object for the query, if the last attempt resulted in an error.\n * - Defaults to `null`.\n */\n error: TError | null\n /**\n * The sum of all errors, incremented every time the query resolves with an error.\n */\n errorUpdateCount: number\n /**\n * The timestamp for when the query most recently returned the `status` as `\"error\"`.\n */\n errorUpdatedAt: number\n /**\n * The failure count for the current fetch.\n * - Incremented every time the fetch fails.\n * - Reset to `0` when the fetch succeeds.\n */\n fetchFailureCount: number\n /**\n * The reason the current fetch failed, as reported by the retryer.\n * - Reset to `null` when the fetch succeeds.\n */\n fetchFailureReason: TError | null\n /**\n * Metadata passed to the currently in-flight (or most recent) fetch, e.g. the\n * `fetchMore` direction for infinite queries.\n */\n fetchMeta: FetchMeta | null\n /**\n * Whether the query has been marked as invalidated via `invalidate()`.\n * - Reset to `false` whenever the query resolves successfully.\n */\n isInvalidated: boolean\n /**\n * The status of the query.\n * - `pending` if there's no cached data and no attempt was finished yet.\n * - `error` if the last attempt resulted in an error.\n * - `success` if the query has data.\n */\n status: QueryStatus\n /**\n * The fetch status of the query.\n * - `fetching`: the `queryFn` is currently executing.\n * - `paused`: a fetch wanted to run but has been paused (see network mode).\n * - `idle`: the query is not fetching.\n */\n fetchStatus: FetchStatus\n}\n\n/**\n * The context passed to a {@link QueryBehavior}'s `onFetch`, which can replace `fetchFn` to change\n * how the query fetches (e.g. to fetch pages for an infinite query).\n */\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n /**\n * The function that runs the fetch. By default it calls `queryFn`; `onFetch` can replace it.\n */\n fetchFn: () => unknown | Promise<unknown>\n /**\n * The options of this fetch.\n */\n fetchOptions?: FetchOptions\n /**\n * The `AbortSignal` that aborts when the fetch is cancelled.\n */\n signal: AbortSignal\n /**\n * The options of the query.\n */\n options: QueryOptions<TQueryFnData, TError, TData, any>\n /**\n * The `QueryClient` the query belongs to.\n */\n client: QueryClient\n /**\n * The key of the query.\n */\n queryKey: TQueryKey\n /**\n * The state of the query when the fetch starts.\n */\n state: QueryState<TData, TError>\n}\n\n/**\n * Customizes how a query fetches, e.g. the behavior that fetches the pages of an infinite query.\n */\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n /**\n * Called before each fetch of the query, e.g. to replace `fetchFn` in the context.\n */\n onFetch: (\n context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n query: Query,\n ) => void\n}\n\n/**\n * The direction an infinite query fetches in: `'forward'` for the next page, `'backward'` for the\n * previous one.\n */\nexport type FetchDirection = 'forward' | 'backward'\n\n/**\n * Metadata for a fetch, e.g. the direction when an infinite query fetches more pages.\n */\nexport interface FetchMeta {\n /**\n * Set when an infinite query fetches another page, with the direction to fetch in.\n */\n fetchMore?: { direction: FetchDirection }\n}\n\n/**\n * Options for a single fetch of a query.\n */\nexport interface FetchOptions<TData = unknown> {\n /**\n * If `true`, an in-flight fetch is cancelled before starting a new one, when the query already\n * has data. Otherwise, the in-flight fetch is reused.\n */\n cancelRefetch?: boolean\n /**\n * Metadata of the fetch, stored in the query's `fetchMeta` state.\n */\n meta?: FetchMeta\n /**\n * A promise to use for the first attempt instead of calling `fetchFn`, e.g. a pending promise\n * restored by `hydrate`.\n */\n initialPromise?: Promise<TData>\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction<TData> {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction<TData, TError> {\n type: 'setState'\n state: Partial<QueryState<TData, TError>>\n}\n\n/**\n * The actions a query dispatches to update its state, e.g. when it starts fetching, fails, or\n * succeeds.\n */\nexport type Action<TData, TError> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction<TData, TError>\n | SuccessAction<TData>\n\n// CLASS\n\n/**\n * Represents a single cached query. A `Query` holds the query's key, options,\n * state (data/error/status), and the observers currently subscribed to it.\n *\n * Instances are created and managed internally by `QueryCache`; application\n * code typically interacts with queries indirectly through `QueryClient` or\n * a framework hook like `useQuery`. Direct access to a `Query` instance is\n * possible via `queryCache.find()`/`findAll()` for inspecting cache state.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n * const query = queryCache.find({ queryKey: ['posts'] })\n *\n * if (query) {\n * console.log(query.state.dataUpdatedAt)\n * }\n * ```\n */\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state: QueryState<TData, TError>\n #queryType?: 'infinite'\n\n #initialState: QueryState<TData, TError>\n #revertState?: QueryState<TData, TError>\n #cache: QueryCache\n #client: QueryClient\n #retryer?: Retryer<TData>\n #fetchPromise?: Promise<TData>\n observers: Array<QueryObserver<any, any, any, any, any>>\n #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#client = config.client\n this.#cache = this.#client.getQueryCache()\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n /**\n * The `meta` object passed in the query's options, if any.\n * @returns The query's `meta`, or `undefined` if none was set.\n */\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n /**\n * `'infinite'` for an infinite query, otherwise `undefined`.\n * @internal\n * @returns The type of the query, set from the `_type` option (e.g. `'infinite'`).\n */\n get queryType() {\n return this.#queryType\n }\n\n /**\n * The promise for the currently in-flight fetch, if the query is fetching.\n * `undefined` when the query is not fetching.\n * @returns The promise of the in-flight fetch, or `undefined`.\n */\n get promise(): Promise<TData> | undefined {\n return this.#retryer?.promise\n }\n\n /**\n * Replaces the query's options and applies their `gcTime`. If the query has no data yet, it gets\n * the `initialData` from the new options, if any.\n * @internal\n * @param options - The new query options, merged on top of the query's default options.\n */\n setOptions(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n if (options?._type) {\n this.#queryType = options._type\n }\n\n this.updateGcTime(this.options.gcTime)\n\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- the constructor calls 'setOptions' before it assigns 'state'\n if (this.state && this.state.data === undefined) {\n const defaultState = getDefaultState(this.options)\n if (defaultState.data !== undefined) {\n this.setState(\n successState(defaultState.data, defaultState.dataUpdatedAt),\n )\n this.#initialState = defaultState\n }\n }\n }\n\n protected override optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n /**\n * Writes new data to the query and marks it as successfully fetched.\n * @internal\n * @param newData - The data to write. Structural sharing with the current data is applied.\n * @param options - Set `updatedAt` to override the timestamp, and `manual` to mark the write as\n * manual (e.g. from `queryClient.setQueryData`).\n * @returns The data that was written.\n */\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n /**\n * Merges the given partial state directly into this query's state, notifying observers. Used\n * by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a\n * user manually trigger a loading/error state or edit the cached data.\n * @param state - The partial state to merge into the query's state.\n */\n setState(state: Partial<QueryState<TData, TError>>): void {\n this.#dispatch({ type: 'setState', state })\n }\n\n /**\n * Cancels the query's currently in-flight fetch, if any.\n * - Returns a promise that resolves once the cancellation has settled.\n * - If no fetch is in progress, resolves immediately.\n * @param options - Set `revert` to restore the state from before the fetch started, and `silent`\n * to suppress the cancellation error when a new fetch replaces the cancelled one.\n * @returns A promise that resolves once the cancellation has settled.\n * @example\n * ```ts\n * await query.cancel()\n * ```\n */\n cancel(options?: CancelOptions): Promise<void> {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n /**\n * Clears the query's garbage collection timeout and silently cancels any\n * in-flight fetch. Called by `QueryCache` when the query is removed from\n * the cache.\n * @see {@link Query#cancel}\n */\n override destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n /**\n * The state the query was created with.\n * @internal\n * @returns The state the query had when it was first created, used by {@link Query#reset}.\n */\n get resetState(): QueryState<TData, TError> {\n return this.#initialState\n }\n\n /**\n * Resets the query back to its initial state (the state it had when it was\n * first created, e.g. any `initialData`), destroying it first to cancel any\n * in-flight fetch.\n */\n reset(): void {\n this.destroy()\n this.setState(this.resetState)\n }\n\n /**\n * Returns `true` if the query has at least one observer for which `enabled`\n * does not resolve to `false`.\n * @returns `true` if the query has an enabled observer.\n */\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveQueryValue(observer.options.enabled, this) !== false,\n )\n }\n\n /**\n * Returns `true` if the query is disabled, meaning it will not fetch\n * automatically.\n * - If the query has observers, it is disabled when none of them are active\n * (see `isActive`).\n * - If the query has no observers, it is disabled when its `queryFn` is\n * `skipToken` or it has never been fetched.\n * @returns `true` if the query is disabled.\n */\n isDisabled(): boolean {\n if (this.getObserversCount() > 0) {\n return !this.isActive()\n }\n // if a query has no observers, it should still be considered disabled if it never attempted a fetch\n return this.options.queryFn === skipToken || !this.isFetched()\n }\n\n /**\n * Returns `true` if the query has been fetched, i.e. it has resolved with\n * either data or an error at least once.\n * @returns `true` if the query has been fetched.\n */\n isFetched() {\n return this.state.dataUpdateCount + this.state.errorUpdateCount > 0\n }\n\n /**\n * Returns `true` if the query has data and at least one observer configured with\n * `staleTime: 'static'`, meaning it is treated as never stale.\n * @returns `true` if the query is static.\n */\n isStatic(): boolean {\n if (this.state.data === undefined) {\n return false\n }\n\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) =>\n resolveQueryValue(observer.options.staleTime, this) === 'static',\n )\n }\n\n return false\n }\n\n /**\n * Returns `true` if the query is stale.\n * - If the query has observers, defers to whether any observer's current\n * result reports `isStale` (which accounts for each observer's own\n * `staleTime` and `enabled` state).\n * - If the query has no observers, it is considered stale when it has no\n * data or has been invalidated.\n * @returns `true` if the query is stale.\n * @see {@link Query#isStaleByTime}\n * @example\n * ```ts\n * if (query.isStale()) {\n * // refetch or otherwise treat the cached data as outdated\n * }\n * ```\n */\n isStale(): boolean {\n // check observers first, their `isStale` has the source of truth\n // calculated with `isStaleByTime` and it takes `enabled` into account\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined || this.state.isInvalidated\n }\n\n /**\n * Returns `true` if the query's data is stale relative to the given\n * `staleTime` (defaults to `0`).\n * - A query with no data is always stale.\n * - `staleTime: 'static'` is never stale.\n * - An invalidated query is always stale.\n * - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`.\n * @param staleTime - The time, in milliseconds, after which data is considered stale, or\n * `'static'` to never treat existing data as stale. A query without data is stale either way.\n * @returns `true` if the query's data is stale.\n * @see {@link Query#isStale}\n * @example\n * ```ts\n * const isStale = query.isStaleByTime(60 * 1000)\n * ```\n */\n isStaleByTime(staleTime: StaleTime = 0): boolean {\n // no data is always stale\n if (this.state.data === undefined) {\n return true\n }\n // static is never stale\n if (staleTime === 'static') {\n return false\n }\n // if the query is invalidated, it is stale\n if (this.state.isInvalidated) {\n return true\n }\n\n return !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n }\n\n /**\n * Refetches the query when the window regains focus, if an observer wants that, and continues a\n * paused fetch.\n * @internal\n */\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n /**\n * Refetches the query when the app reconnects, if an observer wants that, and continues a paused\n * fetch.\n * @internal\n */\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n /**\n * Subscribes an observer to the query and stops its garbage collection.\n * @internal\n * @param observer - The observer to add. Adding an observer that is already subscribed does\n * nothing.\n */\n addObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n /**\n * Unsubscribes an observer from the query.\n * @internal\n * @param observer - The observer to remove. When the last observer is removed, the in-flight\n * fetch is cancelled if its abort signal was consumed (otherwise only its retries are stopped),\n * and garbage collection is scheduled.\n */\n removeObserver(observer: QueryObserver<any, any, any, any, any>): void {\n const index = this.observers.indexOf(observer)\n if (index !== -1) {\n this.observers.splice(index, 1)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (\n this.#abortSignalConsumed ||\n (this.state.fetchStatus === 'paused' &&\n this.state.status === 'pending')\n ) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n /**\n * Returns the number of observers currently subscribed to this query.\n * @returns The number of observers.\n * @example\n * ```ts\n * if (query.getObserversCount() === 0) {\n * // no component is currently watching this query\n * }\n * ```\n */\n getObserversCount(): number {\n return this.observers.length\n }\n\n /**\n * Marks the query as invalidated, unless it is already invalidated. This\n * updates `state.isInvalidated` and notifies observers, but does not by\n * itself trigger a refetch.\n * @example\n * ```ts\n * query.invalidate()\n * ```\n */\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n /**\n * Fetches the query, i.e. runs its `queryFn` (through any configured\n * retryer/behavior) and updates the query's state with the result.\n * - If a fetch is already in flight, returns its promise instead of\n * starting a new one, unless `fetchOptions.cancelRefetch` is set and the\n * query already has data, in which case the current fetch is silently\n * cancelled first.\n * - If `options` is passed, it replaces the query's current options\n * before fetching.\n * @param options - Query options that replace the query's current options before fetching. They\n * are not applied when an in-flight fetch is reused.\n * @param fetchOptions - Set `cancelRefetch` to cancel an in-flight fetch first (only if the query\n * already has data), and `meta` to pass extra information to the query's behavior.\n * @returns A promise that resolves with the fetched data, or rejects with the fetch error. If the\n * fetch is cancelled with `revert` while the query has data, it resolves with the restored data\n * instead.\n */\n async fetch(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n fetchOptions?: FetchOptions<TQueryFnData>,\n ): Promise<TData> {\n if (\n this.state.fetchStatus !== 'idle' &&\n // If the promise in the retryer is already rejected, we have to definitely\n // re-start the fetch; there is a chance that the query is still in a\n // pending state when that happens\n this.#retryer?.status() !== 'rejected'\n ) {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer && this.#fetchPromise) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#fetchPromise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: object) => {\n Object.defineProperties(object, {\n [fetchSignal]: { value: abortController.signal, enumerable: true },\n signal: {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const createQueryFnContext = (): QueryFunctionContext<TQueryKey> => {\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<TQueryKey>,\n 'signal'\n > = {\n client: this.#client,\n queryKey: this.queryKey,\n meta: this.meta,\n }\n addSignalProperty(queryFnContext)\n return queryFnContext as QueryFunctionContext<TQueryKey>\n }\n\n const queryFnContext = createQueryFnContext()\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn,\n queryFnContext,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext)\n }\n\n // Trigger behavior hook\n const createFetchContext = (): FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n > => {\n const context: OmitKeyof<\n FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n client: this.#client,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n return context as FetchContext<TQueryFnData, TError, TData, TQueryKey>\n }\n\n const context = createFetchContext()\n\n const behavior =\n this.#queryType === 'infinite'\n ? (infiniteQueryBehavior(\n (this.options as { pages?: number }).pages,\n ) as QueryBehavior<TQueryFnData, TError, TData, TQueryKey>)\n : this.options.behavior\n behavior?.onFetch(context, this as unknown as Query)\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n // Try to fetch the data\n const retryer = (this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise<TData>\n | undefined,\n fn: context.fetchFn as () => Promise<TData>,\n onCancel: (error) => {\n if (error instanceof CancelledError && error.revert) {\n this.setState({\n ...this.#revertState,\n fetchStatus: 'idle' as const,\n })\n }\n abortController.abort()\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n }))\n\n const fetchPromise = (async () => {\n try {\n const data = await retryer.promise\n // this is more of a runtime guard\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n throw new Error(`${this.queryHash} data is undefined`)\n }\n\n this.setData(data)\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query<any, any, any, any>,\n )\n return data\n } catch (error) {\n if (error instanceof CancelledError) {\n if (error.silent) {\n if (this.#retryer !== retryer && this.#fetchPromise) {\n // A new fetch replaced the silently cancelled one,\n // so we piggyback onto that promise.\n return this.#fetchPromise\n }\n throw error\n } else if (error.revert) {\n // transform error into reverted state data\n // if the initial fetch was cancelled, we have no data, so we have\n // to get reject with a CancelledError\n if (this.state.data === undefined) {\n throw error\n }\n return this.state.data\n }\n }\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query<any, any, any, any>,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query<any, any, any, any>,\n )\n\n throw error // rethrow the error for further handling\n } finally {\n // The settled retryer's promise would otherwise pin this fetch's raw\n // result (a second copy after structural sharing) for the query's lifetime\n if (this.#retryer === retryer) {\n this.#retryer = undefined\n this.#fetchPromise = undefined\n }\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n })()\n this.#fetchPromise = fetchPromise\n retryer.start()\n return fetchPromise\n }\n\n #dispatch(action: Action<TData, TError>): void {\n const reducer = (\n state: QueryState<TData, TError>,\n ): QueryState<TData, TError> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success': {\n const newState = {\n ...state,\n ...successState(action.data, action.dataUpdatedAt),\n dataUpdateCount: state.dataUpdateCount + 1,\n ...(!action.manual && {\n fetchStatus: 'idle' as const,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n // If fetching ends successfully, we don't need revertState as a fallback anymore.\n // For manual updates, capture the state to revert to it in case of a cancellation.\n this.#revertState = action.manual ? newState : undefined\n\n return newState\n }\n case 'error': {\n const error = action.error\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n // flag existing data as invalidated if we get a background error\n // note that \"no data\" always means stale so we can set unconditionally here\n isInvalidated: true,\n }\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n // Keep the current iteration stable if an observer unsubscribes\n // synchronously while it is being notified.\n this.observers.slice().forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\n/**\n * Returns the state changes applied when a query starts fetching.\n * @param data - The query's current data. If it is `undefined`, the query is also reset to\n * `'pending'` with no error.\n * @param options - The query options, whose `networkMode` decides whether the query is `'fetching'`\n * or `'paused'`.\n * @returns The partial query state for a starting fetch.\n */\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\n/**\n * Returns the state changes applied when a query receives data.\n * @param data - The new data.\n * @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to the current time.\n * @returns The partial query state for a successful update.\n */\nfunction successState<TData>(data: TData | undefined, dataUpdatedAt?: number) {\n return {\n data,\n dataUpdatedAt: dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success' as const,\n }\n}\n\n/**\n * Returns the initial state of a query, based on its `initialData` and `initialDataUpdatedAt`\n * options.\n * @param options - The query options.\n * @returns The initial query state: `'success'` if `initialData` is set, otherwise `'pending'`.\n */\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): QueryState<TData, TError> {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction<TData>)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? options.initialDataUpdatedAt()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2RA,IAAa,QAAb,cAKUA,kBAAAA,UAAU;CAiBlB,YAAY,QAA6D;EACvE,MAAM;;;;;;;;;;;EAEN,8BAAA,uBAAA,sBAAA,MAA4B,KAAA;EAC5B,8BAAA,uBAAA,iBAAA,MAAuB,OAAO,cAAA;EAC9B,KAAK,WAAW,OAAO,OAAO;EAC9B,KAAK,YAAY,CAAC;EAClB,8BAAA,uBAAA,SAAA,MAAe,OAAO,MAAA;EACtB,8BAAA,uBAAA,QAAA,MAAA,8BAAA,uBAAA,SAAc,IAAA,CAAA,CAAa,cAAc,CAAA;EACzC,KAAK,WAAW,OAAO;EACvB,KAAK,YAAY,OAAO;EACxB,8BAAA,uBAAA,eAAA,MAAqB,gBAAgB,KAAK,OAAO,CAAA;EACjD,KAAK,QAAQ,OAAO,SAAA,8BAAA,uBAAA,eAAS,IAAA;EAC7B,KAAK,WAAW;CAClB;;;;;CAKA,IAAI,OAA8B;EAChC,OAAO,KAAK,QAAQ;CACtB;;;;;;CAOA,IAAI,YAAY;EACd,OAAA,8BAAA,uBAAA,YAAO,IAAA;CACT;;;;;;CAOA,IAAI,UAAsC;;EACxC,QAAA,2BAAA,8BAAA,uBAAA,UAAO,IAAA,OAAA,QAAA,6BAAA,KAAA,IAAA,KAAA,IAAA,yBAAe;CACxB;;;;;;;CAQA,WACE,SACM;EACN,KAAK,UAAU;GAAE,GAAA,8BAAA,uBAAA,iBAAG,IAAA;GAAsB,GAAG;EAA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O;EACL,mBAAmB;EACnB,oBAAoB;EACpB,aAAaC,gBAAAA,SAAS,QAAQ,WAAW,IAAI,aAAa;EAC1D,GAAI,SAAS,KAAA,KACV;GACC,OAAO;GACP,QAAQ;EACV;CACJ;AACF;;;;;;;AAQA,SAAS,aAAoB,MAAyB,eAAwB;CAC5E,OAAO;EACL;EACA,eAAe,iBAAiB,KAAK,IAAI;EACzC,OAAO;EACP,eAAe;EACf,QAAQ;CACV;AACF;;;;;;;AAQA,SAAS,gBAMP,SAC2B;CAC3B,MAAM,OACJ,OAAO,QAAQ,gBAAgB,aAC1B,QAAQ,YAA2C,IACpD,QAAQ;CAEd,MAAM,UAAU,SAAS,KAAA;CAEzB,MAAM,uBAAuB,UACzB,OAAO,QAAQ,yBAAyB,aACtC,QAAQ,qBAAqB,IAC7B,QAAQ,uBACV;CAEJ,OAAO;EACL;EACA,iBAAiB;EACjB,eAAe,UAAW,wBAAwB,KAAK,IAAI,IAAK;EAChE,OAAO;EACP,kBAAkB;EAClB,gBAAgB;EAChB,mBAAmB;EACnB,oBAAoB;EACpB,WAAW;EACX,eAAe;EACf,QAAQ,UAAU,YAAY;EAC9B,aAAa;CACf;AACF"}
@@ -1,2 +1,2 @@
1
- import { $n as FetchMeta, Qn as FetchDirection, Xn as Action, Zn as FetchContext, er as FetchOptions, ir as fetchState, nr as QueryBehavior, rr as QueryState, tr as Query } from "./hydration-BIRJt69T.cjs";
1
+ import { A as fetchState, C as FetchContext, D as Query, E as FetchOptions, O as QueryBehavior, S as Action, T as FetchMeta, k as QueryState, w as FetchDirection } from "./hydration-24GwbSaU.cjs";
2
2
  export { Action, FetchContext, FetchDirection, FetchMeta, FetchOptions, Query, QueryBehavior, QueryState, fetchState };
@@ -1,2 +1,2 @@
1
- import { $n as FetchMeta, Qn as FetchDirection, Xn as Action, Zn as FetchContext, er as FetchOptions, ir as fetchState, nr as QueryBehavior, rr as QueryState, tr as Query } from "./hydration-9_kOYxJM.js";
1
+ import { A as fetchState, C as FetchContext, D as Query, E as FetchOptions, O as QueryBehavior, S as Action, T as FetchMeta, k as QueryState, w as FetchDirection } from "./hydration-Cbq_heQS.js";
2
2
  export { Action, FetchContext, FetchDirection, FetchMeta, FetchOptions, Query, QueryBehavior, QueryState, fetchState };
@@ -1,9 +1,9 @@
1
1
  import { i as _classPrivateFieldInitSpec, n as _classPrivateFieldGet2, r as _assertClassBrand, t as _classPrivateFieldSet2 } from "./classPrivateFieldSet2-CWIQ5CvM.js";
2
2
  import { ensureQueryFn, fetchSignal, noop, replaceData, resolveQueryValue, skipToken, timeUntilStale } from "./utils.js";
3
+ import { infiniteQueryBehavior } from "./infiniteQueryBehavior.js";
3
4
  import { notifyManager } from "./notifyManager.js";
4
- import { CancelledError, canFetch, createRetryer } from "./retryer.js";
5
5
  import { Removable } from "./removable.js";
6
- import { infiniteQueryBehavior } from "./infiniteQueryBehavior.js";
6
+ import { CancelledError, canFetch, createRetryer } from "./retryer.js";
7
7
  import { t as _classPrivateMethodInitSpec } from "./classPrivateMethodInitSpec-DipaBicy.js";
8
8
  // src/query.ts
9
9
  var _queryType = /* @__PURE__ */ new WeakMap();
@@ -533,7 +533,7 @@ function _dispatch(action) {
533
533
  ...fetchState(state.data, this.options),
534
534
  fetchMeta: action.meta ?? null
535
535
  };
536
- case "success":
536
+ case "success": {
537
537
  const newState = {
538
538
  ...state,
539
539
  ...successState(action.data, action.dataUpdatedAt),
@@ -546,7 +546,8 @@ function _dispatch(action) {
546
546
  };
547
547
  _classPrivateFieldSet2(_revertState, this, action.manual ? newState : void 0);
548
548
  return newState;
549
- case "error":
549
+ }
550
+ case "error": {
550
551
  const error = action.error;
551
552
  return {
552
553
  ...state,
@@ -559,6 +560,7 @@ function _dispatch(action) {
559
560
  status: "error",
560
561
  isInvalidated: true
561
562
  };
563
+ }
562
564
  case "invalidate": return {
563
565
  ...state,
564
566
  isInvalidated: true
@@ -1 +1 @@
1
- {"version":3,"file":"query.js","names":[],"sources":["../../src/query.ts"],"sourcesContent":["import {\n ensureQueryFn,\n fetchSignal,\n noop,\n replaceData,\n resolveQueryValue,\n skipToken,\n timeUntilStale,\n} from './utils'\nimport { notifyManager } from './notifyManager'\nimport { CancelledError, canFetch, createRetryer } from './retryer'\nimport { Removable } from './removable'\nimport { infiniteQueryBehavior } from './infiniteQueryBehavior'\nimport type { QueryCache } from './queryCache'\nimport type { QueryClient } from './queryClient'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n StaleTime,\n} from './types'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n client: QueryClient\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state?: QueryState<TData, TError>\n}\n\n/**\n * The raw state stored on a `Query` instance. This is the underlying state\n * that observer results (e.g. `QueryObserverResult`) are derived from.\n */\nexport interface QueryState<TData = unknown, TError = DefaultError> {\n /**\n * The last successfully resolved data for the query.\n */\n data: TData | undefined\n /**\n * The number of times the query has successfully resolved.\n */\n dataUpdateCount: number\n /**\n * The timestamp for when the query most recently returned the `status` as `\"success\"`.\n */\n dataUpdatedAt: number\n /**\n * The error object for the query, if the last attempt resulted in an error.\n * - Defaults to `null`.\n */\n error: TError | null\n /**\n * The sum of all errors, incremented every time the query resolves with an error.\n */\n errorUpdateCount: number\n /**\n * The timestamp for when the query most recently returned the `status` as `\"error\"`.\n */\n errorUpdatedAt: number\n /**\n * The failure count for the current fetch.\n * - Incremented every time the fetch fails.\n * - Reset to `0` when the fetch succeeds.\n */\n fetchFailureCount: number\n /**\n * The reason the current fetch failed, as reported by the retryer.\n * - Reset to `null` when the fetch succeeds.\n */\n fetchFailureReason: TError | null\n /**\n * Metadata passed to the currently in-flight (or most recent) fetch, e.g. the\n * `fetchMore` direction for infinite queries.\n */\n fetchMeta: FetchMeta | null\n /**\n * Whether the query has been marked as invalidated via `invalidate()`.\n * - Reset to `false` whenever the query resolves successfully.\n */\n isInvalidated: boolean\n /**\n * The status of the query.\n * - `pending` if there's no cached data and no attempt was finished yet.\n * - `error` if the last attempt resulted in an error.\n * - `success` if the query has data.\n */\n status: QueryStatus\n /**\n * The fetch status of the query.\n * - `fetching`: the `queryFn` is currently executing.\n * - `paused`: a fetch wanted to run but has been paused (see network mode).\n * - `idle`: the query is not fetching.\n */\n fetchStatus: FetchStatus\n}\n\n/**\n * The context passed to a {@link QueryBehavior}'s `onFetch`, which can replace `fetchFn` to change\n * how the query fetches (e.g. to fetch pages for an infinite query).\n */\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n /**\n * The function that runs the fetch. By default it calls `queryFn`; `onFetch` can replace it.\n */\n fetchFn: () => unknown | Promise<unknown>\n /**\n * The options of this fetch.\n */\n fetchOptions?: FetchOptions\n /**\n * The `AbortSignal` that aborts when the fetch is cancelled.\n */\n signal: AbortSignal\n /**\n * The options of the query.\n */\n options: QueryOptions<TQueryFnData, TError, TData, any>\n /**\n * The `QueryClient` the query belongs to.\n */\n client: QueryClient\n /**\n * The key of the query.\n */\n queryKey: TQueryKey\n /**\n * The state of the query when the fetch starts.\n */\n state: QueryState<TData, TError>\n}\n\n/**\n * Customizes how a query fetches, e.g. the behavior that fetches the pages of an infinite query.\n */\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n /**\n * Called before each fetch of the query, e.g. to replace `fetchFn` in the context.\n */\n onFetch: (\n context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n query: Query,\n ) => void\n}\n\n/**\n * The direction an infinite query fetches in: `'forward'` for the next page, `'backward'` for the\n * previous one.\n */\nexport type FetchDirection = 'forward' | 'backward'\n\n/**\n * Metadata for a fetch, e.g. the direction when an infinite query fetches more pages.\n */\nexport interface FetchMeta {\n /**\n * Set when an infinite query fetches another page, with the direction to fetch in.\n */\n fetchMore?: { direction: FetchDirection }\n}\n\n/**\n * Options for a single fetch of a query.\n */\nexport interface FetchOptions<TData = unknown> {\n /**\n * If `true`, an in-flight fetch is cancelled before starting a new one, when the query already\n * has data. Otherwise, the in-flight fetch is reused.\n */\n cancelRefetch?: boolean\n /**\n * Metadata of the fetch, stored in the query's `fetchMeta` state.\n */\n meta?: FetchMeta\n /**\n * A promise to use for the first attempt instead of calling `fetchFn`, e.g. a pending promise\n * restored by `hydrate`.\n */\n initialPromise?: Promise<TData>\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction<TData> {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction<TData, TError> {\n type: 'setState'\n state: Partial<QueryState<TData, TError>>\n}\n\n/**\n * The actions a query dispatches to update its state, e.g. when it starts fetching, fails, or\n * succeeds.\n */\nexport type Action<TData, TError> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction<TData, TError>\n | SuccessAction<TData>\n\n// CLASS\n\n/**\n * Represents a single cached query. A `Query` holds the query's key, options,\n * state (data/error/status), and the observers currently subscribed to it.\n *\n * Instances are created and managed internally by `QueryCache`; application\n * code typically interacts with queries indirectly through `QueryClient` or\n * a framework hook like `useQuery`. Direct access to a `Query` instance is\n * possible via `queryCache.find()`/`findAll()` for inspecting cache state.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n * const query = queryCache.find({ queryKey: ['posts'] })\n *\n * if (query) {\n * console.log(query.state.dataUpdatedAt)\n * }\n * ```\n */\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state: QueryState<TData, TError>\n #queryType?: 'infinite'\n\n #initialState: QueryState<TData, TError>\n #revertState?: QueryState<TData, TError>\n #cache: QueryCache\n #client: QueryClient\n #retryer?: Retryer<TData>\n #fetchPromise?: Promise<TData>\n observers: Array<QueryObserver<any, any, any, any, any>>\n #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#client = config.client\n this.#cache = this.#client.getQueryCache()\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n /**\n * The `meta` object passed in the query's options, if any.\n * @returns The query's `meta`, or `undefined` if none was set.\n */\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n /**\n * `'infinite'` for an infinite query, otherwise `undefined`.\n * @internal\n * @returns The type of the query, set from the `_type` option (e.g. `'infinite'`).\n */\n get queryType() {\n return this.#queryType\n }\n\n /**\n * The promise for the currently in-flight fetch, if the query is fetching.\n * `undefined` when the query is not fetching.\n * @returns The promise of the in-flight fetch, or `undefined`.\n */\n get promise(): Promise<TData> | undefined {\n return this.#retryer?.promise\n }\n\n /**\n * Replaces the query's options and applies their `gcTime`. If the query has no data yet, it gets\n * the `initialData` from the new options, if any.\n * @internal\n * @param options - The new query options, merged on top of the query's default options.\n */\n setOptions(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n if (options?._type) {\n this.#queryType = options._type\n }\n\n this.updateGcTime(this.options.gcTime)\n\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- the constructor calls 'setOptions' before it assigns 'state'\n if (this.state && this.state.data === undefined) {\n const defaultState = getDefaultState(this.options)\n if (defaultState.data !== undefined) {\n this.setState(\n successState(defaultState.data, defaultState.dataUpdatedAt),\n )\n this.#initialState = defaultState\n }\n }\n }\n\n protected override optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n /**\n * Writes new data to the query and marks it as successfully fetched.\n * @internal\n * @param newData - The data to write. Structural sharing with the current data is applied.\n * @param options - Set `updatedAt` to override the timestamp, and `manual` to mark the write as\n * manual (e.g. from `queryClient.setQueryData`).\n * @returns The data that was written.\n */\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n /**\n * Merges the given partial state directly into this query's state, notifying observers. Used\n * by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a\n * user manually trigger a loading/error state or edit the cached data.\n * @param state - The partial state to merge into the query's state.\n */\n setState(state: Partial<QueryState<TData, TError>>): void {\n this.#dispatch({ type: 'setState', state })\n }\n\n /**\n * Cancels the query's currently in-flight fetch, if any.\n * - Returns a promise that resolves once the cancellation has settled.\n * - If no fetch is in progress, resolves immediately.\n * @param options - Set `revert` to restore the state from before the fetch started, and `silent`\n * to suppress the cancellation error when a new fetch replaces the cancelled one.\n * @returns A promise that resolves once the cancellation has settled.\n * @example\n * ```ts\n * await query.cancel()\n * ```\n */\n cancel(options?: CancelOptions): Promise<void> {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n /**\n * Clears the query's garbage collection timeout and silently cancels any\n * in-flight fetch. Called by `QueryCache` when the query is removed from\n * the cache.\n * @see {@link Query#cancel}\n */\n override destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n /**\n * The state the query was created with.\n * @internal\n * @returns The state the query had when it was first created, used by {@link Query#reset}.\n */\n get resetState(): QueryState<TData, TError> {\n return this.#initialState\n }\n\n /**\n * Resets the query back to its initial state (the state it had when it was\n * first created, e.g. any `initialData`), destroying it first to cancel any\n * in-flight fetch.\n */\n reset(): void {\n this.destroy()\n this.setState(this.resetState)\n }\n\n /**\n * Returns `true` if the query has at least one observer for which `enabled`\n * does not resolve to `false`.\n * @returns `true` if the query has an enabled observer.\n */\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveQueryValue(observer.options.enabled, this) !== false,\n )\n }\n\n /**\n * Returns `true` if the query is disabled, meaning it will not fetch\n * automatically.\n * - If the query has observers, it is disabled when none of them are active\n * (see `isActive`).\n * - If the query has no observers, it is disabled when its `queryFn` is\n * `skipToken` or it has never been fetched.\n * @returns `true` if the query is disabled.\n */\n isDisabled(): boolean {\n if (this.getObserversCount() > 0) {\n return !this.isActive()\n }\n // if a query has no observers, it should still be considered disabled if it never attempted a fetch\n return this.options.queryFn === skipToken || !this.isFetched()\n }\n\n /**\n * Returns `true` if the query has been fetched, i.e. it has resolved with\n * either data or an error at least once.\n * @returns `true` if the query has been fetched.\n */\n isFetched() {\n return this.state.dataUpdateCount + this.state.errorUpdateCount > 0\n }\n\n /**\n * Returns `true` if the query has data and at least one observer configured with\n * `staleTime: 'static'`, meaning it is treated as never stale.\n * @returns `true` if the query is static.\n */\n isStatic(): boolean {\n if (this.state.data === undefined) {\n return false\n }\n\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) =>\n resolveQueryValue(observer.options.staleTime, this) === 'static',\n )\n }\n\n return false\n }\n\n /**\n * Returns `true` if the query is stale.\n * - If the query has observers, defers to whether any observer's current\n * result reports `isStale` (which accounts for each observer's own\n * `staleTime` and `enabled` state).\n * - If the query has no observers, it is considered stale when it has no\n * data or has been invalidated.\n * @returns `true` if the query is stale.\n * @see {@link Query#isStaleByTime}\n * @example\n * ```ts\n * if (query.isStale()) {\n * // refetch or otherwise treat the cached data as outdated\n * }\n * ```\n */\n isStale(): boolean {\n // check observers first, their `isStale` has the source of truth\n // calculated with `isStaleByTime` and it takes `enabled` into account\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined || this.state.isInvalidated\n }\n\n /**\n * Returns `true` if the query's data is stale relative to the given\n * `staleTime` (defaults to `0`).\n * - A query with no data is always stale.\n * - `staleTime: 'static'` is never stale.\n * - An invalidated query is always stale.\n * - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`.\n * @param staleTime - The time, in milliseconds, after which data is considered stale, or\n * `'static'` to never treat existing data as stale. A query without data is stale either way.\n * @returns `true` if the query's data is stale.\n * @see {@link Query#isStale}\n * @example\n * ```ts\n * const isStale = query.isStaleByTime(60 * 1000)\n * ```\n */\n isStaleByTime(staleTime: StaleTime = 0): boolean {\n // no data is always stale\n if (this.state.data === undefined) {\n return true\n }\n // static is never stale\n if (staleTime === 'static') {\n return false\n }\n // if the query is invalidated, it is stale\n if (this.state.isInvalidated) {\n return true\n }\n\n return !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n }\n\n /**\n * Refetches the query when the window regains focus, if an observer wants that, and continues a\n * paused fetch.\n * @internal\n */\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n /**\n * Refetches the query when the app reconnects, if an observer wants that, and continues a paused\n * fetch.\n * @internal\n */\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n /**\n * Subscribes an observer to the query and stops its garbage collection.\n * @internal\n * @param observer - The observer to add. Adding an observer that is already subscribed does\n * nothing.\n */\n addObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n /**\n * Unsubscribes an observer from the query.\n * @internal\n * @param observer - The observer to remove. When the last observer is removed, the in-flight\n * fetch is cancelled if its abort signal was consumed (otherwise only its retries are stopped),\n * and garbage collection is scheduled.\n */\n removeObserver(observer: QueryObserver<any, any, any, any, any>): void {\n const index = this.observers.indexOf(observer)\n if (index !== -1) {\n this.observers.splice(index, 1)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (\n this.#abortSignalConsumed ||\n (this.state.fetchStatus === 'paused' &&\n this.state.status === 'pending')\n ) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n /**\n * Returns the number of observers currently subscribed to this query.\n * @returns The number of observers.\n * @example\n * ```ts\n * if (query.getObserversCount() === 0) {\n * // no component is currently watching this query\n * }\n * ```\n */\n getObserversCount(): number {\n return this.observers.length\n }\n\n /**\n * Marks the query as invalidated, unless it is already invalidated. This\n * updates `state.isInvalidated` and notifies observers, but does not by\n * itself trigger a refetch.\n * @example\n * ```ts\n * query.invalidate()\n * ```\n */\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n /**\n * Fetches the query, i.e. runs its `queryFn` (through any configured\n * retryer/behavior) and updates the query's state with the result.\n * - If a fetch is already in flight, returns its promise instead of\n * starting a new one, unless `fetchOptions.cancelRefetch` is set and the\n * query already has data, in which case the current fetch is silently\n * cancelled first.\n * - If `options` is passed, it replaces the query's current options\n * before fetching.\n * @param options - Query options that replace the query's current options before fetching. They\n * are not applied when an in-flight fetch is reused.\n * @param fetchOptions - Set `cancelRefetch` to cancel an in-flight fetch first (only if the query\n * already has data), and `meta` to pass extra information to the query's behavior.\n * @returns A promise that resolves with the fetched data, or rejects with the fetch error. If the\n * fetch is cancelled with `revert` while the query has data, it resolves with the restored data\n * instead.\n */\n async fetch(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n fetchOptions?: FetchOptions<TQueryFnData>,\n ): Promise<TData> {\n if (\n this.state.fetchStatus !== 'idle' &&\n // If the promise in the retryer is already rejected, we have to definitely\n // re-start the fetch; there is a chance that the query is still in a\n // pending state when that happens\n this.#retryer?.status() !== 'rejected'\n ) {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer && this.#fetchPromise) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#fetchPromise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: object) => {\n Object.defineProperties(object, {\n [fetchSignal]: { value: abortController.signal, enumerable: true },\n signal: {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const createQueryFnContext = (): QueryFunctionContext<TQueryKey> => {\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<TQueryKey>,\n 'signal'\n > = {\n client: this.#client,\n queryKey: this.queryKey,\n meta: this.meta,\n }\n addSignalProperty(queryFnContext)\n return queryFnContext as QueryFunctionContext<TQueryKey>\n }\n\n const queryFnContext = createQueryFnContext()\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn,\n queryFnContext,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext)\n }\n\n // Trigger behavior hook\n const createFetchContext = (): FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n > => {\n const context: OmitKeyof<\n FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n client: this.#client,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n return context as FetchContext<TQueryFnData, TError, TData, TQueryKey>\n }\n\n const context = createFetchContext()\n\n const behavior =\n this.#queryType === 'infinite'\n ? (infiniteQueryBehavior(\n (this.options as { pages?: number }).pages,\n ) as QueryBehavior<TQueryFnData, TError, TData, TQueryKey>)\n : this.options.behavior\n behavior?.onFetch(context, this as unknown as Query)\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n // Try to fetch the data\n const retryer = (this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise<TData>\n | undefined,\n fn: context.fetchFn as () => Promise<TData>,\n onCancel: (error) => {\n if (error instanceof CancelledError && error.revert) {\n this.setState({\n ...this.#revertState,\n fetchStatus: 'idle' as const,\n })\n }\n abortController.abort()\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n }))\n\n const fetchPromise = (async () => {\n try {\n const data = await retryer.promise\n // this is more of a runtime guard\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n throw new Error(`${this.queryHash} data is undefined`)\n }\n\n this.setData(data)\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query<any, any, any, any>,\n )\n return data\n } catch (error) {\n if (error instanceof CancelledError) {\n if (error.silent) {\n if (this.#retryer !== retryer && this.#fetchPromise) {\n // A new fetch replaced the silently cancelled one,\n // so we piggyback onto that promise.\n return this.#fetchPromise\n }\n throw error\n } else if (error.revert) {\n // transform error into reverted state data\n // if the initial fetch was cancelled, we have no data, so we have\n // to get reject with a CancelledError\n if (this.state.data === undefined) {\n throw error\n }\n return this.state.data\n }\n }\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query<any, any, any, any>,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query<any, any, any, any>,\n )\n\n throw error // rethrow the error for further handling\n } finally {\n // The settled retryer's promise would otherwise pin this fetch's raw\n // result (a second copy after structural sharing) for the query's lifetime\n if (this.#retryer === retryer) {\n this.#retryer = undefined\n this.#fetchPromise = undefined\n }\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n })()\n this.#fetchPromise = fetchPromise\n retryer.start()\n return fetchPromise\n }\n\n #dispatch(action: Action<TData, TError>): void {\n const reducer = (\n state: QueryState<TData, TError>,\n ): QueryState<TData, TError> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success':\n const newState = {\n ...state,\n ...successState(action.data, action.dataUpdatedAt),\n dataUpdateCount: state.dataUpdateCount + 1,\n ...(!action.manual && {\n fetchStatus: 'idle' as const,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n // If fetching ends successfully, we don't need revertState as a fallback anymore.\n // For manual updates, capture the state to revert to it in case of a cancellation.\n this.#revertState = action.manual ? newState : undefined\n\n return newState\n case 'error':\n const error = action.error\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n // flag existing data as invalidated if we get a background error\n // note that \"no data\" always means stale so we can set unconditionally here\n isInvalidated: true,\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n // Keep the current iteration stable if an observer unsubscribes\n // synchronously while it is being notified.\n this.observers.slice().forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\n/**\n * Returns the state changes applied when a query starts fetching.\n * @param data - The query's current data. If it is `undefined`, the query is also reset to\n * `'pending'` with no error.\n * @param options - The query options, whose `networkMode` decides whether the query is `'fetching'`\n * or `'paused'`.\n * @returns The partial query state for a starting fetch.\n */\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\n/**\n * Returns the state changes applied when a query receives data.\n * @param data - The new data.\n * @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to the current time.\n * @returns The partial query state for a successful update.\n */\nfunction successState<TData>(data: TData | undefined, dataUpdatedAt?: number) {\n return {\n data,\n dataUpdatedAt: dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success' as const,\n }\n}\n\n/**\n * Returns the initial state of a query, based on its `initialData` and `initialDataUpdatedAt`\n * options.\n * @param options - The query options.\n * @returns The initial query state: `'success'` if `initialData` is set, otherwise `'pending'`.\n */\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): QueryState<TData, TError> {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction<TData>)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? options.initialDataUpdatedAt()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2RA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IACH,GAAG,OAAO;GACZ;EACJ;CACF;CAEA,KAAK,QAAQ,QAAQ,KAAK,KAAK;CAE/B,cAAc,YAAY;EAGxB,KAAK,UAAU,MAAM,CAAC,CAAC,SAAS,aAAa;GAC3C,SAAS,cAAc;EACzB,CAAC;EAED,uBAAA,QAAA,IAAA,CAAA,CAAY,OAAO;GAAE,OAAO;GAAM,MAAM;GAAW;EAAO,CAAC;CAC7D,CAAC;AACH;;;;;;;;;AAWF,SAAgB,WAMd,MACA,SACA;CACA,OAAO;EACL,mBAAmB;EACnB,oBAAoB;EACpB,aAAa,SAAS,QAAQ,WAAW,IAAI,aAAa;EAC1D,GAAI,SAAS,KAAA,KACV;GACC,OAAO;GACP,QAAQ;EACV;CACJ;AACF;;;;;;;AAQA,SAAS,aAAoB,MAAyB,eAAwB;CAC5E,OAAO;EACL;EACA,eAAe,iBAAiB,KAAK,IAAI;EACzC,OAAO;EACP,eAAe;EACf,QAAQ;CACV;AACF;;;;;;;AAQA,SAAS,gBAMP,SAC2B;CAC3B,MAAM,OACJ,OAAO,QAAQ,gBAAgB,aAC1B,QAAQ,YAA2C,IACpD,QAAQ;CAEd,MAAM,UAAU,SAAS,KAAA;CAEzB,MAAM,uBAAuB,UACzB,OAAO,QAAQ,yBAAyB,aACtC,QAAQ,qBAAqB,IAC7B,QAAQ,uBACV;CAEJ,OAAO;EACL;EACA,iBAAiB;EACjB,eAAe,UAAW,wBAAwB,KAAK,IAAI,IAAK;EAChE,OAAO;EACP,kBAAkB;EAClB,gBAAgB;EAChB,mBAAmB;EACnB,oBAAoB;EACpB,WAAW;EACX,eAAe;EACf,QAAQ,UAAU,YAAY;EAC9B,aAAa;CACf;AACF"}
1
+ {"version":3,"file":"query.js","names":[],"sources":["../../src/query.ts"],"sourcesContent":["import { infiniteQueryBehavior } from './infiniteQueryBehavior'\nimport { notifyManager } from './notifyManager'\nimport { Removable } from './removable'\nimport { CancelledError, canFetch, createRetryer } from './retryer'\nimport {\n ensureQueryFn,\n fetchSignal,\n noop,\n replaceData,\n resolveQueryValue,\n skipToken,\n timeUntilStale,\n} from './utils'\nimport type { QueryCache } from './queryCache'\nimport type { QueryClient } from './queryClient'\nimport type { QueryObserver } from './queryObserver'\nimport type { Retryer } from './retryer'\nimport type {\n CancelOptions,\n DefaultError,\n FetchStatus,\n InitialDataFunction,\n OmitKeyof,\n QueryFunctionContext,\n QueryKey,\n QueryMeta,\n QueryOptions,\n QueryStatus,\n SetDataOptions,\n StaleTime,\n} from './types'\n\n// TYPES\n\ninterface QueryConfig<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n client: QueryClient\n queryKey: TQueryKey\n queryHash: string\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state?: QueryState<TData, TError>\n}\n\n/**\n * The raw state stored on a `Query` instance. This is the underlying state\n * that observer results (e.g. `QueryObserverResult`) are derived from.\n */\nexport interface QueryState<TData = unknown, TError = DefaultError> {\n /**\n * The last successfully resolved data for the query.\n */\n data: TData | undefined\n /**\n * The number of times the query has successfully resolved.\n */\n dataUpdateCount: number\n /**\n * The timestamp for when the query most recently returned the `status` as `\"success\"`.\n */\n dataUpdatedAt: number\n /**\n * The error object for the query, if the last attempt resulted in an error.\n * - Defaults to `null`.\n */\n error: TError | null\n /**\n * The sum of all errors, incremented every time the query resolves with an error.\n */\n errorUpdateCount: number\n /**\n * The timestamp for when the query most recently returned the `status` as `\"error\"`.\n */\n errorUpdatedAt: number\n /**\n * The failure count for the current fetch.\n * - Incremented every time the fetch fails.\n * - Reset to `0` when the fetch succeeds.\n */\n fetchFailureCount: number\n /**\n * The reason the current fetch failed, as reported by the retryer.\n * - Reset to `null` when the fetch succeeds.\n */\n fetchFailureReason: TError | null\n /**\n * Metadata passed to the currently in-flight (or most recent) fetch, e.g. the\n * `fetchMore` direction for infinite queries.\n */\n fetchMeta: FetchMeta | null\n /**\n * Whether the query has been marked as invalidated via `invalidate()`.\n * - Reset to `false` whenever the query resolves successfully.\n */\n isInvalidated: boolean\n /**\n * The status of the query.\n * - `pending` if there's no cached data and no attempt was finished yet.\n * - `error` if the last attempt resulted in an error.\n * - `success` if the query has data.\n */\n status: QueryStatus\n /**\n * The fetch status of the query.\n * - `fetching`: the `queryFn` is currently executing.\n * - `paused`: a fetch wanted to run but has been paused (see network mode).\n * - `idle`: the query is not fetching.\n */\n fetchStatus: FetchStatus\n}\n\n/**\n * The context passed to a {@link QueryBehavior}'s `onFetch`, which can replace `fetchFn` to change\n * how the query fetches (e.g. to fetch pages for an infinite query).\n */\nexport interface FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n /**\n * The function that runs the fetch. By default it calls `queryFn`; `onFetch` can replace it.\n */\n fetchFn: () => unknown | Promise<unknown>\n /**\n * The options of this fetch.\n */\n fetchOptions?: FetchOptions\n /**\n * The `AbortSignal` that aborts when the fetch is cancelled.\n */\n signal: AbortSignal\n /**\n * The options of the query.\n */\n options: QueryOptions<TQueryFnData, TError, TData, any>\n /**\n * The `QueryClient` the query belongs to.\n */\n client: QueryClient\n /**\n * The key of the query.\n */\n queryKey: TQueryKey\n /**\n * The state of the query when the fetch starts.\n */\n state: QueryState<TData, TError>\n}\n\n/**\n * Customizes how a query fetches, e.g. the behavior that fetches the pages of an infinite query.\n */\nexport interface QueryBehavior<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> {\n /**\n * Called before each fetch of the query, e.g. to replace `fetchFn` in the context.\n */\n onFetch: (\n context: FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n query: Query,\n ) => void\n}\n\n/**\n * The direction an infinite query fetches in: `'forward'` for the next page, `'backward'` for the\n * previous one.\n */\nexport type FetchDirection = 'forward' | 'backward'\n\n/**\n * Metadata for a fetch, e.g. the direction when an infinite query fetches more pages.\n */\nexport interface FetchMeta {\n /**\n * Set when an infinite query fetches another page, with the direction to fetch in.\n */\n fetchMore?: { direction: FetchDirection }\n}\n\n/**\n * Options for a single fetch of a query.\n */\nexport interface FetchOptions<TData = unknown> {\n /**\n * If `true`, an in-flight fetch is cancelled before starting a new one, when the query already\n * has data. Otherwise, the in-flight fetch is reused.\n */\n cancelRefetch?: boolean\n /**\n * Metadata of the fetch, stored in the query's `fetchMeta` state.\n */\n meta?: FetchMeta\n /**\n * A promise to use for the first attempt instead of calling `fetchFn`, e.g. a pending promise\n * restored by `hydrate`.\n */\n initialPromise?: Promise<TData>\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError\n}\n\ninterface FetchAction {\n type: 'fetch'\n meta?: FetchMeta\n}\n\ninterface SuccessAction<TData> {\n data: TData | undefined\n type: 'success'\n dataUpdatedAt?: number\n manual?: boolean\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface InvalidateAction {\n type: 'invalidate'\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\ninterface SetStateAction<TData, TError> {\n type: 'setState'\n state: Partial<QueryState<TData, TError>>\n}\n\n/**\n * The actions a query dispatches to update its state, e.g. when it starts fetching, fails, or\n * succeeds.\n */\nexport type Action<TData, TError> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | FetchAction\n | InvalidateAction\n | PauseAction\n | SetStateAction<TData, TError>\n | SuccessAction<TData>\n\n// CLASS\n\n/**\n * Represents a single cached query. A `Query` holds the query's key, options,\n * state (data/error/status), and the observers currently subscribed to it.\n *\n * Instances are created and managed internally by `QueryCache`; application\n * code typically interacts with queries indirectly through `QueryClient` or\n * a framework hook like `useQuery`. Direct access to a `Query` instance is\n * possible via `queryCache.find()`/`findAll()` for inspecting cache state.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n * const query = queryCache.find({ queryKey: ['posts'] })\n *\n * if (query) {\n * console.log(query.state.dataUpdatedAt)\n * }\n * ```\n */\nexport class Query<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> extends Removable {\n queryKey: TQueryKey\n queryHash: string\n options!: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n state: QueryState<TData, TError>\n #queryType?: 'infinite'\n\n #initialState: QueryState<TData, TError>\n #revertState?: QueryState<TData, TError>\n #cache: QueryCache\n #client: QueryClient\n #retryer?: Retryer<TData>\n #fetchPromise?: Promise<TData>\n observers: Array<QueryObserver<any, any, any, any, any>>\n #defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>\n #abortSignalConsumed: boolean\n\n constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {\n super()\n\n this.#abortSignalConsumed = false\n this.#defaultOptions = config.defaultOptions\n this.setOptions(config.options)\n this.observers = []\n this.#client = config.client\n this.#cache = this.#client.getQueryCache()\n this.queryKey = config.queryKey\n this.queryHash = config.queryHash\n this.#initialState = getDefaultState(this.options)\n this.state = config.state ?? this.#initialState\n this.scheduleGc()\n }\n /**\n * The `meta` object passed in the query's options, if any.\n * @returns The query's `meta`, or `undefined` if none was set.\n */\n get meta(): QueryMeta | undefined {\n return this.options.meta\n }\n\n /**\n * `'infinite'` for an infinite query, otherwise `undefined`.\n * @internal\n * @returns The type of the query, set from the `_type` option (e.g. `'infinite'`).\n */\n get queryType() {\n return this.#queryType\n }\n\n /**\n * The promise for the currently in-flight fetch, if the query is fetching.\n * `undefined` when the query is not fetching.\n * @returns The promise of the in-flight fetch, or `undefined`.\n */\n get promise(): Promise<TData> | undefined {\n return this.#retryer?.promise\n }\n\n /**\n * Replaces the query's options and applies their `gcTime`. If the query has no data yet, it gets\n * the `initialData` from the new options, if any.\n * @internal\n * @param options - The new query options, merged on top of the query's default options.\n */\n setOptions(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n ): void {\n this.options = { ...this.#defaultOptions, ...options }\n\n if (options?._type) {\n this.#queryType = options._type\n }\n\n this.updateGcTime(this.options.gcTime)\n\n // oxlint-disable-next-line typescript/no-unnecessary-condition -- the constructor calls 'setOptions' before it assigns 'state'\n if (this.state && this.state.data === undefined) {\n const defaultState = getDefaultState(this.options)\n if (defaultState.data !== undefined) {\n this.setState(\n successState(defaultState.data, defaultState.dataUpdatedAt),\n )\n this.#initialState = defaultState\n }\n }\n }\n\n protected override optionalRemove() {\n if (!this.observers.length && this.state.fetchStatus === 'idle') {\n this.#cache.remove(this)\n }\n }\n\n /**\n * Writes new data to the query and marks it as successfully fetched.\n * @internal\n * @param newData - The data to write. Structural sharing with the current data is applied.\n * @param options - Set `updatedAt` to override the timestamp, and `manual` to mark the write as\n * manual (e.g. from `queryClient.setQueryData`).\n * @returns The data that was written.\n */\n setData(\n newData: TData,\n options?: SetDataOptions & { manual: boolean },\n ): TData {\n const data = replaceData(this.state.data, newData, this.options)\n\n // Set data and mark it as cached\n this.#dispatch({\n data,\n type: 'success',\n dataUpdatedAt: options?.updatedAt,\n manual: options?.manual,\n })\n\n return data\n }\n\n /**\n * Merges the given partial state directly into this query's state, notifying observers. Used\n * by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a\n * user manually trigger a loading/error state or edit the cached data.\n * @param state - The partial state to merge into the query's state.\n */\n setState(state: Partial<QueryState<TData, TError>>): void {\n this.#dispatch({ type: 'setState', state })\n }\n\n /**\n * Cancels the query's currently in-flight fetch, if any.\n * - Returns a promise that resolves once the cancellation has settled.\n * - If no fetch is in progress, resolves immediately.\n * @param options - Set `revert` to restore the state from before the fetch started, and `silent`\n * to suppress the cancellation error when a new fetch replaces the cancelled one.\n * @returns A promise that resolves once the cancellation has settled.\n * @example\n * ```ts\n * await query.cancel()\n * ```\n */\n cancel(options?: CancelOptions): Promise<void> {\n const promise = this.#retryer?.promise\n this.#retryer?.cancel(options)\n return promise ? promise.then(noop).catch(noop) : Promise.resolve()\n }\n\n /**\n * Clears the query's garbage collection timeout and silently cancels any\n * in-flight fetch. Called by `QueryCache` when the query is removed from\n * the cache.\n * @see {@link Query#cancel}\n */\n override destroy(): void {\n super.destroy()\n\n this.cancel({ silent: true })\n }\n\n /**\n * The state the query was created with.\n * @internal\n * @returns The state the query had when it was first created, used by {@link Query#reset}.\n */\n get resetState(): QueryState<TData, TError> {\n return this.#initialState\n }\n\n /**\n * Resets the query back to its initial state (the state it had when it was\n * first created, e.g. any `initialData`), destroying it first to cancel any\n * in-flight fetch.\n */\n reset(): void {\n this.destroy()\n this.setState(this.resetState)\n }\n\n /**\n * Returns `true` if the query has at least one observer for which `enabled`\n * does not resolve to `false`.\n * @returns `true` if the query has an enabled observer.\n */\n isActive(): boolean {\n return this.observers.some(\n (observer) => resolveQueryValue(observer.options.enabled, this) !== false,\n )\n }\n\n /**\n * Returns `true` if the query is disabled, meaning it will not fetch\n * automatically.\n * - If the query has observers, it is disabled when none of them are active\n * (see `isActive`).\n * - If the query has no observers, it is disabled when its `queryFn` is\n * `skipToken` or it has never been fetched.\n * @returns `true` if the query is disabled.\n */\n isDisabled(): boolean {\n if (this.getObserversCount() > 0) {\n return !this.isActive()\n }\n // if a query has no observers, it should still be considered disabled if it never attempted a fetch\n return this.options.queryFn === skipToken || !this.isFetched()\n }\n\n /**\n * Returns `true` if the query has been fetched, i.e. it has resolved with\n * either data or an error at least once.\n * @returns `true` if the query has been fetched.\n */\n isFetched() {\n return this.state.dataUpdateCount + this.state.errorUpdateCount > 0\n }\n\n /**\n * Returns `true` if the query has data and at least one observer configured with\n * `staleTime: 'static'`, meaning it is treated as never stale.\n * @returns `true` if the query is static.\n */\n isStatic(): boolean {\n if (this.state.data === undefined) {\n return false\n }\n\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) =>\n resolveQueryValue(observer.options.staleTime, this) === 'static',\n )\n }\n\n return false\n }\n\n /**\n * Returns `true` if the query is stale.\n * - If the query has observers, defers to whether any observer's current\n * result reports `isStale` (which accounts for each observer's own\n * `staleTime` and `enabled` state).\n * - If the query has no observers, it is considered stale when it has no\n * data or has been invalidated.\n * @returns `true` if the query is stale.\n * @see {@link Query#isStaleByTime}\n * @example\n * ```ts\n * if (query.isStale()) {\n * // refetch or otherwise treat the cached data as outdated\n * }\n * ```\n */\n isStale(): boolean {\n // check observers first, their `isStale` has the source of truth\n // calculated with `isStaleByTime` and it takes `enabled` into account\n if (this.getObserversCount() > 0) {\n return this.observers.some(\n (observer) => observer.getCurrentResult().isStale,\n )\n }\n\n return this.state.data === undefined || this.state.isInvalidated\n }\n\n /**\n * Returns `true` if the query's data is stale relative to the given\n * `staleTime` (defaults to `0`).\n * - A query with no data is always stale.\n * - `staleTime: 'static'` is never stale.\n * - An invalidated query is always stale.\n * - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`.\n * @param staleTime - The time, in milliseconds, after which data is considered stale, or\n * `'static'` to never treat existing data as stale. A query without data is stale either way.\n * @returns `true` if the query's data is stale.\n * @see {@link Query#isStale}\n * @example\n * ```ts\n * const isStale = query.isStaleByTime(60 * 1000)\n * ```\n */\n isStaleByTime(staleTime: StaleTime = 0): boolean {\n // no data is always stale\n if (this.state.data === undefined) {\n return true\n }\n // static is never stale\n if (staleTime === 'static') {\n return false\n }\n // if the query is invalidated, it is stale\n if (this.state.isInvalidated) {\n return true\n }\n\n return !timeUntilStale(this.state.dataUpdatedAt, staleTime)\n }\n\n /**\n * Refetches the query when the window regains focus, if an observer wants that, and continues a\n * paused fetch.\n * @internal\n */\n onFocus(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n /**\n * Refetches the query when the app reconnects, if an observer wants that, and continues a paused\n * fetch.\n * @internal\n */\n onOnline(): void {\n const observer = this.observers.find((x) => x.shouldFetchOnReconnect())\n\n observer?.refetch({ cancelRefetch: false })\n\n // Continue fetch if currently paused\n this.#retryer?.continue()\n }\n\n /**\n * Subscribes an observer to the query and stops its garbage collection.\n * @internal\n * @param observer - The observer to add. Adding an observer that is already subscribed does\n * nothing.\n */\n addObserver(observer: QueryObserver<any, any, any, any, any>): void {\n if (!this.observers.includes(observer)) {\n this.observers.push(observer)\n\n // Stop the query from being garbage collected\n this.clearGcTimeout()\n\n this.#cache.notify({ type: 'observerAdded', query: this, observer })\n }\n }\n\n /**\n * Unsubscribes an observer from the query.\n * @internal\n * @param observer - The observer to remove. When the last observer is removed, the in-flight\n * fetch is cancelled if its abort signal was consumed (otherwise only its retries are stopped),\n * and garbage collection is scheduled.\n */\n removeObserver(observer: QueryObserver<any, any, any, any, any>): void {\n const index = this.observers.indexOf(observer)\n if (index !== -1) {\n this.observers.splice(index, 1)\n\n if (!this.observers.length) {\n // If the transport layer does not support cancellation\n // we'll let the query continue so the result can be cached\n if (this.#retryer) {\n if (\n this.#abortSignalConsumed ||\n (this.state.fetchStatus === 'paused' &&\n this.state.status === 'pending')\n ) {\n this.#retryer.cancel({ revert: true })\n } else {\n this.#retryer.cancelRetry()\n }\n }\n\n this.scheduleGc()\n }\n\n this.#cache.notify({ type: 'observerRemoved', query: this, observer })\n }\n }\n\n /**\n * Returns the number of observers currently subscribed to this query.\n * @returns The number of observers.\n * @example\n * ```ts\n * if (query.getObserversCount() === 0) {\n * // no component is currently watching this query\n * }\n * ```\n */\n getObserversCount(): number {\n return this.observers.length\n }\n\n /**\n * Marks the query as invalidated, unless it is already invalidated. This\n * updates `state.isInvalidated` and notifies observers, but does not by\n * itself trigger a refetch.\n * @example\n * ```ts\n * query.invalidate()\n * ```\n */\n invalidate(): void {\n if (!this.state.isInvalidated) {\n this.#dispatch({ type: 'invalidate' })\n }\n }\n\n /**\n * Fetches the query, i.e. runs its `queryFn` (through any configured\n * retryer/behavior) and updates the query's state with the result.\n * - If a fetch is already in flight, returns its promise instead of\n * starting a new one, unless `fetchOptions.cancelRefetch` is set and the\n * query already has data, in which case the current fetch is silently\n * cancelled first.\n * - If `options` is passed, it replaces the query's current options\n * before fetching.\n * @param options - Query options that replace the query's current options before fetching. They\n * are not applied when an in-flight fetch is reused.\n * @param fetchOptions - Set `cancelRefetch` to cancel an in-flight fetch first (only if the query\n * already has data), and `meta` to pass extra information to the query's behavior.\n * @returns A promise that resolves with the fetched data, or rejects with the fetch error. If the\n * fetch is cancelled with `revert` while the query has data, it resolves with the restored data\n * instead.\n */\n async fetch(\n options?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n fetchOptions?: FetchOptions<TQueryFnData>,\n ): Promise<TData> {\n if (\n this.state.fetchStatus !== 'idle' &&\n // If the promise in the retryer is already rejected, we have to definitely\n // re-start the fetch; there is a chance that the query is still in a\n // pending state when that happens\n this.#retryer?.status() !== 'rejected'\n ) {\n if (this.state.data !== undefined && fetchOptions?.cancelRefetch) {\n // Silently cancel current fetch if the user wants to cancel refetch\n this.cancel({ silent: true })\n } else if (this.#retryer && this.#fetchPromise) {\n // make sure that retries that were potentially cancelled due to unmounts can continue\n this.#retryer.continueRetry()\n // Return current promise if we are already fetching\n return this.#fetchPromise\n }\n }\n\n // Update config if passed, otherwise the config from the last execution is used\n if (options) {\n this.setOptions(options)\n }\n\n // Use the options from the first observer with a query function if no function is found.\n // This can happen when the query is hydrated or created with setQueryData.\n if (!this.options.queryFn) {\n const observer = this.observers.find((x) => x.options.queryFn)\n if (observer) {\n this.setOptions(observer.options)\n }\n }\n\n if (process.env.NODE_ENV !== 'production') {\n if (!Array.isArray(this.options.queryKey)) {\n console.error(\n `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`,\n )\n }\n }\n\n const abortController = new AbortController()\n\n // Adds an enumerable signal property to the object that\n // which sets abortSignalConsumed to true when the signal\n // is read.\n const addSignalProperty = (object: object) => {\n Object.defineProperties(object, {\n [fetchSignal]: { value: abortController.signal, enumerable: true },\n signal: {\n enumerable: true,\n get: () => {\n this.#abortSignalConsumed = true\n return abortController.signal\n },\n },\n })\n }\n\n // Create fetch function\n const fetchFn = () => {\n const queryFn = ensureQueryFn(this.options, fetchOptions)\n\n // Create query function context\n const createQueryFnContext = (): QueryFunctionContext<TQueryKey> => {\n const queryFnContext: OmitKeyof<\n QueryFunctionContext<TQueryKey>,\n 'signal'\n > = {\n client: this.#client,\n queryKey: this.queryKey,\n meta: this.meta,\n }\n addSignalProperty(queryFnContext)\n return queryFnContext as QueryFunctionContext<TQueryKey>\n }\n\n const queryFnContext = createQueryFnContext()\n\n this.#abortSignalConsumed = false\n if (this.options.persister) {\n return this.options.persister(\n queryFn,\n queryFnContext,\n this as unknown as Query,\n )\n }\n\n return queryFn(queryFnContext)\n }\n\n // Trigger behavior hook\n const createFetchContext = (): FetchContext<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n > => {\n const context: OmitKeyof<\n FetchContext<TQueryFnData, TError, TData, TQueryKey>,\n 'signal'\n > = {\n fetchOptions,\n options: this.options,\n queryKey: this.queryKey,\n client: this.#client,\n state: this.state,\n fetchFn,\n }\n\n addSignalProperty(context)\n return context as FetchContext<TQueryFnData, TError, TData, TQueryKey>\n }\n\n const context = createFetchContext()\n\n const behavior =\n this.#queryType === 'infinite'\n ? (infiniteQueryBehavior(\n (this.options as { pages?: number }).pages,\n ) as QueryBehavior<TQueryFnData, TError, TData, TQueryKey>)\n : this.options.behavior\n behavior?.onFetch(context, this as unknown as Query)\n\n // Store state in case the current fetch needs to be reverted\n this.#revertState = this.state\n\n // Set to fetching state if not already in it\n if (\n this.state.fetchStatus === 'idle' ||\n this.state.fetchMeta !== context.fetchOptions?.meta\n ) {\n this.#dispatch({ type: 'fetch', meta: context.fetchOptions?.meta })\n }\n\n // Try to fetch the data\n const retryer = (this.#retryer = createRetryer({\n initialPromise: fetchOptions?.initialPromise as\n | Promise<TData>\n | undefined,\n fn: context.fetchFn as () => Promise<TData>,\n onCancel: (error) => {\n if (error instanceof CancelledError && error.revert) {\n this.setState({\n ...this.#revertState,\n fetchStatus: 'idle' as const,\n })\n }\n abortController.abort()\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue: () => {\n this.#dispatch({ type: 'continue' })\n },\n retry: context.options.retry,\n retryDelay: context.options.retryDelay,\n networkMode: context.options.networkMode,\n canRun: () => true,\n }))\n\n const fetchPromise = (async () => {\n try {\n const data = await retryer.promise\n // this is more of a runtime guard\n if (data === undefined) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(\n `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`,\n )\n }\n throw new Error(`${this.queryHash} data is undefined`)\n }\n\n this.setData(data)\n\n // Notify cache callback\n this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)\n this.#cache.config.onSettled?.(\n data,\n this.state.error as any,\n this as Query<any, any, any, any>,\n )\n return data\n } catch (error) {\n if (error instanceof CancelledError) {\n if (error.silent) {\n if (this.#retryer !== retryer && this.#fetchPromise) {\n // A new fetch replaced the silently cancelled one,\n // so we piggyback onto that promise.\n return this.#fetchPromise\n }\n throw error\n } else if (error.revert) {\n // transform error into reverted state data\n // if the initial fetch was cancelled, we have no data, so we have\n // to get reject with a CancelledError\n if (this.state.data === undefined) {\n throw error\n }\n return this.state.data\n }\n }\n this.#dispatch({\n type: 'error',\n error: error as TError,\n })\n\n // Notify cache callback\n this.#cache.config.onError?.(\n error as any,\n this as Query<any, any, any, any>,\n )\n this.#cache.config.onSettled?.(\n this.state.data,\n error as any,\n this as Query<any, any, any, any>,\n )\n\n throw error // rethrow the error for further handling\n } finally {\n // The settled retryer's promise would otherwise pin this fetch's raw\n // result (a second copy after structural sharing) for the query's lifetime\n if (this.#retryer === retryer) {\n this.#retryer = undefined\n this.#fetchPromise = undefined\n }\n // Schedule query gc after fetching\n this.scheduleGc()\n }\n })()\n this.#fetchPromise = fetchPromise\n retryer.start()\n return fetchPromise\n }\n\n #dispatch(action: Action<TData, TError>): void {\n const reducer = (\n state: QueryState<TData, TError>,\n ): QueryState<TData, TError> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n fetchFailureCount: action.failureCount,\n fetchFailureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n fetchStatus: 'paused',\n }\n case 'continue':\n return {\n ...state,\n fetchStatus: 'fetching',\n }\n case 'fetch':\n return {\n ...state,\n ...fetchState(state.data, this.options),\n fetchMeta: action.meta ?? null,\n }\n case 'success': {\n const newState = {\n ...state,\n ...successState(action.data, action.dataUpdatedAt),\n dataUpdateCount: state.dataUpdateCount + 1,\n ...(!action.manual && {\n fetchStatus: 'idle' as const,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n }),\n }\n // If fetching ends successfully, we don't need revertState as a fallback anymore.\n // For manual updates, capture the state to revert to it in case of a cancellation.\n this.#revertState = action.manual ? newState : undefined\n\n return newState\n }\n case 'error': {\n const error = action.error\n return {\n ...state,\n error,\n errorUpdateCount: state.errorUpdateCount + 1,\n errorUpdatedAt: Date.now(),\n fetchFailureCount: state.fetchFailureCount + 1,\n fetchFailureReason: error,\n fetchStatus: 'idle',\n status: 'error',\n // flag existing data as invalidated if we get a background error\n // note that \"no data\" always means stale so we can set unconditionally here\n isInvalidated: true,\n }\n }\n case 'invalidate':\n return {\n ...state,\n isInvalidated: true,\n }\n case 'setState':\n return {\n ...state,\n ...action.state,\n }\n }\n }\n\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n // Keep the current iteration stable if an observer unsubscribes\n // synchronously while it is being notified.\n this.observers.slice().forEach((observer) => {\n observer.onQueryUpdate()\n })\n\n this.#cache.notify({ query: this, type: 'updated', action })\n })\n }\n}\n\n/**\n * Returns the state changes applied when a query starts fetching.\n * @param data - The query's current data. If it is `undefined`, the query is also reset to\n * `'pending'` with no error.\n * @param options - The query options, whose `networkMode` decides whether the query is `'fetching'`\n * or `'paused'`.\n * @returns The partial query state for a starting fetch.\n */\nexport function fetchState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n data: TData | undefined,\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n) {\n return {\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused',\n ...(data === undefined &&\n ({\n error: null,\n status: 'pending',\n } as const)),\n } as const\n}\n\n/**\n * Returns the state changes applied when a query receives data.\n * @param data - The new data.\n * @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to the current time.\n * @returns The partial query state for a successful update.\n */\nfunction successState<TData>(data: TData | undefined, dataUpdatedAt?: number) {\n return {\n data,\n dataUpdatedAt: dataUpdatedAt ?? Date.now(),\n error: null,\n isInvalidated: false,\n status: 'success' as const,\n }\n}\n\n/**\n * Returns the initial state of a query, based on its `initialData` and `initialDataUpdatedAt`\n * options.\n * @param options - The query options.\n * @returns The initial query state: `'success'` if `initialData` is set, otherwise `'pending'`.\n */\nfunction getDefaultState<\n TQueryFnData,\n TError,\n TData,\n TQueryKey extends QueryKey,\n>(\n options: QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): QueryState<TData, TError> {\n const data =\n typeof options.initialData === 'function'\n ? (options.initialData as InitialDataFunction<TData>)()\n : options.initialData\n\n const hasData = data !== undefined\n\n const initialDataUpdatedAt = hasData\n ? typeof options.initialDataUpdatedAt === 'function'\n ? options.initialDataUpdatedAt()\n : options.initialDataUpdatedAt\n : 0\n\n return {\n data,\n dataUpdateCount: 0,\n dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0,\n error: null,\n errorUpdateCount: 0,\n errorUpdatedAt: 0,\n fetchFailureCount: 0,\n fetchFailureReason: null,\n fetchMeta: null,\n isInvalidated: false,\n status: hasData ? 'success' : 'pending',\n fetchStatus: 'idle',\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2RA,IAAa,QAAb,cAKU,UAAU;CAiBlB,YAAY,QAA6D;EACvE,MAAM;;;;;;;;;;;EAEN,uBAAA,sBAAA,MAA4B,KAAA;EAC5B,uBAAA,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,KAAK,UAAU,MAAM,CAAC,CAAC,SAAS,aAAa;GAC3C,SAAS,cAAc;EACzB,CAAC;EAED,uBAAA,QAAA,IAAA,CAAA,CAAY,OAAO;GAAE,OAAO;GAAM,MAAM;GAAW;EAAO,CAAC;CAC7D,CAAC;AACH;;;;;;;;;AAWF,SAAgB,WAMd,MACA,SACA;CACA,OAAO;EACL,mBAAmB;EACnB,oBAAoB;EACpB,aAAa,SAAS,QAAQ,WAAW,IAAI,aAAa;EAC1D,GAAI,SAAS,KAAA,KACV;GACC,OAAO;GACP,QAAQ;EACV;CACJ;AACF;;;;;;;AAQA,SAAS,aAAoB,MAAyB,eAAwB;CAC5E,OAAO;EACL;EACA,eAAe,iBAAiB,KAAK,IAAI;EACzC,OAAO;EACP,eAAe;EACf,QAAQ;CACV;AACF;;;;;;;AAQA,SAAS,gBAMP,SAC2B;CAC3B,MAAM,OACJ,OAAO,QAAQ,gBAAgB,aAC1B,QAAQ,YAA2C,IACpD,QAAQ;CAEd,MAAM,UAAU,SAAS,KAAA;CAEzB,MAAM,uBAAuB,UACzB,OAAO,QAAQ,yBAAyB,aACtC,QAAQ,qBAAqB,IAC7B,QAAQ,uBACV;CAEJ,OAAO;EACL;EACA,iBAAiB;EACjB,eAAe,UAAW,wBAAwB,KAAK,IAAI,IAAK;EAChE,OAAO;EACP,kBAAkB;EAClB,gBAAgB;EAChB,mBAAmB;EACnB,oBAAoB;EACpB,WAAW;EACX,eAAe;EACf,QAAQ,UAAU,YAAY;EAC9B,aAAa;CACf;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"queryCache.cjs","names":["Subscribable","hashQueryKeyByOptions","Query","matchQuery"],"sources":["../../src/queryCache.ts"],"sourcesContent":["import { hashQueryKeyByOptions, matchQuery } from './utils'\nimport { Query } from './query'\nimport { notifyManager } from './notifyManager'\nimport { Subscribable } from './subscribable'\nimport type { QueryFilters } from './utils'\nimport type { Action, QueryState } from './query'\nimport type {\n DefaultError,\n NotifyEvent,\n QueryKey,\n QueryOptions,\n WithRequired,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { QueryObserver } from './queryObserver'\n\n// TYPES\n\n/**\n * Global callbacks that fire for every query handled by a `QueryCache`, regardless of which\n * component or observer triggered it. Unlike `QueryClient`'s `defaultOptions`, which a query can\n * override, these callbacks are always called. Unlike `MutationCacheConfig`'s callbacks, these\n * are fire-and-forget: their return value is not awaited before the query settles.\n */\nexport interface QueryCacheConfig {\n /** Called when any query in the cache encounters an error. */\n onError?: (\n error: DefaultError,\n query: Query<unknown, unknown, unknown>,\n ) => void\n /** Called when any query in the cache is successful. */\n onSuccess?: (data: unknown, query: Query<unknown, unknown, unknown>) => void\n /** Called when any query in the cache is settled, either successfully or with an error. */\n onSettled?: (\n data: unknown | undefined,\n error: DefaultError | null,\n query: Query<unknown, unknown, unknown>,\n ) => void\n}\n\ninterface NotifyEventQueryAdded extends NotifyEvent {\n type: 'added'\n query: Query<any, any, any, any>\n}\n\ninterface NotifyEventQueryRemoved extends NotifyEvent {\n type: 'removed'\n query: Query<any, any, any, any>\n}\n\ninterface NotifyEventQueryUpdated extends NotifyEvent {\n type: 'updated'\n query: Query<any, any, any, any>\n action: Action<any, any>\n}\n\ninterface NotifyEventQueryObserverAdded extends NotifyEvent {\n type: 'observerAdded'\n query: Query<any, any, any, any>\n observer: QueryObserver<any, any, any, any, any>\n}\n\ninterface NotifyEventQueryObserverRemoved extends NotifyEvent {\n type: 'observerRemoved'\n query: Query<any, any, any, any>\n observer: QueryObserver<any, any, any, any, any>\n}\n\ninterface NotifyEventQueryObserverResultsUpdated extends NotifyEvent {\n type: 'observerResultsUpdated'\n query: Query<any, any, any, any>\n}\n\ninterface NotifyEventQueryObserverOptionsUpdated extends NotifyEvent {\n type: 'observerOptionsUpdated'\n query: Query<any, any, any, any>\n observer: QueryObserver<any, any, any, any, any>\n}\n\n/**\n * The event passed to a `QueryCache` subscriber. Fired whenever a query is added or removed from\n * the cache, its state is updated (e.g. via `query.setState` or `queryClient.removeQueries`), or\n * one of its observers is added, removed, or has its results or options updated.\n */\nexport type QueryCacheNotifyEvent =\n | NotifyEventQueryAdded\n | NotifyEventQueryRemoved\n | NotifyEventQueryUpdated\n | NotifyEventQueryObserverAdded\n | NotifyEventQueryObserverRemoved\n | NotifyEventQueryObserverResultsUpdated\n | NotifyEventQueryObserverOptionsUpdated\n\ntype QueryCacheListener = (event: QueryCacheNotifyEvent) => void\n\n/**\n * The store a `QueryCache` keeps its queries in, keyed by query hash.\n */\nexport interface QueryStore {\n /**\n * Returns whether a query with the given hash is stored.\n */\n has: (queryHash: string) => boolean\n /**\n * Stores a query under its hash.\n */\n set: (queryHash: string, query: Query) => void\n /**\n * Returns the query with the given hash, if any.\n */\n get: (queryHash: string) => Query | undefined\n /**\n * Removes the query with the given hash.\n */\n delete: (queryHash: string) => void\n /**\n * Returns an iterator over all stored queries.\n */\n values: () => IterableIterator<Query>\n}\n\n// CLASS\n\n/**\n * The `QueryCache` is the storage mechanism for TanStack Query. It stores all the data, meta\n * information, and state of the queries it contains.\n *\n * Normally, you will not interact with the `QueryCache` directly and instead use a `QueryClient`\n * for a specific cache. You can subscribe to it (inherited from `Subscribable`) to be informed of\n * safe/known updates to the cache, such as queries being added, removed, or updated — updates made\n * outside of the cache's own tracked mechanisms (e.g. mutating a query's state object directly) do\n * not notify subscribers.\n * @example\n * ```ts\n * const unsubscribe = queryCache.subscribe((event) => {\n * console.log(event.type, event.query)\n * })\n * ```\n */\nexport class QueryCache extends Subscribable<QueryCacheListener> {\n #queries: QueryStore\n\n constructor(public config: QueryCacheConfig = {}) {\n super()\n this.#queries = new Map<string, Query>()\n }\n\n /**\n * Returns the existing `Query` instance for the given options' `queryKey`/`queryHash`, or\n * builds and adds a new one to the cache if none exists yet. Used by framework adapters and\n * plugins (e.g. broadcast/persistence) that need to get-or-create a `Query` directly, bypassing\n * the reactive `QueryObserver` machinery.\n * @param client - The client the query belongs to, used to default its options.\n * @param options - The query options, including the `queryKey`. A new query is created with the\n * options defaulted by {@link QueryClient#defaultQueryOptions}.\n * @param state - The initial state of a newly created query, e.g. when hydrating. Ignored if the\n * query already exists.\n * @returns The existing or newly created query.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const query = queryCache.build(queryClient, {\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * })\n * ```\n */\n build<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n client: QueryClient,\n options: WithRequired<\n QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'queryKey'\n >,\n state?: QueryState<TData, TError>,\n ): Query<TQueryFnData, TError, TData, TQueryKey> {\n const queryKey = options.queryKey\n const queryHash =\n options.queryHash ?? hashQueryKeyByOptions(queryKey, options)\n let query = this.get<TQueryFnData, TError, TData, TQueryKey>(queryHash)\n\n if (!query) {\n query = new Query({\n client,\n queryKey,\n queryHash,\n options: client.defaultQueryOptions(options),\n state,\n defaultOptions: client.getQueryDefaults(queryKey),\n })\n this.add(query)\n }\n\n return query\n }\n\n /**\n * Adds a query to the cache.\n * @internal\n * @param query - The query to add. If a query with the same hash is already cached, nothing\n * happens.\n */\n add(query: Query<any, any, any, any>): void {\n if (!this.#queries.has(query.queryHash)) {\n this.#queries.set(query.queryHash, query)\n\n this.notify({\n type: 'added',\n query,\n })\n }\n }\n\n /**\n * Destroys the given `Query` and removes it from the cache, notifying subscribers with a\n * `'removed'` event. A no-op if the query is no longer the one currently stored under its hash\n * (e.g. it was already replaced). Used by plugins (e.g. the broadcast client) that mirror\n * removals across `QueryCache` instances.\n * @param query - The query to remove.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n * const query = queryCache.find({ queryKey: ['posts'] })\n *\n * if (query) {\n * queryCache.remove(query)\n * }\n * ```\n */\n remove(query: Query<any, any, any, any>): void {\n const queryInMap = this.#queries.get(query.queryHash)\n\n if (queryInMap === query) {\n query.destroy()\n this.#queries.delete(query.queryHash)\n this.notify({ type: 'removed', query })\n }\n }\n\n /**\n * Removes all queries from the cache.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * queryCache.clear()\n * ```\n */\n clear(): void {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n this.remove(query)\n })\n })\n }\n\n /**\n * Returns the `Query` instance stored under the given `queryHash`, or `undefined` if none\n * exists. Unlike {@link QueryCache#find}, this looks up by the already-computed hash rather\n * than by `QueryFilters`. Used by plugins (e.g. broadcast/hydration) that already have a hash\n * to look up directly.\n * @param queryHash - The hash of the query to look up.\n * @returns The query stored under the hash, or `undefined`.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n * const queryHash = hashKey(['posts'])\n *\n * const query = queryCache.get(queryHash)\n * ```\n */\n get<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n queryHash: string,\n ): Query<TQueryFnData, TError, TData, TQueryKey> | undefined {\n return this.#queries.get(queryHash) as\n | Query<TQueryFnData, TError, TData, TQueryKey>\n | undefined\n }\n\n /**\n * Returns all queries within the cache.\n * @returns Every query in the cache.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const queries = queryCache.getAll()\n * ```\n */\n getAll(): Array<Query> {\n return [...this.#queries.values()]\n }\n\n /**\n * A slightly more advanced method that can be used to get an existing query instance from the\n * cache. This instance not only contains all the state for the query, but all of the instances,\n * and underlying guts of the query as well. If the query does not exist, `undefined` is\n * returned.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about a query in rare scenarios (e.g. looking at `query.state.dataUpdatedAt` to\n * decide whether a query is fresh enough to be used as an initial value).\n * @param filters - The filters to match, including the required `queryKey`. `exact` defaults to\n * `true`.\n * @returns The first matching query, or `undefined`.\n * @see {@link QueryCache#findAll}\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const query = queryCache.find({ queryKey: ['posts'] })\n * ```\n */\n find<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData>(\n filters: WithRequired<QueryFilters, 'queryKey'>,\n ): Query<TQueryFnData, TError, TData> | undefined {\n const defaultedFilters = { exact: true, ...filters }\n\n return this.getAll().find((query) =>\n matchQuery(defaultedFilters, query),\n ) as Query<TQueryFnData, TError, TData> | undefined\n }\n\n /**\n * An even more advanced method that can be used to get existing query instances from the cache\n * that partially match a query key. If no queries match, an empty array is returned.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about queries in rare scenarios.\n * @param filters - The filters to match. Without filters, every query is returned.\n * @returns The matching queries.\n * @see {@link QueryCache#find}\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const queries = queryCache.findAll({ queryKey: ['posts'] })\n * ```\n */\n findAll(filters: QueryFilters<any> = {}): Array<Query> {\n const queries = this.getAll()\n return Object.keys(filters).length > 0\n ? queries.filter((query) => matchQuery(filters, query))\n : queries\n }\n\n /**\n * Notifies every cache listener of an event, in one batch.\n * @internal\n * @param event - The event passed to every listener.\n */\n notify(event: QueryCacheNotifyEvent): void {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(event)\n })\n })\n }\n\n /**\n * Calls {@link Query#onFocus} on every cached query, in one batch.\n * @internal\n */\n onFocus(): void {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n query.onFocus()\n })\n })\n }\n\n /**\n * Calls {@link Query#onOnline} on every cached query, in one batch.\n * @internal\n */\n onOnline(): void {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n query.onOnline()\n })\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA2IA,IAAa,aAAb,cAAgCA,qBAAAA,aAAiC;CAG/D,YAAY,SAAkC,CAAC,GAAG;EAChD,MAAM;EADW,KAAA,SAAA;;EAEjB,8BAAA,uBAAA,UAAA,sBAAgB,IAAI,IAAmB,CAAA;CACzC;;;;;;;;;;;;;;;;;;;;;;CAuBA,MAME,QACA,SAIA,OAC+C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MAAM,mBAAmB;GAAE,OAAO;GAAM,GAAG;EAAQ;EAEnD,OAAO,KAAK,OAAO,CAAC,CAAC,MAAM,UACzBC,cAAAA,WAAW,kBAAkB,KAAK,CACpC;CACF;;;;;;;;;;;;;;;;;CAkBA,QAAQ,UAA6B,CAAC,GAAiB;EACrD,MAAM,UAAU,KAAK,OAAO;EAC5B,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,IACjC,QAAQ,QAAQ,UAAUA,cAAAA,WAAW,SAAS,KAAK,CAAC,IACpD;CACN;;;;;;CAOA,OAAO,OAAoC;EACzC,sBAAA,cAAc,YAAY;GACxB,KAAK,UAAU,SAAS,aAAa;IACnC,SAAS,KAAK;GAChB,CAAC;EACH,CAAC;CACH;;;;;CAMA,UAAgB;EACd,sBAAA,cAAc,YAAY;GACxB,KAAK,OAAO,CAAC,CAAC,SAAS,UAAU;IAC/B,MAAM,QAAQ;GAChB,CAAC;EACH,CAAC;CACH;;;;;CAMA,WAAiB;EACf,sBAAA,cAAc,YAAY;GACxB,KAAK,OAAO,CAAC,CAAC,SAAS,UAAU;IAC/B,MAAM,SAAS;GACjB,CAAC;EACH,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"queryCache.cjs","names":["Subscribable","hashQueryKeyByOptions","Query","matchQuery"],"sources":["../../src/queryCache.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { Query } from './query'\nimport { Subscribable } from './subscribable'\nimport { hashQueryKeyByOptions, matchQuery } from './utils'\nimport type { Action, QueryState } from './query'\nimport type { QueryClient } from './queryClient'\nimport type { QueryObserver } from './queryObserver'\nimport type {\n DefaultError,\n NotifyEvent,\n QueryKey,\n QueryOptions,\n WithRequired,\n} from './types'\nimport type { QueryFilters } from './utils'\n\n// TYPES\n\n/**\n * Global callbacks that fire for every query handled by a `QueryCache`, regardless of which\n * component or observer triggered it. Unlike `QueryClient`'s `defaultOptions`, which a query can\n * override, these callbacks are always called. Unlike `MutationCacheConfig`'s callbacks, these\n * are fire-and-forget: their return value is not awaited before the query settles.\n */\nexport interface QueryCacheConfig {\n /** Called when any query in the cache encounters an error. */\n onError?: (\n error: DefaultError,\n query: Query<unknown, unknown, unknown>,\n ) => void\n /** Called when any query in the cache is successful. */\n onSuccess?: (data: unknown, query: Query<unknown, unknown, unknown>) => void\n /** Called when any query in the cache is settled, either successfully or with an error. */\n onSettled?: (\n data: unknown | undefined,\n error: DefaultError | null,\n query: Query<unknown, unknown, unknown>,\n ) => void\n}\n\ninterface NotifyEventQueryAdded extends NotifyEvent {\n type: 'added'\n query: Query<any, any, any, any>\n}\n\ninterface NotifyEventQueryRemoved extends NotifyEvent {\n type: 'removed'\n query: Query<any, any, any, any>\n}\n\ninterface NotifyEventQueryUpdated extends NotifyEvent {\n type: 'updated'\n query: Query<any, any, any, any>\n action: Action<any, any>\n}\n\ninterface NotifyEventQueryObserverAdded extends NotifyEvent {\n type: 'observerAdded'\n query: Query<any, any, any, any>\n observer: QueryObserver<any, any, any, any, any>\n}\n\ninterface NotifyEventQueryObserverRemoved extends NotifyEvent {\n type: 'observerRemoved'\n query: Query<any, any, any, any>\n observer: QueryObserver<any, any, any, any, any>\n}\n\ninterface NotifyEventQueryObserverResultsUpdated extends NotifyEvent {\n type: 'observerResultsUpdated'\n query: Query<any, any, any, any>\n}\n\ninterface NotifyEventQueryObserverOptionsUpdated extends NotifyEvent {\n type: 'observerOptionsUpdated'\n query: Query<any, any, any, any>\n observer: QueryObserver<any, any, any, any, any>\n}\n\n/**\n * The event passed to a `QueryCache` subscriber. Fired whenever a query is added or removed from\n * the cache, its state is updated (e.g. via `query.setState` or `queryClient.removeQueries`), or\n * one of its observers is added, removed, or has its results or options updated.\n */\nexport type QueryCacheNotifyEvent =\n | NotifyEventQueryAdded\n | NotifyEventQueryRemoved\n | NotifyEventQueryUpdated\n | NotifyEventQueryObserverAdded\n | NotifyEventQueryObserverRemoved\n | NotifyEventQueryObserverResultsUpdated\n | NotifyEventQueryObserverOptionsUpdated\n\ntype QueryCacheListener = (event: QueryCacheNotifyEvent) => void\n\n/**\n * The store a `QueryCache` keeps its queries in, keyed by query hash.\n */\nexport interface QueryStore {\n /**\n * Returns whether a query with the given hash is stored.\n */\n has: (queryHash: string) => boolean\n /**\n * Stores a query under its hash.\n */\n set: (queryHash: string, query: Query) => void\n /**\n * Returns the query with the given hash, if any.\n */\n get: (queryHash: string) => Query | undefined\n /**\n * Removes the query with the given hash.\n */\n delete: (queryHash: string) => void\n /**\n * Returns an iterator over all stored queries.\n */\n values: () => IterableIterator<Query>\n}\n\n// CLASS\n\n/**\n * The `QueryCache` is the storage mechanism for TanStack Query. It stores all the data, meta\n * information, and state of the queries it contains.\n *\n * Normally, you will not interact with the `QueryCache` directly and instead use a `QueryClient`\n * for a specific cache. You can subscribe to it (inherited from `Subscribable`) to be informed of\n * safe/known updates to the cache, such as queries being added, removed, or updated — updates made\n * outside of the cache's own tracked mechanisms (e.g. mutating a query's state object directly) do\n * not notify subscribers.\n * @example\n * ```ts\n * const unsubscribe = queryCache.subscribe((event) => {\n * console.log(event.type, event.query)\n * })\n * ```\n */\nexport class QueryCache extends Subscribable<QueryCacheListener> {\n #queries: QueryStore\n\n constructor(public config: QueryCacheConfig = {}) {\n super()\n this.#queries = new Map<string, Query>()\n }\n\n /**\n * Returns the existing `Query` instance for the given options' `queryKey`/`queryHash`, or\n * builds and adds a new one to the cache if none exists yet. Used by framework adapters and\n * plugins (e.g. broadcast/persistence) that need to get-or-create a `Query` directly, bypassing\n * the reactive `QueryObserver` machinery.\n * @param client - The client the query belongs to, used to default its options.\n * @param options - The query options, including the `queryKey`. A new query is created with the\n * options defaulted by {@link QueryClient#defaultQueryOptions}.\n * @param state - The initial state of a newly created query, e.g. when hydrating. Ignored if the\n * query already exists.\n * @returns The existing or newly created query.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const query = queryCache.build(queryClient, {\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * })\n * ```\n */\n build<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n client: QueryClient,\n options: WithRequired<\n QueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'queryKey'\n >,\n state?: QueryState<TData, TError>,\n ): Query<TQueryFnData, TError, TData, TQueryKey> {\n const queryKey = options.queryKey\n const queryHash =\n options.queryHash ?? hashQueryKeyByOptions(queryKey, options)\n let query = this.get<TQueryFnData, TError, TData, TQueryKey>(queryHash)\n\n if (!query) {\n query = new Query({\n client,\n queryKey,\n queryHash,\n options: client.defaultQueryOptions(options),\n state,\n defaultOptions: client.getQueryDefaults(queryKey),\n })\n this.add(query)\n }\n\n return query\n }\n\n /**\n * Adds a query to the cache.\n * @internal\n * @param query - The query to add. If a query with the same hash is already cached, nothing\n * happens.\n */\n add(query: Query<any, any, any, any>): void {\n if (!this.#queries.has(query.queryHash)) {\n this.#queries.set(query.queryHash, query)\n\n this.notify({\n type: 'added',\n query,\n })\n }\n }\n\n /**\n * Destroys the given `Query` and removes it from the cache, notifying subscribers with a\n * `'removed'` event. A no-op if the query is no longer the one currently stored under its hash\n * (e.g. it was already replaced). Used by plugins (e.g. the broadcast client) that mirror\n * removals across `QueryCache` instances.\n * @param query - The query to remove.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n * const query = queryCache.find({ queryKey: ['posts'] })\n *\n * if (query) {\n * queryCache.remove(query)\n * }\n * ```\n */\n remove(query: Query<any, any, any, any>): void {\n const queryInMap = this.#queries.get(query.queryHash)\n\n if (queryInMap === query) {\n query.destroy()\n this.#queries.delete(query.queryHash)\n this.notify({ type: 'removed', query })\n }\n }\n\n /**\n * Removes all queries from the cache.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * queryCache.clear()\n * ```\n */\n clear(): void {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n this.remove(query)\n })\n })\n }\n\n /**\n * Returns the `Query` instance stored under the given `queryHash`, or `undefined` if none\n * exists. Unlike {@link QueryCache#find}, this looks up by the already-computed hash rather\n * than by `QueryFilters`. Used by plugins (e.g. broadcast/hydration) that already have a hash\n * to look up directly.\n * @param queryHash - The hash of the query to look up.\n * @returns The query stored under the hash, or `undefined`.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n * const queryHash = hashKey(['posts'])\n *\n * const query = queryCache.get(queryHash)\n * ```\n */\n get<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n >(\n queryHash: string,\n ): Query<TQueryFnData, TError, TData, TQueryKey> | undefined {\n return this.#queries.get(queryHash) as\n | Query<TQueryFnData, TError, TData, TQueryKey>\n | undefined\n }\n\n /**\n * Returns all queries within the cache.\n * @returns Every query in the cache.\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const queries = queryCache.getAll()\n * ```\n */\n getAll(): Array<Query> {\n return [...this.#queries.values()]\n }\n\n /**\n * A slightly more advanced method that can be used to get an existing query instance from the\n * cache. This instance not only contains all the state for the query, but all of the instances,\n * and underlying guts of the query as well. If the query does not exist, `undefined` is\n * returned.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about a query in rare scenarios (e.g. looking at `query.state.dataUpdatedAt` to\n * decide whether a query is fresh enough to be used as an initial value).\n * @param filters - The filters to match, including the required `queryKey`. `exact` defaults to\n * `true`.\n * @returns The first matching query, or `undefined`.\n * @see {@link QueryCache#findAll}\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const query = queryCache.find({ queryKey: ['posts'] })\n * ```\n */\n find<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData>(\n filters: WithRequired<QueryFilters, 'queryKey'>,\n ): Query<TQueryFnData, TError, TData> | undefined {\n const defaultedFilters = { exact: true, ...filters }\n\n return this.getAll().find((query) =>\n matchQuery(defaultedFilters, query),\n ) as Query<TQueryFnData, TError, TData> | undefined\n }\n\n /**\n * An even more advanced method that can be used to get existing query instances from the cache\n * that partially match a query key. If no queries match, an empty array is returned.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about queries in rare scenarios.\n * @param filters - The filters to match. Without filters, every query is returned.\n * @returns The matching queries.\n * @see {@link QueryCache#find}\n * @example\n * ```ts\n * const queryCache = queryClient.getQueryCache()\n *\n * const queries = queryCache.findAll({ queryKey: ['posts'] })\n * ```\n */\n findAll(filters: QueryFilters<any> = {}): Array<Query> {\n const queries = this.getAll()\n return Object.keys(filters).length > 0\n ? queries.filter((query) => matchQuery(filters, query))\n : queries\n }\n\n /**\n * Notifies every cache listener of an event, in one batch.\n * @internal\n * @param event - The event passed to every listener.\n */\n notify(event: QueryCacheNotifyEvent): void {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(event)\n })\n })\n }\n\n /**\n * Calls {@link Query#onFocus} on every cached query, in one batch.\n * @internal\n */\n onFocus(): void {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n query.onFocus()\n })\n })\n }\n\n /**\n * Calls {@link Query#onOnline} on every cached query, in one batch.\n * @internal\n */\n onOnline(): void {\n notifyManager.batch(() => {\n this.getAll().forEach((query) => {\n query.onOnline()\n })\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA2IA,IAAa,aAAb,cAAgCA,qBAAAA,aAAiC;CAG/D,YAAY,SAAkC,CAAC,GAAG;EAChD,MAAM;EADW,KAAA,SAAA;;EAEjB,8BAAA,uBAAA,UAAA,sBAAgB,IAAI,IAAmB,CAAA;CACzC;;;;;;;;;;;;;;;;;;;;;;CAuBA,MAME,QACA,SAIA,OAC+C;EAC/C,MAAM,WAAW,QAAQ;EACzB,MAAM,YACJ,QAAQ,aAAaC,cAAAA,sBAAsB,UAAU,OAAO;EAC9D,IAAI,QAAQ,KAAK,IAA4C,SAAS;EAEtE,IAAI,CAAC,OAAO;GACV,QAAQ,IAAIC,cAAAA,MAAM;IAChB;IACA;IACA;IACA,SAAS,OAAO,oBAAoB,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OAAO,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,IACjC,QAAQ,QAAQ,UAAUA,cAAAA,WAAW,SAAS,KAAK,CAAC,IACpD;CACN;;;;;;CAOA,OAAO,OAAoC;EACzC,sBAAA,cAAc,YAAY;GACxB,KAAK,UAAU,SAAS,aAAa;IACnC,SAAS,KAAK;GAChB,CAAC;EACH,CAAC;CACH;;;;;CAMA,UAAgB;EACd,sBAAA,cAAc,YAAY;GACxB,KAAK,OAAO,CAAC,CAAC,SAAS,UAAU;IAC/B,MAAM,QAAQ;GAChB,CAAC;EACH,CAAC;CACH;;;;;CAMA,WAAiB;EACf,sBAAA,cAAc,YAAY;GACxB,KAAK,OAAO,CAAC,CAAC,SAAS,UAAU;IAC/B,MAAM,SAAS;GACjB,CAAC;EACH,CAAC;CACH;AACF"}
@@ -1,2 +1,2 @@
1
- import { cn as QueryCacheConfig, ln as QueryCacheNotifyEvent, sn as QueryCache, un as QueryStore } from "./hydration-BIRJt69T.cjs";
1
+ import { b as QueryCacheNotifyEvent, v as QueryCache, x as QueryStore, y as QueryCacheConfig } from "./hydration-24GwbSaU.cjs";
2
2
  export { QueryCache, QueryCacheConfig, QueryCacheNotifyEvent, QueryStore };
@@ -1,2 +1,2 @@
1
- import { cn as QueryCacheConfig, ln as QueryCacheNotifyEvent, sn as QueryCache, un as QueryStore } from "./hydration-9_kOYxJM.js";
1
+ import { b as QueryCacheNotifyEvent, v as QueryCache, x as QueryStore, y as QueryCacheConfig } from "./hydration-Cbq_heQS.js";
2
2
  export { QueryCache, QueryCacheConfig, QueryCacheNotifyEvent, QueryStore };