@tanstack/query-core 5.107.1 → 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":"mutationObserver.js","names":[],"sources":["../../src/mutationObserver.ts"],"sourcesContent":["import { getDefaultState } from './mutation'\nimport { notifyManager } from './notifyManager'\nimport { Subscribable } from './subscribable'\nimport { hashKey, shallowEqualObjects } from './utils'\nimport type { QueryClient } from './queryClient'\nimport type {\n DefaultError,\n MutateOptions,\n MutationFunctionContext,\n MutationObserverOptions,\n MutationObserverResult,\n} from './types'\nimport type { Action, Mutation } from './mutation'\n\n// TYPES\n\ntype MutationObserverListener<TData, TError, TVariables, TOnMutateResult> = (\n result: MutationObserverResult<TData, TError, TVariables, TOnMutateResult>,\n) => void\n\n// CLASS\n\n/**\n * Observes a single mutation and derives a `MutationObserverResult` from it.\n * A framework hook like `useMutation` creates one `MutationObserver` per hook\n * call, keeps it stable across re-renders, calls `setOptions` when the options\n * passed to the hook change, subscribes to it to re-render on updates, and\n * reads `getCurrentResult()` for the value to return. Calling `mutate()`\n * builds a new underlying `Mutation` in the `MutationCache` and executes it.\n * @example\n * ```ts\n * const observer = new MutationObserver(queryClient, {\n * mutationFn: (variables: { title: string }) => addPost(variables),\n * })\n * ```\n */\nexport class MutationObserver<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n> extends Subscribable<\n MutationObserverListener<TData, TError, TVariables, TOnMutateResult>\n> {\n options!: MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>\n\n #client: QueryClient\n #currentResult: MutationObserverResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > = undefined!\n #currentMutation?: Mutation<TData, TError, TVariables, TOnMutateResult>\n #mutateOptions?: MutateOptions<TData, TError, TVariables, TOnMutateResult>\n\n constructor(\n client: QueryClient,\n options: MutationObserverOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n ) {\n super()\n\n this.#client = client\n this.setOptions(options)\n this.bindMethods()\n this.#updateResult()\n }\n\n /**\n * Binds the methods of the result (`mutate` and `reset`) to the observer, so they keep working when\n * destructured from it.\n */\n protected bindMethods(): void {\n this.mutate = this.mutate.bind(this)\n this.reset = this.reset.bind(this)\n }\n\n /**\n * Updates the observer's options.\n *\n * If the new `mutationKey` differs from the previous one (and both were\n * defined), the observer is reset, detaching it from the mutation it was\n * observing. Otherwise, if the currently observed mutation is still\n * `pending`, its options are updated in place as well.\n * @param options - The new mutation observer options. They are defaulted with {@link\n * QueryClient#defaultMutationOptions} before being applied.\n * @example\n * ```ts\n * observer.setOptions({\n * mutationFn: (variables: { title: string }) => addPost(variables),\n * onSuccess: (data) => console.log(data),\n * })\n * ```\n */\n setOptions(\n options: MutationObserverOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n ) {\n const prevOptions = this.options as\n | MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>\n | undefined\n this.options = this.#client.defaultMutationOptions(options)\n if (!shallowEqualObjects(this.options, prevOptions)) {\n this.#client.getMutationCache().notify({\n type: 'observerOptionsUpdated',\n mutation: this.#currentMutation,\n observer: this,\n })\n }\n\n if (\n prevOptions?.mutationKey &&\n this.options.mutationKey &&\n hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)\n ) {\n this.reset()\n } else if (this.#currentMutation?.state.status === 'pending') {\n this.#currentMutation.setOptions(this.options)\n }\n }\n\n protected override onSubscribe(): void {\n if (this.listeners.size === 1 && this.#currentMutation) {\n this.#currentMutation.addObserver(this)\n\n this.#updateResult()\n }\n }\n\n protected override onUnsubscribe(): void {\n if (!this.hasListeners()) {\n this.#currentMutation?.removeObserver(this)\n }\n }\n\n /**\n * Updates the observer's result when the observed mutation changes, and notifies its listeners.\n * @internal\n * @param action - The action that updated the observed mutation, passed on to the observer's\n * callbacks.\n */\n onMutationUpdate(\n action: Action<TData, TError, TVariables, TOnMutateResult>,\n ): void {\n this.#updateResult()\n\n this.#notify(action)\n }\n\n /**\n * Returns the observer's current result, derived from the observed\n * mutation's state (or the default, `idle` state if no mutation has been\n * built yet, e.g. before the first `mutate()` call or after `reset()`).\n * @returns The observer's latest result.\n */\n getCurrentResult(): MutationObserverResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > {\n return this.#currentResult\n }\n\n /**\n * Detaches the observer from the mutation it is currently observing (if\n * any) and resets the observed result back to its default, `idle` state.\n *\n * This does not cancel an in-flight mutation; the mutation itself keeps\n * running to completion and its own callbacks still fire, but this\n * observer stops reflecting its state and a subsequent `mutate()` call\n * will build a brand new mutation.\n * @see {@link MutationObserver#mutate}\n * @example\n * ```ts\n * observer.reset()\n * ```\n */\n reset(): void {\n // reset needs to remove the observer from the mutation because there is no way to \"get it back\"\n // another mutate call will yield a new mutation!\n this.#currentMutation?.removeObserver(this)\n this.#currentMutation = undefined\n this.#updateResult()\n this.#notify()\n }\n\n /**\n * Builds a new `Mutation` in the `MutationCache` using the observer's\n * current options, detaches this observer from any previously observed\n * mutation, attaches it to the new one, and executes it with the given\n * variables.\n *\n * The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are\n * invoked once the mutation settles, in addition to any callbacks defined\n * on the observer's own options.\n * @param variables - The variables passed to the `mutationFn`.\n * @param options - Per-call `onSuccess`, `onError`, and `onSettled` callbacks.\n * @returns A promise that resolves with the mutation's data, or rejects with its error.\n * @example\n * ```ts\n * await observer.mutate(\n * { title: 'New post' },\n * { onSuccess: (data) => console.log(data) },\n * )\n * ```\n */\n mutate(\n variables: TVariables,\n options?: MutateOptions<TData, TError, TVariables, TOnMutateResult>,\n ): Promise<TData> {\n this.#mutateOptions = options\n\n this.#currentMutation?.removeObserver(this)\n\n this.#currentMutation = this.#client\n .getMutationCache()\n .build(this.#client, this.options)\n\n this.#currentMutation.addObserver(this)\n\n return this.#currentMutation.execute(variables)\n }\n\n #updateResult(): void {\n const state =\n this.#currentMutation?.state ??\n getDefaultState<TData, TError, TVariables, TOnMutateResult>()\n\n this.#currentResult = {\n ...state,\n isPending: state.status === 'pending',\n isSuccess: state.status === 'success',\n isError: state.status === 'error',\n isIdle: state.status === 'idle',\n mutate: this.mutate,\n reset: this.reset,\n } as MutationObserverResult<TData, TError, TVariables, TOnMutateResult>\n }\n\n #notify(action?: Action<TData, TError, TVariables, TOnMutateResult>): void {\n notifyManager.batch(() => {\n // First trigger the mutate callbacks\n // Snapshot mutateOptions before dispatching — a callback (e.g. onSuccess)\n // may call mutate() again, which overwrites this.#mutateOptions in place.\n // Without the snapshot, onSettled would fire with the *next* mutation's\n // options but the *current* mutation's data/variables.\n const mutateOptions = this.#mutateOptions\n if (mutateOptions && this.hasListeners()) {\n const variables = this.#currentResult.variables!\n const onMutateResult = this.#currentResult.context\n\n const context = {\n client: this.#client,\n meta: this.options.meta,\n mutationKey: this.options.mutationKey,\n } satisfies MutationFunctionContext\n\n if (action?.type === 'success') {\n try {\n mutateOptions.onSuccess?.(\n action.data,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n try {\n mutateOptions.onSettled?.(\n action.data,\n null,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n } else if (action?.type === 'error') {\n try {\n mutateOptions.onError?.(\n action.error,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n try {\n mutateOptions.onSettled?.(\n undefined,\n action.error,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n }\n }\n\n // Then trigger the listeners\n this.listeners.forEach((listener) => {\n listener(this.#currentResult)\n })\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoCA,IAAa,mBAAb,cAKU,aAER;CAGA;CACA,iBAKI,KAAA;CACJ;CACA;CAEA,YACE,QACA,SAMA;EACA,MAAM;EAEN,KAAK,UAAU;EACf,KAAK,WAAW,OAAO;EACvB,KAAK,YAAY;EACjB,KAAK,cAAc;CACrB;;;;;CAMA,cAA8B;EAC5B,KAAK,SAAS,KAAK,OAAO,KAAK,IAAI;EACnC,KAAK,QAAQ,KAAK,MAAM,KAAK,IAAI;CACnC;;;;;;;;;;;;;;;;;;CAmBA,WACE,SAMA;EACA,MAAM,cAAc,KAAK;EAGzB,KAAK,UAAU,KAAK,QAAQ,uBAAuB,OAAO;EAC1D,IAAI,CAAC,oBAAoB,KAAK,SAAS,WAAW,GAChD,KAAK,QAAQ,iBAAiB,CAAC,CAAC,OAAO;GACrC,MAAM;GACN,UAAU,KAAK;GACf,UAAU;EACZ,CAAC;EAGH,IACE,aAAa,eACb,KAAK,QAAQ,eACb,QAAQ,YAAY,WAAW,MAAM,QAAQ,KAAK,QAAQ,WAAW,GAErE,KAAK,MAAM;OACN,IAAI,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QAAQ,KAAK;KACb,MAAM,KAAK,QAAQ;KACnB,aAAa,KAAK,QAAQ;IAC5B;IAEA,IAAI,QAAQ,SAAS,WAAW;KAC9B,IAAI;MACF,cAAc,YACZ,OAAO,MACP,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;KACA,IAAI;MACF,cAAc,YACZ,OAAO,MACP,MACA,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;IACF,OAAO,IAAI,QAAQ,SAAS,SAAS;KACnC,IAAI;MACF,cAAc,UACZ,OAAO,OACP,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;KACA,IAAI;MACF,cAAc,YACZ,KAAA,GACA,OAAO,OACP,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;IACF;GACF;GAGA,KAAK,UAAU,SAAS,aAAa;IACnC,SAAS,KAAK,cAAc;GAC9B,CAAC;EACH,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"mutationObserver.js","names":[],"sources":["../../src/mutationObserver.ts"],"sourcesContent":["import { getDefaultState } from './mutation'\nimport { notifyManager } from './notifyManager'\nimport { Subscribable } from './subscribable'\nimport { hashKey, shallowEqualObjects } from './utils'\nimport type { Action, Mutation } from './mutation'\nimport type { QueryClient } from './queryClient'\nimport type {\n DefaultError,\n MutateOptions,\n MutationFunctionContext,\n MutationObserverOptions,\n MutationObserverResult,\n} from './types'\n\n// TYPES\n\ntype MutationObserverListener<TData, TError, TVariables, TOnMutateResult> = (\n result: MutationObserverResult<TData, TError, TVariables, TOnMutateResult>,\n) => void\n\n// CLASS\n\n/**\n * Observes a single mutation and derives a `MutationObserverResult` from it.\n * A framework hook like `useMutation` creates one `MutationObserver` per hook\n * call, keeps it stable across re-renders, calls `setOptions` when the options\n * passed to the hook change, subscribes to it to re-render on updates, and\n * reads `getCurrentResult()` for the value to return. Calling `mutate()`\n * builds a new underlying `Mutation` in the `MutationCache` and executes it.\n * @example\n * ```ts\n * const observer = new MutationObserver(queryClient, {\n * mutationFn: (variables: { title: string }) => addPost(variables),\n * })\n * ```\n */\nexport class MutationObserver<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n> extends Subscribable<\n MutationObserverListener<TData, TError, TVariables, TOnMutateResult>\n> {\n options!: MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>\n\n #client: QueryClient\n #currentResult: MutationObserverResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > = undefined!\n #currentMutation?: Mutation<TData, TError, TVariables, TOnMutateResult>\n #mutateOptions?: MutateOptions<TData, TError, TVariables, TOnMutateResult>\n\n constructor(\n client: QueryClient,\n options: MutationObserverOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n ) {\n super()\n\n this.#client = client\n this.setOptions(options)\n this.bindMethods()\n this.#updateResult()\n }\n\n /**\n * Binds the methods of the result (`mutate` and `reset`) to the observer, so they keep working when\n * destructured from it.\n */\n protected bindMethods(): void {\n this.mutate = this.mutate.bind(this)\n this.reset = this.reset.bind(this)\n }\n\n /**\n * Updates the observer's options.\n *\n * If the new `mutationKey` differs from the previous one (and both were\n * defined), the observer is reset, detaching it from the mutation it was\n * observing. Otherwise, if the currently observed mutation is still\n * `pending`, its options are updated in place as well.\n * @param options - The new mutation observer options. They are defaulted with {@link\n * QueryClient#defaultMutationOptions} before being applied.\n * @example\n * ```ts\n * observer.setOptions({\n * mutationFn: (variables: { title: string }) => addPost(variables),\n * onSuccess: (data) => console.log(data),\n * })\n * ```\n */\n setOptions(\n options: MutationObserverOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n ) {\n const prevOptions = this.options as\n | MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>\n | undefined\n this.options = this.#client.defaultMutationOptions(options)\n if (!shallowEqualObjects(this.options, prevOptions)) {\n this.#client.getMutationCache().notify({\n type: 'observerOptionsUpdated',\n mutation: this.#currentMutation,\n observer: this,\n })\n }\n\n if (\n prevOptions?.mutationKey &&\n this.options.mutationKey &&\n hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)\n ) {\n this.reset()\n } else if (this.#currentMutation?.state.status === 'pending') {\n this.#currentMutation.setOptions(this.options)\n }\n }\n\n protected override onSubscribe(): void {\n if (this.listeners.size === 1 && this.#currentMutation) {\n this.#currentMutation.addObserver(this)\n\n this.#updateResult()\n }\n }\n\n protected override onUnsubscribe(): void {\n if (!this.hasListeners()) {\n this.#currentMutation?.removeObserver(this)\n }\n }\n\n /**\n * Updates the observer's result when the observed mutation changes, and notifies its listeners.\n * @internal\n * @param action - The action that updated the observed mutation, passed on to the observer's\n * callbacks.\n */\n onMutationUpdate(\n action: Action<TData, TError, TVariables, TOnMutateResult>,\n ): void {\n this.#updateResult()\n\n this.#notify(action)\n }\n\n /**\n * Returns the observer's current result, derived from the observed\n * mutation's state (or the default, `idle` state if no mutation has been\n * built yet, e.g. before the first `mutate()` call or after `reset()`).\n * @returns The observer's latest result.\n */\n getCurrentResult(): MutationObserverResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > {\n return this.#currentResult\n }\n\n /**\n * Detaches the observer from the mutation it is currently observing (if\n * any) and resets the observed result back to its default, `idle` state.\n *\n * This does not cancel an in-flight mutation; the mutation itself keeps\n * running to completion and its own callbacks still fire, but this\n * observer stops reflecting its state and a subsequent `mutate()` call\n * will build a brand new mutation.\n * @see {@link MutationObserver#mutate}\n * @example\n * ```ts\n * observer.reset()\n * ```\n */\n reset(): void {\n // reset needs to remove the observer from the mutation because there is no way to \"get it back\"\n // another mutate call will yield a new mutation!\n this.#currentMutation?.removeObserver(this)\n this.#currentMutation = undefined\n this.#updateResult()\n this.#notify()\n }\n\n /**\n * Builds a new `Mutation` in the `MutationCache` using the observer's\n * current options, detaches this observer from any previously observed\n * mutation, attaches it to the new one, and executes it with the given\n * variables.\n *\n * The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are\n * invoked once the mutation settles, in addition to any callbacks defined\n * on the observer's own options.\n * @param variables - The variables passed to the `mutationFn`.\n * @param options - Per-call `onSuccess`, `onError`, and `onSettled` callbacks.\n * @returns A promise that resolves with the mutation's data, or rejects with its error.\n * @example\n * ```ts\n * await observer.mutate(\n * { title: 'New post' },\n * { onSuccess: (data) => console.log(data) },\n * )\n * ```\n */\n mutate(\n variables: TVariables,\n options?: MutateOptions<TData, TError, TVariables, TOnMutateResult>,\n ): Promise<TData> {\n this.#mutateOptions = options\n\n this.#currentMutation?.removeObserver(this)\n\n this.#currentMutation = this.#client\n .getMutationCache()\n .build(this.#client, this.options)\n\n this.#currentMutation.addObserver(this)\n\n return this.#currentMutation.execute(variables)\n }\n\n #updateResult(): void {\n const state =\n this.#currentMutation?.state ??\n getDefaultState<TData, TError, TVariables, TOnMutateResult>()\n\n this.#currentResult = {\n ...state,\n isPending: state.status === 'pending',\n isSuccess: state.status === 'success',\n isError: state.status === 'error',\n isIdle: state.status === 'idle',\n mutate: this.mutate,\n reset: this.reset,\n } as MutationObserverResult<TData, TError, TVariables, TOnMutateResult>\n }\n\n #notify(action?: Action<TData, TError, TVariables, TOnMutateResult>): void {\n notifyManager.batch(() => {\n // First trigger the mutate callbacks\n // Snapshot mutateOptions before dispatching — a callback (e.g. onSuccess)\n // may call mutate() again, which overwrites this.#mutateOptions in place.\n // Without the snapshot, onSettled would fire with the *next* mutation's\n // options but the *current* mutation's data/variables.\n const mutateOptions = this.#mutateOptions\n if (mutateOptions && this.hasListeners()) {\n const variables = this.#currentResult.variables!\n const onMutateResult = this.#currentResult.context\n\n const context = {\n client: this.#client,\n meta: this.options.meta,\n mutationKey: this.options.mutationKey,\n } satisfies MutationFunctionContext\n\n if (action?.type === 'success') {\n try {\n mutateOptions.onSuccess?.(\n action.data,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n try {\n mutateOptions.onSettled?.(\n action.data,\n null,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n } else if (action?.type === 'error') {\n try {\n mutateOptions.onError?.(\n action.error,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n try {\n mutateOptions.onSettled?.(\n undefined,\n action.error,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n }\n }\n\n // Then trigger the listeners\n this.listeners.forEach((listener) => {\n listener(this.#currentResult)\n })\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoCA,IAAa,mBAAb,cAKU,aAER;CAGA;CACA,iBAKI,KAAA;CACJ;CACA;CAEA,YACE,QACA,SAMA;EACA,MAAM;EAEN,KAAK,UAAU;EACf,KAAK,WAAW,OAAO;EACvB,KAAK,YAAY;EACjB,KAAK,cAAc;CACrB;;;;;CAMA,cAA8B;EAC5B,KAAK,SAAS,KAAK,OAAO,KAAK,IAAI;EACnC,KAAK,QAAQ,KAAK,MAAM,KAAK,IAAI;CACnC;;;;;;;;;;;;;;;;;;CAmBA,WACE,SAMA;EACA,MAAM,cAAc,KAAK;EAGzB,KAAK,UAAU,KAAK,QAAQ,uBAAuB,OAAO;EAC1D,IAAI,CAAC,oBAAoB,KAAK,SAAS,WAAW,GAChD,KAAK,QAAQ,iBAAiB,CAAC,CAAC,OAAO;GACrC,MAAM;GACN,UAAU,KAAK;GACf,UAAU;EACZ,CAAC;EAGH,IACE,aAAa,eACb,KAAK,QAAQ,eACb,QAAQ,YAAY,WAAW,MAAM,QAAQ,KAAK,QAAQ,WAAW,GAErE,KAAK,MAAM;OACN,IAAI,KAAK,kBAAkB,MAAM,WAAW,WACjD,KAAK,iBAAiB,WAAW,KAAK,OAAO;CAEjD;CAEA,cAAuC;EACrC,IAAI,KAAK,UAAU,SAAS,KAAK,KAAK,kBAAkB;GACtD,KAAK,iBAAiB,YAAY,IAAI;GAEtC,KAAK,cAAc;EACrB;CACF;CAEA,gBAAyC;EACvC,IAA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c,YACZ,OAAO,MACP,MACA,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;IACF,OAAO,IAAI,QAAQ,SAAS,SAAS;KACnC,IAAI;MACF,cAAc,UACZ,OAAO,OACP,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;KACA,IAAI;MACF,cAAc,YACZ,KAAA,GACA,OAAO,OACP,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;IACF;GACF;GAGA,KAAK,UAAU,SAAS,aAAa;IACnC,SAAS,KAAK,cAAc;GAC9B,CAAC;EACH,CAAC;CACH;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"queriesObserver.cjs","names":["Subscribable","shallowEqualObjects","replaceEqualDeep","QueryObserver"],"sources":["../../src/queriesObserver.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { QueryObserver } from './queryObserver'\nimport { Subscribable } from './subscribable'\nimport { replaceEqualDeep, shallowEqualObjects } from './utils'\nimport type {\n DefaultedQueryObserverOptions,\n QueryObserverOptions,\n QueryObserverResult,\n} from './types'\nimport type { QueryClient } from './queryClient'\n\n/**\n * Returns the items of `array1` that are not in `array2`.\n * @param array1 - The items to filter.\n * @param array2 - The items to exclude.\n * @returns A new array with the items of `array1` that are not in `array2`.\n */\nfunction difference<T>(array1: Array<T>, array2: Array<T>): Array<T> {\n const excludeSet = new Set(array2)\n return array1.filter((x) => !excludeSet.has(x))\n}\n\ntype QueriesObserverListener = (result: Array<QueryObserverResult>) => void\n\ntype CombineFn<TCombinedResult> = (\n result: Array<QueryObserverResult>,\n) => TCombinedResult\n\n/**\n * Options for a `QueriesObserver` that apply to all of its queries at once.\n */\nexport interface QueriesObserverOptions<\n TCombinedResult = Array<QueryObserverResult>,\n> {\n /**\n * A function that combines the array of `QueryObserverResult`s (one per\n * observed query) into a single value. The combined value is memoized and\n * only recomputed when one of the underlying results, the query hashes, or\n * the `combine` function itself changes.\n *\n * Defaults to returning the array of `QueryObserverResult`s unchanged.\n */\n combine?: CombineFn<TCombinedResult>\n}\n\n/**\n * A `QueriesObserver` watches an array of queries at once, exposing them as\n * a single array of `QueryObserverResult`s (or, when a `combine` option is\n * given, as a combined value derived from that array). It manages one\n * internal `QueryObserver` per query, and is the primitive that framework\n * adapters (e.g. `useQueries`) build their hooks on top of.\n * @example\n * ```ts\n * const observer = new QueriesObserver(queryClient, [\n * { queryKey: ['post', 1], queryFn: fetchPost },\n * { queryKey: ['post', 2], queryFn: fetchPost },\n * ])\n *\n * const unsubscribe = observer.subscribe((result) => {\n * console.log(result)\n * })\n * ```\n */\nexport class QueriesObserver<\n TCombinedResult = Array<QueryObserverResult>,\n> extends Subscribable<QueriesObserverListener> {\n #client: QueryClient\n #result!: Array<QueryObserverResult>\n #queries: Array<QueryObserverOptions>\n #options?: QueriesObserverOptions<TCombinedResult>\n #observers: Array<QueryObserver>\n #combinedResult!: TCombinedResult\n #lastCombine?: CombineFn<TCombinedResult>\n #lastResult?: Array<QueryObserverResult>\n #lastQueryHashes?: Array<string>\n #observerMatches: Array<QueryObserverMatch> = []\n\n constructor(\n client: QueryClient,\n queries: Array<QueryObserverOptions<any, any, any, any, any>>,\n options?: QueriesObserverOptions<TCombinedResult>,\n ) {\n super()\n\n this.#client = client\n this.#options = options\n this.#queries = []\n this.#observers = []\n this.#result = []\n\n this.setQueries(queries)\n }\n\n protected override onSubscribe(): void {\n if (this.listeners.size === 1) {\n this.#observers.forEach((observer) => {\n observer.subscribe((result) => {\n this.#onUpdate(observer, result)\n })\n })\n }\n }\n\n protected override onUnsubscribe(): void {\n if (!this.listeners.size) {\n this.destroy()\n }\n }\n\n /**\n * Stops observing all queries: clears all listeners and destroys every\n * underlying `QueryObserver` this observer manages.\n */\n destroy(): void {\n this.listeners = new Set()\n this.#observers.forEach((observer) => {\n observer.destroy()\n })\n }\n\n /**\n * Replaces the set of queries being observed. Existing `QueryObserver`s\n * are reused for queries that match an already-observed query hash;\n * observers for queries that are no longer present are destroyed, and new\n * observers are created and subscribed to for newly added queries.\n * @param queries - The options of the queries to observe.\n * @param options - Replaces the observer's options, e.g. its `combine` function.\n * @example\n * ```ts\n * observer.setQueries([\n * { queryKey: ['post', 1], queryFn: fetchPost },\n * { queryKey: ['post', 3], queryFn: fetchPost },\n * ])\n * ```\n */\n setQueries(\n queries: Array<QueryObserverOptions>,\n options?: QueriesObserverOptions<TCombinedResult>,\n ): void {\n this.#queries = queries\n this.#options = options\n\n if (process.env.NODE_ENV !== 'production') {\n const queryHashes = queries.map(\n (query) => this.#client.defaultQueryOptions(query).queryHash,\n )\n if (new Set(queryHashes).size !== queryHashes.length) {\n console.warn(\n '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.',\n )\n }\n }\n\n notifyManager.batch(() => {\n const prevObservers = this.#observers\n\n const newObserverMatches = this.#findMatchingObservers(this.#queries)\n\n // set options for the new observers to notify of changes\n newObserverMatches.forEach((match) =>\n match.observer.setOptions(match.defaultedQueryOptions),\n )\n\n const newObservers = newObserverMatches.map((match) => match.observer)\n const newResult = newObservers.map((observer) =>\n observer.getCurrentResult(),\n )\n\n const hasLengthChange = prevObservers.length !== newObservers.length\n const hasIndexChange = newObservers.some(\n (observer, index) => observer !== prevObservers[index],\n )\n const hasStructuralChange = hasLengthChange || hasIndexChange\n\n const hasResultChange = hasStructuralChange\n ? true\n : newResult.some((result, index) => {\n const prev = this.#result[index]\n return !prev || !shallowEqualObjects(result, prev)\n })\n\n if (!hasStructuralChange && !hasResultChange) return\n\n if (hasStructuralChange) {\n this.#observerMatches = newObserverMatches\n this.#observers = newObservers\n }\n\n this.#result = newResult\n\n if (!this.hasListeners()) return\n\n if (hasStructuralChange) {\n difference(prevObservers, newObservers).forEach((observer) => {\n observer.destroy()\n })\n difference(newObservers, prevObservers).forEach((observer) => {\n observer.subscribe((result) => {\n this.#onUpdate(observer, result)\n })\n })\n }\n\n this.#notify()\n })\n }\n\n /**\n * Returns the most recently computed array of `QueryObserverResult`s, one\n * per observed query, in the same order as the queries passed to the\n * constructor or `setQueries`.\n * @returns The current results.\n * @example\n * ```ts\n * const results = observer.getCurrentResult()\n * const data = results.map((result) => result.data)\n * ```\n */\n getCurrentResult(): Array<QueryObserverResult> {\n return this.#result\n }\n\n /**\n * Returns the underlying `Query` instances currently being observed, in\n * the same order as the queries passed to the constructor or `setQueries`.\n * @returns The observed queries.\n */\n getQueries() {\n return this.#observers.map((observer) => observer.getCurrentQuery())\n }\n\n /**\n * Returns the underlying `QueryObserver` instances this observer manages,\n * in the same order as the queries passed to the constructor or\n * `setQueries`.\n * @returns The managed query observers.\n */\n getObservers() {\n return this.#observers\n }\n\n /**\n * The `QueriesObserver` counterpart of {@link QueryObserver#getOptimisticResult} — computes\n * the result for the given (already-defaulted) queries right now, synchronously. Called by\n * framework adapters (e.g. `useQueries`) ahead of subscribing, returning a tuple of the raw\n * per-query results, a function to compute the combined result from them, and a function to\n * wrap the results for property-access tracking.\n * @param queries - The defaulted options of the queries to compute the result for.\n * @param combine - The `combine` function used by the returned `combineResult`, if any.\n * @returns A tuple of the per-query results, a function that computes the combined result, and a\n * function that returns the results wrapped for property-access tracking.\n */\n getOptimisticResult(\n queries: Array<QueryObserverOptions>,\n combine: CombineFn<TCombinedResult> | undefined,\n ): [\n rawResult: Array<QueryObserverResult>,\n combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult,\n trackResult: () => Array<QueryObserverResult>,\n ] {\n const matches = this.#findMatchingObservers(queries)\n const result = matches.map((match) =>\n match.observer.getOptimisticResult(match.defaultedQueryOptions),\n )\n const queryHashes = matches.map(\n (match) => match.defaultedQueryOptions.queryHash,\n )\n\n return [\n result,\n (r?: Array<QueryObserverResult>) => {\n return this.#combineResult(r ?? result, combine, queryHashes)\n },\n () => {\n return this.#trackResult(result, matches)\n },\n ]\n }\n\n #trackResult(\n result: Array<QueryObserverResult>,\n matches: Array<QueryObserverMatch>,\n ) {\n const trackedProps = new Set<keyof QueryObserverResult>()\n\n return matches.map((match, index) => {\n const observerResult = result[index]!\n return !match.defaultedQueryOptions.notifyOnChangeProps\n ? match.observer.trackResult(observerResult, (accessedProp) => {\n // track property on all observers to ensure proper (synchronized) tracking (#7000)\n if (!trackedProps.has(accessedProp)) {\n trackedProps.add(accessedProp)\n matches.forEach((m) => {\n m.observer.trackProp(accessedProp)\n })\n }\n })\n : observerResult\n })\n }\n\n #combineResult(\n input: Array<QueryObserverResult>,\n combine: CombineFn<TCombinedResult> | undefined,\n queryHashes?: Array<string>,\n ): TCombinedResult {\n if (combine) {\n const lastHashes = this.#lastQueryHashes\n const queryHashesChanged =\n queryHashes !== undefined &&\n lastHashes !== undefined &&\n (lastHashes.length !== queryHashes.length ||\n queryHashes.some((hash, i) => hash !== lastHashes[i]))\n\n if (\n this.#result !== this.#lastResult ||\n queryHashesChanged ||\n combine !== this.#lastCombine\n ) {\n this.#lastCombine = combine\n this.#lastResult = this.#result\n\n if (queryHashes !== undefined) {\n this.#lastQueryHashes = queryHashes\n }\n this.#combinedResult = replaceEqualDeep(\n this.#combinedResult,\n combine(input),\n )\n }\n\n return this.#combinedResult\n }\n return input as any\n }\n\n #shouldSkipCombine(): boolean {\n return (\n !this.#options?.combine ||\n this.#observers.some((observer, index) => {\n return (\n observer.options.suspense && this.#result[index]?.data === undefined\n )\n })\n )\n }\n\n #findMatchingObservers(\n queries: Array<QueryObserverOptions>,\n ): Array<QueryObserverMatch> {\n const prevObserversMap = new Map<string, Array<QueryObserver>>()\n\n this.#observers.forEach((observer) => {\n const key = observer.options.queryHash\n if (!key) return\n\n const previousObservers = prevObserversMap.get(key)\n\n if (previousObservers) {\n previousObservers.push(observer)\n } else {\n prevObserversMap.set(key, [observer])\n }\n })\n\n const observers: Array<QueryObserverMatch> = []\n\n queries.forEach((options) => {\n const defaultedOptions = this.#client.defaultQueryOptions(options)\n const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift()\n const observer =\n match ?? new QueryObserver(this.#client, defaultedOptions)\n\n observers.push({\n defaultedQueryOptions: defaultedOptions,\n observer,\n })\n })\n\n return observers\n }\n\n #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {\n const index = this.#observers.indexOf(observer)\n if (index !== -1) {\n this.#result = this.#result.slice()\n this.#result[index] = result\n this.#notify()\n }\n }\n\n #notify(): void {\n if (this.hasListeners()) {\n const shouldSkipCombine = this.#shouldSkipCombine()\n const previousResult = this.#combinedResult\n const newResult = shouldSkipCombine\n ? previousResult\n : this.#combineResult(\n this.#trackResult(this.#result, this.#observerMatches),\n this.#options?.combine,\n )\n\n if (shouldSkipCombine || previousResult !== newResult) {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(this.#result)\n })\n })\n }\n }\n }\n}\n\ntype QueryObserverMatch = {\n defaultedQueryOptions: DefaultedQueryObserverOptions\n observer: QueryObserver\n}\n"],"mappings":";;;;;;;;;;;;AAiBA,SAAS,WAAc,QAAkB,QAA4B;CACnE,MAAM,aAAa,IAAI,IAAI,MAAM;CACjC,OAAO,OAAO,QAAQ,MAAM,CAAC,WAAW,IAAI,CAAC,CAAC;AAChD;;;;;;;;;;;;;;;;;;;AA2CA,IAAa,kBAAb,cAEUA,qBAAAA,aAAsC;CAC9C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,mBAA8C,CAAC;CAE/C,YACE,QACA,SACA,SACA;EACA,MAAM;EAEN,KAAK,UAAU;EACf,KAAK,WAAW;EAChB,KAAK,WAAW,CAAC;EACjB,KAAK,aAAa,CAAC;EACnB,KAAK,UAAU,CAAC;EAEhB,KAAK,WAAW,OAAO;CACzB;CAEA,cAAuC;EACrC,IAAI,KAAK,UAAU,SAAS,GAC1B,KAAK,WAAW,SAAS,aAAa;GACpC,SAAS,WAAW,WAAW;IAC7B,KAAK,UAAU,UAAU,MAAM;GACjC,CAAC;EACH,CAAC;CAEL;CAEA,gBAAyC;EACvC,IAAI,CAAC,KAAK,UAAU,MAClB,KAAK,QAAQ;CAEjB;;;;;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AG;GACvB,MAAM,oBAAoB,KAAK,mBAAmB;GAClD,MAAM,iBAAiB,KAAK;GAC5B,MAAM,YAAY,oBACd,iBACA,KAAK,eACH,KAAK,aAAa,KAAK,SAAS,KAAK,gBAAgB,GACrD,KAAK,UAAU,OACjB;GAEJ,IAAI,qBAAqB,mBAAmB,WAC1C,sBAAA,cAAc,YAAY;IACxB,KAAK,UAAU,SAAS,aAAa;KACnC,SAAS,KAAK,OAAO;IACvB,CAAC;GACH,CAAC;EAEL;CACF;AACF"}
1
+ {"version":3,"file":"queriesObserver.cjs","names":["Subscribable","shallowEqualObjects","replaceEqualDeep","QueryObserver"],"sources":["../../src/queriesObserver.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { QueryObserver } from './queryObserver'\nimport { Subscribable } from './subscribable'\nimport { replaceEqualDeep, shallowEqualObjects } from './utils'\nimport type { QueryClient } from './queryClient'\nimport type {\n DefaultedQueryObserverOptions,\n QueryObserverOptions,\n QueryObserverResult,\n} from './types'\n\n/**\n * Returns the items of `array1` that are not in `array2`.\n * @param array1 - The items to filter.\n * @param array2 - The items to exclude.\n * @returns A new array with the items of `array1` that are not in `array2`.\n */\nfunction difference<T>(array1: Array<T>, array2: Array<T>): Array<T> {\n const excludeSet = new Set(array2)\n return array1.filter((x) => !excludeSet.has(x))\n}\n\ntype QueriesObserverListener = (result: Array<QueryObserverResult>) => void\n\ntype CombineFn<TCombinedResult> = (\n result: Array<QueryObserverResult>,\n) => TCombinedResult\n\n/**\n * Options for a `QueriesObserver` that apply to all of its queries at once.\n */\nexport interface QueriesObserverOptions<\n TCombinedResult = Array<QueryObserverResult>,\n> {\n /**\n * A function that combines the array of `QueryObserverResult`s (one per\n * observed query) into a single value. The combined value is memoized and\n * only recomputed when one of the underlying results, the query hashes, or\n * the `combine` function itself changes.\n *\n * Defaults to returning the array of `QueryObserverResult`s unchanged.\n */\n combine?: CombineFn<TCombinedResult>\n}\n\n/**\n * A `QueriesObserver` watches an array of queries at once, exposing them as\n * a single array of `QueryObserverResult`s (or, when a `combine` option is\n * given, as a combined value derived from that array). It manages one\n * internal `QueryObserver` per query, and is the primitive that framework\n * adapters (e.g. `useQueries`) build their hooks on top of.\n * @example\n * ```ts\n * const observer = new QueriesObserver(queryClient, [\n * { queryKey: ['post', 1], queryFn: fetchPost },\n * { queryKey: ['post', 2], queryFn: fetchPost },\n * ])\n *\n * const unsubscribe = observer.subscribe((result) => {\n * console.log(result)\n * })\n * ```\n */\nexport class QueriesObserver<\n TCombinedResult = Array<QueryObserverResult>,\n> extends Subscribable<QueriesObserverListener> {\n #client: QueryClient\n #result!: Array<QueryObserverResult>\n #queries: Array<QueryObserverOptions>\n #options?: QueriesObserverOptions<TCombinedResult>\n #observers: Array<QueryObserver>\n #combinedResult!: TCombinedResult\n #lastCombine?: CombineFn<TCombinedResult>\n #lastResult?: Array<QueryObserverResult>\n #lastQueryHashes?: Array<string>\n #observerMatches: Array<QueryObserverMatch> = []\n\n constructor(\n client: QueryClient,\n queries: Array<QueryObserverOptions<any, any, any, any, any>>,\n options?: QueriesObserverOptions<TCombinedResult>,\n ) {\n super()\n\n this.#client = client\n this.#options = options\n this.#queries = []\n this.#observers = []\n this.#result = []\n\n this.setQueries(queries)\n }\n\n protected override onSubscribe(): void {\n if (this.listeners.size === 1) {\n this.#observers.forEach((observer) => {\n observer.subscribe((result) => {\n this.#onUpdate(observer, result)\n })\n })\n }\n }\n\n protected override onUnsubscribe(): void {\n if (!this.listeners.size) {\n this.destroy()\n }\n }\n\n /**\n * Stops observing all queries: clears all listeners and destroys every\n * underlying `QueryObserver` this observer manages.\n */\n destroy(): void {\n this.listeners = new Set()\n this.#observers.forEach((observer) => {\n observer.destroy()\n })\n }\n\n /**\n * Replaces the set of queries being observed. Existing `QueryObserver`s\n * are reused for queries that match an already-observed query hash;\n * observers for queries that are no longer present are destroyed, and new\n * observers are created and subscribed to for newly added queries.\n * @param queries - The options of the queries to observe.\n * @param options - Replaces the observer's options, e.g. its `combine` function.\n * @example\n * ```ts\n * observer.setQueries([\n * { queryKey: ['post', 1], queryFn: fetchPost },\n * { queryKey: ['post', 3], queryFn: fetchPost },\n * ])\n * ```\n */\n setQueries(\n queries: Array<QueryObserverOptions>,\n options?: QueriesObserverOptions<TCombinedResult>,\n ): void {\n this.#queries = queries\n this.#options = options\n\n if (process.env.NODE_ENV !== 'production') {\n const queryHashes = queries.map(\n (query) => this.#client.defaultQueryOptions(query).queryHash,\n )\n if (new Set(queryHashes).size !== queryHashes.length) {\n console.warn(\n '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.',\n )\n }\n }\n\n notifyManager.batch(() => {\n const prevObservers = this.#observers\n\n const newObserverMatches = this.#findMatchingObservers(this.#queries)\n\n // set options for the new observers to notify of changes\n newObserverMatches.forEach((match) =>\n match.observer.setOptions(match.defaultedQueryOptions),\n )\n\n const newObservers = newObserverMatches.map((match) => match.observer)\n const newResult = newObservers.map((observer) =>\n observer.getCurrentResult(),\n )\n\n const hasLengthChange = prevObservers.length !== newObservers.length\n const hasIndexChange = newObservers.some(\n (observer, index) => observer !== prevObservers[index],\n )\n const hasStructuralChange = hasLengthChange || hasIndexChange\n\n const hasResultChange = hasStructuralChange\n ? true\n : newResult.some((result, index) => {\n const prev = this.#result[index]\n return !prev || !shallowEqualObjects(result, prev)\n })\n\n if (!hasStructuralChange && !hasResultChange) return\n\n if (hasStructuralChange) {\n this.#observerMatches = newObserverMatches\n this.#observers = newObservers\n }\n\n this.#result = newResult\n\n if (!this.hasListeners()) return\n\n if (hasStructuralChange) {\n difference(prevObservers, newObservers).forEach((observer) => {\n observer.destroy()\n })\n difference(newObservers, prevObservers).forEach((observer) => {\n observer.subscribe((result) => {\n this.#onUpdate(observer, result)\n })\n })\n }\n\n this.#notify()\n })\n }\n\n /**\n * Returns the most recently computed array of `QueryObserverResult`s, one\n * per observed query, in the same order as the queries passed to the\n * constructor or `setQueries`.\n * @returns The current results.\n * @example\n * ```ts\n * const results = observer.getCurrentResult()\n * const data = results.map((result) => result.data)\n * ```\n */\n getCurrentResult(): Array<QueryObserverResult> {\n return this.#result\n }\n\n /**\n * Returns the underlying `Query` instances currently being observed, in\n * the same order as the queries passed to the constructor or `setQueries`.\n * @returns The observed queries.\n */\n getQueries() {\n return this.#observers.map((observer) => observer.getCurrentQuery())\n }\n\n /**\n * Returns the underlying `QueryObserver` instances this observer manages,\n * in the same order as the queries passed to the constructor or\n * `setQueries`.\n * @returns The managed query observers.\n */\n getObservers() {\n return this.#observers\n }\n\n /**\n * The `QueriesObserver` counterpart of {@link QueryObserver#getOptimisticResult} — computes\n * the result for the given (already-defaulted) queries right now, synchronously. Called by\n * framework adapters (e.g. `useQueries`) ahead of subscribing, returning a tuple of the raw\n * per-query results, a function to compute the combined result from them, and a function to\n * wrap the results for property-access tracking.\n * @param queries - The defaulted options of the queries to compute the result for.\n * @param combine - The `combine` function used by the returned `combineResult`, if any.\n * @returns A tuple of the per-query results, a function that computes the combined result, and a\n * function that returns the results wrapped for property-access tracking.\n */\n getOptimisticResult(\n queries: Array<QueryObserverOptions>,\n combine: CombineFn<TCombinedResult> | undefined,\n ): [\n rawResult: Array<QueryObserverResult>,\n combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult,\n trackResult: () => Array<QueryObserverResult>,\n ] {\n const matches = this.#findMatchingObservers(queries)\n const result = matches.map((match) =>\n match.observer.getOptimisticResult(match.defaultedQueryOptions),\n )\n const queryHashes = matches.map(\n (match) => match.defaultedQueryOptions.queryHash,\n )\n\n return [\n result,\n (r?: Array<QueryObserverResult>) => {\n return this.#combineResult(r ?? result, combine, queryHashes)\n },\n () => {\n return this.#trackResult(result, matches)\n },\n ]\n }\n\n #trackResult(\n result: Array<QueryObserverResult>,\n matches: Array<QueryObserverMatch>,\n ) {\n const trackedProps = new Set<keyof QueryObserverResult>()\n\n return matches.map((match, index) => {\n const observerResult = result[index]!\n return !match.defaultedQueryOptions.notifyOnChangeProps\n ? match.observer.trackResult(observerResult, (accessedProp) => {\n // track property on all observers to ensure proper (synchronized) tracking (#7000)\n if (!trackedProps.has(accessedProp)) {\n trackedProps.add(accessedProp)\n matches.forEach((m) => {\n m.observer.trackProp(accessedProp)\n })\n }\n })\n : observerResult\n })\n }\n\n #combineResult(\n input: Array<QueryObserverResult>,\n combine: CombineFn<TCombinedResult> | undefined,\n queryHashes?: Array<string>,\n ): TCombinedResult {\n if (combine) {\n const lastHashes = this.#lastQueryHashes\n const queryHashesChanged =\n queryHashes !== undefined &&\n lastHashes !== undefined &&\n (lastHashes.length !== queryHashes.length ||\n queryHashes.some((hash, i) => hash !== lastHashes[i]))\n\n if (\n this.#result !== this.#lastResult ||\n queryHashesChanged ||\n combine !== this.#lastCombine\n ) {\n this.#lastCombine = combine\n this.#lastResult = this.#result\n\n if (queryHashes !== undefined) {\n this.#lastQueryHashes = queryHashes\n }\n this.#combinedResult = replaceEqualDeep(\n this.#combinedResult,\n combine(input),\n )\n }\n\n return this.#combinedResult\n }\n return input as any\n }\n\n #shouldSkipCombine(): boolean {\n return (\n !this.#options?.combine ||\n this.#observers.some((observer, index) => {\n return (\n observer.options.suspense && this.#result[index]?.data === undefined\n )\n })\n )\n }\n\n #findMatchingObservers(\n queries: Array<QueryObserverOptions>,\n ): Array<QueryObserverMatch> {\n const prevObserversMap = new Map<string, Array<QueryObserver>>()\n\n this.#observers.forEach((observer) => {\n const key = observer.options.queryHash\n if (!key) return\n\n const previousObservers = prevObserversMap.get(key)\n\n if (previousObservers) {\n previousObservers.push(observer)\n } else {\n prevObserversMap.set(key, [observer])\n }\n })\n\n const observers: Array<QueryObserverMatch> = []\n\n queries.forEach((options) => {\n const defaultedOptions = this.#client.defaultQueryOptions(options)\n const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift()\n const observer =\n match ?? new QueryObserver(this.#client, defaultedOptions)\n\n observers.push({\n defaultedQueryOptions: defaultedOptions,\n observer,\n })\n })\n\n return observers\n }\n\n #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {\n const index = this.#observers.indexOf(observer)\n if (index !== -1) {\n this.#result = this.#result.slice()\n this.#result[index] = result\n this.#notify()\n }\n }\n\n #notify(): void {\n if (this.hasListeners()) {\n const shouldSkipCombine = this.#shouldSkipCombine()\n const previousResult = this.#combinedResult\n const newResult = shouldSkipCombine\n ? previousResult\n : this.#combineResult(\n this.#trackResult(this.#result, this.#observerMatches),\n this.#options?.combine,\n )\n\n if (shouldSkipCombine || previousResult !== newResult) {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(this.#result)\n })\n })\n }\n }\n }\n}\n\ntype QueryObserverMatch = {\n defaultedQueryOptions: DefaultedQueryObserverOptions\n observer: QueryObserver\n}\n"],"mappings":";;;;;;;;;;;;AAiBA,SAAS,WAAc,QAAkB,QAA4B;CACnE,MAAM,aAAa,IAAI,IAAI,MAAM;CACjC,OAAO,OAAO,QAAQ,MAAM,CAAC,WAAW,IAAI,CAAC,CAAC;AAChD;;;;;;;;;;;;;;;;;;;AA2CA,IAAa,kBAAb,cAEUA,qBAAAA,aAAsC;CAC9C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,mBAA8C,CAAC;CAE/C,YACE,QACA,SACA,SACA;EACA,MAAM;EAEN,KAAK,UAAU;EACf,KAAK,WAAW;EAChB,KAAK,WAAW,CAAC;EACjB,KAAK,aAAa,CAAC;EACnB,KAAK,UAAU,CAAC;EAEhB,KAAK,WAAW,OAAO;CACzB;CAEA,cAAuC;EACrC,IAAI,KAAK,UAAU,SAAS,GAC1B,KAAK,WAAW,SAAS,aAAa;GACpC,SAAS,WAAW,WAAW;IAC7B,KAAK,UAAU,UAAU,MAAM;GACjC,CAAC;EACH,CAAC;CAEL;CAEA,gBAAyC;EACvC,IAAI,CAAC,KAAK,UAAU,MAClB,KAAK,QAAQ;CAEjB;;;;;CAMA,UAAgB;EACd,KAAK,4BAAY,IAAI,IAAI;EACzB,KAAK,WAAW,SAAS,aAAa;GACpC,SAAS,QAAQ;EACnB,CAAC;CACH;;;;;;;;;;;;;;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SAAS,KAAK,gBAAgB,GACrD,KAAK,UAAU,OACjB;GAEJ,IAAI,qBAAqB,mBAAmB,WAC1C,sBAAA,cAAc,YAAY;IACxB,KAAK,UAAU,SAAS,aAAa;KACnC,SAAS,KAAK,OAAO;IACvB,CAAC;GACH,CAAC;EAEL;CACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { t as Subscribable } from "./subscribable-D2lAzdDi.cjs";
2
- import { At as QueryObserverOptions, Pt as QueryObserverResult, ar as QueryObserver, on as QueryClient, tr as Query } from "./hydration-BIRJt69T.cjs";
2
+ import { $t as QueryObserverOptions, D as Query, _ as QueryClient, j as QueryObserver, rn as QueryObserverResult } from "./hydration-24GwbSaU.cjs";
3
3
  type QueriesObserverListener = (result: Array<QueryObserverResult>) => void;
4
4
  type CombineFn<TCombinedResult> = (result: Array<QueryObserverResult>) => TCombinedResult;
5
5
  /**
@@ -1,5 +1,5 @@
1
1
  import { t as Subscribable } from "./subscribable-D2lAzdDi.js";
2
- import { At as QueryObserverOptions, Pt as QueryObserverResult, ar as QueryObserver, on as QueryClient, tr as Query } from "./hydration-9_kOYxJM.js";
2
+ import { $t as QueryObserverOptions, D as Query, _ as QueryClient, j as QueryObserver, rn as QueryObserverResult } from "./hydration-Cbq_heQS.js";
3
3
  type QueriesObserverListener = (result: Array<QueryObserverResult>) => void;
4
4
  type CombineFn<TCombinedResult> = (result: Array<QueryObserverResult>) => TCombinedResult;
5
5
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"queriesObserver.js","names":[],"sources":["../../src/queriesObserver.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { QueryObserver } from './queryObserver'\nimport { Subscribable } from './subscribable'\nimport { replaceEqualDeep, shallowEqualObjects } from './utils'\nimport type {\n DefaultedQueryObserverOptions,\n QueryObserverOptions,\n QueryObserverResult,\n} from './types'\nimport type { QueryClient } from './queryClient'\n\n/**\n * Returns the items of `array1` that are not in `array2`.\n * @param array1 - The items to filter.\n * @param array2 - The items to exclude.\n * @returns A new array with the items of `array1` that are not in `array2`.\n */\nfunction difference<T>(array1: Array<T>, array2: Array<T>): Array<T> {\n const excludeSet = new Set(array2)\n return array1.filter((x) => !excludeSet.has(x))\n}\n\ntype QueriesObserverListener = (result: Array<QueryObserverResult>) => void\n\ntype CombineFn<TCombinedResult> = (\n result: Array<QueryObserverResult>,\n) => TCombinedResult\n\n/**\n * Options for a `QueriesObserver` that apply to all of its queries at once.\n */\nexport interface QueriesObserverOptions<\n TCombinedResult = Array<QueryObserverResult>,\n> {\n /**\n * A function that combines the array of `QueryObserverResult`s (one per\n * observed query) into a single value. The combined value is memoized and\n * only recomputed when one of the underlying results, the query hashes, or\n * the `combine` function itself changes.\n *\n * Defaults to returning the array of `QueryObserverResult`s unchanged.\n */\n combine?: CombineFn<TCombinedResult>\n}\n\n/**\n * A `QueriesObserver` watches an array of queries at once, exposing them as\n * a single array of `QueryObserverResult`s (or, when a `combine` option is\n * given, as a combined value derived from that array). It manages one\n * internal `QueryObserver` per query, and is the primitive that framework\n * adapters (e.g. `useQueries`) build their hooks on top of.\n * @example\n * ```ts\n * const observer = new QueriesObserver(queryClient, [\n * { queryKey: ['post', 1], queryFn: fetchPost },\n * { queryKey: ['post', 2], queryFn: fetchPost },\n * ])\n *\n * const unsubscribe = observer.subscribe((result) => {\n * console.log(result)\n * })\n * ```\n */\nexport class QueriesObserver<\n TCombinedResult = Array<QueryObserverResult>,\n> extends Subscribable<QueriesObserverListener> {\n #client: QueryClient\n #result!: Array<QueryObserverResult>\n #queries: Array<QueryObserverOptions>\n #options?: QueriesObserverOptions<TCombinedResult>\n #observers: Array<QueryObserver>\n #combinedResult!: TCombinedResult\n #lastCombine?: CombineFn<TCombinedResult>\n #lastResult?: Array<QueryObserverResult>\n #lastQueryHashes?: Array<string>\n #observerMatches: Array<QueryObserverMatch> = []\n\n constructor(\n client: QueryClient,\n queries: Array<QueryObserverOptions<any, any, any, any, any>>,\n options?: QueriesObserverOptions<TCombinedResult>,\n ) {\n super()\n\n this.#client = client\n this.#options = options\n this.#queries = []\n this.#observers = []\n this.#result = []\n\n this.setQueries(queries)\n }\n\n protected override onSubscribe(): void {\n if (this.listeners.size === 1) {\n this.#observers.forEach((observer) => {\n observer.subscribe((result) => {\n this.#onUpdate(observer, result)\n })\n })\n }\n }\n\n protected override onUnsubscribe(): void {\n if (!this.listeners.size) {\n this.destroy()\n }\n }\n\n /**\n * Stops observing all queries: clears all listeners and destroys every\n * underlying `QueryObserver` this observer manages.\n */\n destroy(): void {\n this.listeners = new Set()\n this.#observers.forEach((observer) => {\n observer.destroy()\n })\n }\n\n /**\n * Replaces the set of queries being observed. Existing `QueryObserver`s\n * are reused for queries that match an already-observed query hash;\n * observers for queries that are no longer present are destroyed, and new\n * observers are created and subscribed to for newly added queries.\n * @param queries - The options of the queries to observe.\n * @param options - Replaces the observer's options, e.g. its `combine` function.\n * @example\n * ```ts\n * observer.setQueries([\n * { queryKey: ['post', 1], queryFn: fetchPost },\n * { queryKey: ['post', 3], queryFn: fetchPost },\n * ])\n * ```\n */\n setQueries(\n queries: Array<QueryObserverOptions>,\n options?: QueriesObserverOptions<TCombinedResult>,\n ): void {\n this.#queries = queries\n this.#options = options\n\n if (process.env.NODE_ENV !== 'production') {\n const queryHashes = queries.map(\n (query) => this.#client.defaultQueryOptions(query).queryHash,\n )\n if (new Set(queryHashes).size !== queryHashes.length) {\n console.warn(\n '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.',\n )\n }\n }\n\n notifyManager.batch(() => {\n const prevObservers = this.#observers\n\n const newObserverMatches = this.#findMatchingObservers(this.#queries)\n\n // set options for the new observers to notify of changes\n newObserverMatches.forEach((match) =>\n match.observer.setOptions(match.defaultedQueryOptions),\n )\n\n const newObservers = newObserverMatches.map((match) => match.observer)\n const newResult = newObservers.map((observer) =>\n observer.getCurrentResult(),\n )\n\n const hasLengthChange = prevObservers.length !== newObservers.length\n const hasIndexChange = newObservers.some(\n (observer, index) => observer !== prevObservers[index],\n )\n const hasStructuralChange = hasLengthChange || hasIndexChange\n\n const hasResultChange = hasStructuralChange\n ? true\n : newResult.some((result, index) => {\n const prev = this.#result[index]\n return !prev || !shallowEqualObjects(result, prev)\n })\n\n if (!hasStructuralChange && !hasResultChange) return\n\n if (hasStructuralChange) {\n this.#observerMatches = newObserverMatches\n this.#observers = newObservers\n }\n\n this.#result = newResult\n\n if (!this.hasListeners()) return\n\n if (hasStructuralChange) {\n difference(prevObservers, newObservers).forEach((observer) => {\n observer.destroy()\n })\n difference(newObservers, prevObservers).forEach((observer) => {\n observer.subscribe((result) => {\n this.#onUpdate(observer, result)\n })\n })\n }\n\n this.#notify()\n })\n }\n\n /**\n * Returns the most recently computed array of `QueryObserverResult`s, one\n * per observed query, in the same order as the queries passed to the\n * constructor or `setQueries`.\n * @returns The current results.\n * @example\n * ```ts\n * const results = observer.getCurrentResult()\n * const data = results.map((result) => result.data)\n * ```\n */\n getCurrentResult(): Array<QueryObserverResult> {\n return this.#result\n }\n\n /**\n * Returns the underlying `Query` instances currently being observed, in\n * the same order as the queries passed to the constructor or `setQueries`.\n * @returns The observed queries.\n */\n getQueries() {\n return this.#observers.map((observer) => observer.getCurrentQuery())\n }\n\n /**\n * Returns the underlying `QueryObserver` instances this observer manages,\n * in the same order as the queries passed to the constructor or\n * `setQueries`.\n * @returns The managed query observers.\n */\n getObservers() {\n return this.#observers\n }\n\n /**\n * The `QueriesObserver` counterpart of {@link QueryObserver#getOptimisticResult} — computes\n * the result for the given (already-defaulted) queries right now, synchronously. Called by\n * framework adapters (e.g. `useQueries`) ahead of subscribing, returning a tuple of the raw\n * per-query results, a function to compute the combined result from them, and a function to\n * wrap the results for property-access tracking.\n * @param queries - The defaulted options of the queries to compute the result for.\n * @param combine - The `combine` function used by the returned `combineResult`, if any.\n * @returns A tuple of the per-query results, a function that computes the combined result, and a\n * function that returns the results wrapped for property-access tracking.\n */\n getOptimisticResult(\n queries: Array<QueryObserverOptions>,\n combine: CombineFn<TCombinedResult> | undefined,\n ): [\n rawResult: Array<QueryObserverResult>,\n combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult,\n trackResult: () => Array<QueryObserverResult>,\n ] {\n const matches = this.#findMatchingObservers(queries)\n const result = matches.map((match) =>\n match.observer.getOptimisticResult(match.defaultedQueryOptions),\n )\n const queryHashes = matches.map(\n (match) => match.defaultedQueryOptions.queryHash,\n )\n\n return [\n result,\n (r?: Array<QueryObserverResult>) => {\n return this.#combineResult(r ?? result, combine, queryHashes)\n },\n () => {\n return this.#trackResult(result, matches)\n },\n ]\n }\n\n #trackResult(\n result: Array<QueryObserverResult>,\n matches: Array<QueryObserverMatch>,\n ) {\n const trackedProps = new Set<keyof QueryObserverResult>()\n\n return matches.map((match, index) => {\n const observerResult = result[index]!\n return !match.defaultedQueryOptions.notifyOnChangeProps\n ? match.observer.trackResult(observerResult, (accessedProp) => {\n // track property on all observers to ensure proper (synchronized) tracking (#7000)\n if (!trackedProps.has(accessedProp)) {\n trackedProps.add(accessedProp)\n matches.forEach((m) => {\n m.observer.trackProp(accessedProp)\n })\n }\n })\n : observerResult\n })\n }\n\n #combineResult(\n input: Array<QueryObserverResult>,\n combine: CombineFn<TCombinedResult> | undefined,\n queryHashes?: Array<string>,\n ): TCombinedResult {\n if (combine) {\n const lastHashes = this.#lastQueryHashes\n const queryHashesChanged =\n queryHashes !== undefined &&\n lastHashes !== undefined &&\n (lastHashes.length !== queryHashes.length ||\n queryHashes.some((hash, i) => hash !== lastHashes[i]))\n\n if (\n this.#result !== this.#lastResult ||\n queryHashesChanged ||\n combine !== this.#lastCombine\n ) {\n this.#lastCombine = combine\n this.#lastResult = this.#result\n\n if (queryHashes !== undefined) {\n this.#lastQueryHashes = queryHashes\n }\n this.#combinedResult = replaceEqualDeep(\n this.#combinedResult,\n combine(input),\n )\n }\n\n return this.#combinedResult\n }\n return input as any\n }\n\n #shouldSkipCombine(): boolean {\n return (\n !this.#options?.combine ||\n this.#observers.some((observer, index) => {\n return (\n observer.options.suspense && this.#result[index]?.data === undefined\n )\n })\n )\n }\n\n #findMatchingObservers(\n queries: Array<QueryObserverOptions>,\n ): Array<QueryObserverMatch> {\n const prevObserversMap = new Map<string, Array<QueryObserver>>()\n\n this.#observers.forEach((observer) => {\n const key = observer.options.queryHash\n if (!key) return\n\n const previousObservers = prevObserversMap.get(key)\n\n if (previousObservers) {\n previousObservers.push(observer)\n } else {\n prevObserversMap.set(key, [observer])\n }\n })\n\n const observers: Array<QueryObserverMatch> = []\n\n queries.forEach((options) => {\n const defaultedOptions = this.#client.defaultQueryOptions(options)\n const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift()\n const observer =\n match ?? new QueryObserver(this.#client, defaultedOptions)\n\n observers.push({\n defaultedQueryOptions: defaultedOptions,\n observer,\n })\n })\n\n return observers\n }\n\n #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {\n const index = this.#observers.indexOf(observer)\n if (index !== -1) {\n this.#result = this.#result.slice()\n this.#result[index] = result\n this.#notify()\n }\n }\n\n #notify(): void {\n if (this.hasListeners()) {\n const shouldSkipCombine = this.#shouldSkipCombine()\n const previousResult = this.#combinedResult\n const newResult = shouldSkipCombine\n ? previousResult\n : this.#combineResult(\n this.#trackResult(this.#result, this.#observerMatches),\n this.#options?.combine,\n )\n\n if (shouldSkipCombine || previousResult !== newResult) {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(this.#result)\n })\n })\n }\n }\n }\n}\n\ntype QueryObserverMatch = {\n defaultedQueryOptions: DefaultedQueryObserverOptions\n observer: QueryObserver\n}\n"],"mappings":";;;;;;;;;;;AAiBA,SAAS,WAAc,QAAkB,QAA4B;CACnE,MAAM,aAAa,IAAI,IAAI,MAAM;CACjC,OAAO,OAAO,QAAQ,MAAM,CAAC,WAAW,IAAI,CAAC,CAAC;AAChD;;;;;;;;;;;;;;;;;;;AA2CA,IAAa,kBAAb,cAEU,aAAsC;CAC9C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,mBAA8C,CAAC;CA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iBAAiB,SAAS,CAAC,EAAE,MAAM,KAE3D,IAAI,cAAc,KAAK,SAAS,gBAAgB;GAE3D,UAAU,KAAK;IACb,uBAAuB;IACvB;GACF,CAAC;EACH,CAAC;EAED,OAAO;CACT;CAEA,UAAU,UAAyB,QAAmC;EACpE,MAAM,QAAQ,KAAK,WAAW,QAAQ,QAAQ;EAC9C,IAAI,UAAU,IAAI;GAChB,KAAK,UAAU,KAAK,QAAQ,MAAM;GAClC,KAAK,QAAQ,SAAS;GACtB,KAAK,QAAQ;EACf;CACF;CAEA,UAAgB;EACd,IAAI,KAAK,aAAa,GAAG;GACvB,MAAM,oBAAoB,KAAK,mBAAmB;GAClD,MAAM,iBAAiB,KAAK;GAC5B,MAAM,YAAY,oBACd,iBACA,KAAK,eACH,KAAK,aAAa,KAAK,SAAS,KAAK,gBAAgB,GACrD,KAAK,UAAU,OACjB;GAEJ,IAAI,qBAAqB,mBAAmB,WAC1C,cAAc,YAAY;IACxB,KAAK,UAAU,SAAS,aAAa;KACnC,SAAS,KAAK,OAAO;IACvB,CAAC;GACH,CAAC;EAEL;CACF;AACF"}
1
+ {"version":3,"file":"queriesObserver.js","names":[],"sources":["../../src/queriesObserver.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { QueryObserver } from './queryObserver'\nimport { Subscribable } from './subscribable'\nimport { replaceEqualDeep, shallowEqualObjects } from './utils'\nimport type { QueryClient } from './queryClient'\nimport type {\n DefaultedQueryObserverOptions,\n QueryObserverOptions,\n QueryObserverResult,\n} from './types'\n\n/**\n * Returns the items of `array1` that are not in `array2`.\n * @param array1 - The items to filter.\n * @param array2 - The items to exclude.\n * @returns A new array with the items of `array1` that are not in `array2`.\n */\nfunction difference<T>(array1: Array<T>, array2: Array<T>): Array<T> {\n const excludeSet = new Set(array2)\n return array1.filter((x) => !excludeSet.has(x))\n}\n\ntype QueriesObserverListener = (result: Array<QueryObserverResult>) => void\n\ntype CombineFn<TCombinedResult> = (\n result: Array<QueryObserverResult>,\n) => TCombinedResult\n\n/**\n * Options for a `QueriesObserver` that apply to all of its queries at once.\n */\nexport interface QueriesObserverOptions<\n TCombinedResult = Array<QueryObserverResult>,\n> {\n /**\n * A function that combines the array of `QueryObserverResult`s (one per\n * observed query) into a single value. The combined value is memoized and\n * only recomputed when one of the underlying results, the query hashes, or\n * the `combine` function itself changes.\n *\n * Defaults to returning the array of `QueryObserverResult`s unchanged.\n */\n combine?: CombineFn<TCombinedResult>\n}\n\n/**\n * A `QueriesObserver` watches an array of queries at once, exposing them as\n * a single array of `QueryObserverResult`s (or, when a `combine` option is\n * given, as a combined value derived from that array). It manages one\n * internal `QueryObserver` per query, and is the primitive that framework\n * adapters (e.g. `useQueries`) build their hooks on top of.\n * @example\n * ```ts\n * const observer = new QueriesObserver(queryClient, [\n * { queryKey: ['post', 1], queryFn: fetchPost },\n * { queryKey: ['post', 2], queryFn: fetchPost },\n * ])\n *\n * const unsubscribe = observer.subscribe((result) => {\n * console.log(result)\n * })\n * ```\n */\nexport class QueriesObserver<\n TCombinedResult = Array<QueryObserverResult>,\n> extends Subscribable<QueriesObserverListener> {\n #client: QueryClient\n #result!: Array<QueryObserverResult>\n #queries: Array<QueryObserverOptions>\n #options?: QueriesObserverOptions<TCombinedResult>\n #observers: Array<QueryObserver>\n #combinedResult!: TCombinedResult\n #lastCombine?: CombineFn<TCombinedResult>\n #lastResult?: Array<QueryObserverResult>\n #lastQueryHashes?: Array<string>\n #observerMatches: Array<QueryObserverMatch> = []\n\n constructor(\n client: QueryClient,\n queries: Array<QueryObserverOptions<any, any, any, any, any>>,\n options?: QueriesObserverOptions<TCombinedResult>,\n ) {\n super()\n\n this.#client = client\n this.#options = options\n this.#queries = []\n this.#observers = []\n this.#result = []\n\n this.setQueries(queries)\n }\n\n protected override onSubscribe(): void {\n if (this.listeners.size === 1) {\n this.#observers.forEach((observer) => {\n observer.subscribe((result) => {\n this.#onUpdate(observer, result)\n })\n })\n }\n }\n\n protected override onUnsubscribe(): void {\n if (!this.listeners.size) {\n this.destroy()\n }\n }\n\n /**\n * Stops observing all queries: clears all listeners and destroys every\n * underlying `QueryObserver` this observer manages.\n */\n destroy(): void {\n this.listeners = new Set()\n this.#observers.forEach((observer) => {\n observer.destroy()\n })\n }\n\n /**\n * Replaces the set of queries being observed. Existing `QueryObserver`s\n * are reused for queries that match an already-observed query hash;\n * observers for queries that are no longer present are destroyed, and new\n * observers are created and subscribed to for newly added queries.\n * @param queries - The options of the queries to observe.\n * @param options - Replaces the observer's options, e.g. its `combine` function.\n * @example\n * ```ts\n * observer.setQueries([\n * { queryKey: ['post', 1], queryFn: fetchPost },\n * { queryKey: ['post', 3], queryFn: fetchPost },\n * ])\n * ```\n */\n setQueries(\n queries: Array<QueryObserverOptions>,\n options?: QueriesObserverOptions<TCombinedResult>,\n ): void {\n this.#queries = queries\n this.#options = options\n\n if (process.env.NODE_ENV !== 'production') {\n const queryHashes = queries.map(\n (query) => this.#client.defaultQueryOptions(query).queryHash,\n )\n if (new Set(queryHashes).size !== queryHashes.length) {\n console.warn(\n '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.',\n )\n }\n }\n\n notifyManager.batch(() => {\n const prevObservers = this.#observers\n\n const newObserverMatches = this.#findMatchingObservers(this.#queries)\n\n // set options for the new observers to notify of changes\n newObserverMatches.forEach((match) =>\n match.observer.setOptions(match.defaultedQueryOptions),\n )\n\n const newObservers = newObserverMatches.map((match) => match.observer)\n const newResult = newObservers.map((observer) =>\n observer.getCurrentResult(),\n )\n\n const hasLengthChange = prevObservers.length !== newObservers.length\n const hasIndexChange = newObservers.some(\n (observer, index) => observer !== prevObservers[index],\n )\n const hasStructuralChange = hasLengthChange || hasIndexChange\n\n const hasResultChange = hasStructuralChange\n ? true\n : newResult.some((result, index) => {\n const prev = this.#result[index]\n return !prev || !shallowEqualObjects(result, prev)\n })\n\n if (!hasStructuralChange && !hasResultChange) return\n\n if (hasStructuralChange) {\n this.#observerMatches = newObserverMatches\n this.#observers = newObservers\n }\n\n this.#result = newResult\n\n if (!this.hasListeners()) return\n\n if (hasStructuralChange) {\n difference(prevObservers, newObservers).forEach((observer) => {\n observer.destroy()\n })\n difference(newObservers, prevObservers).forEach((observer) => {\n observer.subscribe((result) => {\n this.#onUpdate(observer, result)\n })\n })\n }\n\n this.#notify()\n })\n }\n\n /**\n * Returns the most recently computed array of `QueryObserverResult`s, one\n * per observed query, in the same order as the queries passed to the\n * constructor or `setQueries`.\n * @returns The current results.\n * @example\n * ```ts\n * const results = observer.getCurrentResult()\n * const data = results.map((result) => result.data)\n * ```\n */\n getCurrentResult(): Array<QueryObserverResult> {\n return this.#result\n }\n\n /**\n * Returns the underlying `Query` instances currently being observed, in\n * the same order as the queries passed to the constructor or `setQueries`.\n * @returns The observed queries.\n */\n getQueries() {\n return this.#observers.map((observer) => observer.getCurrentQuery())\n }\n\n /**\n * Returns the underlying `QueryObserver` instances this observer manages,\n * in the same order as the queries passed to the constructor or\n * `setQueries`.\n * @returns The managed query observers.\n */\n getObservers() {\n return this.#observers\n }\n\n /**\n * The `QueriesObserver` counterpart of {@link QueryObserver#getOptimisticResult} — computes\n * the result for the given (already-defaulted) queries right now, synchronously. Called by\n * framework adapters (e.g. `useQueries`) ahead of subscribing, returning a tuple of the raw\n * per-query results, a function to compute the combined result from them, and a function to\n * wrap the results for property-access tracking.\n * @param queries - The defaulted options of the queries to compute the result for.\n * @param combine - The `combine` function used by the returned `combineResult`, if any.\n * @returns A tuple of the per-query results, a function that computes the combined result, and a\n * function that returns the results wrapped for property-access tracking.\n */\n getOptimisticResult(\n queries: Array<QueryObserverOptions>,\n combine: CombineFn<TCombinedResult> | undefined,\n ): [\n rawResult: Array<QueryObserverResult>,\n combineResult: (r?: Array<QueryObserverResult>) => TCombinedResult,\n trackResult: () => Array<QueryObserverResult>,\n ] {\n const matches = this.#findMatchingObservers(queries)\n const result = matches.map((match) =>\n match.observer.getOptimisticResult(match.defaultedQueryOptions),\n )\n const queryHashes = matches.map(\n (match) => match.defaultedQueryOptions.queryHash,\n )\n\n return [\n result,\n (r?: Array<QueryObserverResult>) => {\n return this.#combineResult(r ?? result, combine, queryHashes)\n },\n () => {\n return this.#trackResult(result, matches)\n },\n ]\n }\n\n #trackResult(\n result: Array<QueryObserverResult>,\n matches: Array<QueryObserverMatch>,\n ) {\n const trackedProps = new Set<keyof QueryObserverResult>()\n\n return matches.map((match, index) => {\n const observerResult = result[index]!\n return !match.defaultedQueryOptions.notifyOnChangeProps\n ? match.observer.trackResult(observerResult, (accessedProp) => {\n // track property on all observers to ensure proper (synchronized) tracking (#7000)\n if (!trackedProps.has(accessedProp)) {\n trackedProps.add(accessedProp)\n matches.forEach((m) => {\n m.observer.trackProp(accessedProp)\n })\n }\n })\n : observerResult\n })\n }\n\n #combineResult(\n input: Array<QueryObserverResult>,\n combine: CombineFn<TCombinedResult> | undefined,\n queryHashes?: Array<string>,\n ): TCombinedResult {\n if (combine) {\n const lastHashes = this.#lastQueryHashes\n const queryHashesChanged =\n queryHashes !== undefined &&\n lastHashes !== undefined &&\n (lastHashes.length !== queryHashes.length ||\n queryHashes.some((hash, i) => hash !== lastHashes[i]))\n\n if (\n this.#result !== this.#lastResult ||\n queryHashesChanged ||\n combine !== this.#lastCombine\n ) {\n this.#lastCombine = combine\n this.#lastResult = this.#result\n\n if (queryHashes !== undefined) {\n this.#lastQueryHashes = queryHashes\n }\n this.#combinedResult = replaceEqualDeep(\n this.#combinedResult,\n combine(input),\n )\n }\n\n return this.#combinedResult\n }\n return input as any\n }\n\n #shouldSkipCombine(): boolean {\n return (\n !this.#options?.combine ||\n this.#observers.some((observer, index) => {\n return (\n observer.options.suspense && this.#result[index]?.data === undefined\n )\n })\n )\n }\n\n #findMatchingObservers(\n queries: Array<QueryObserverOptions>,\n ): Array<QueryObserverMatch> {\n const prevObserversMap = new Map<string, Array<QueryObserver>>()\n\n this.#observers.forEach((observer) => {\n const key = observer.options.queryHash\n if (!key) return\n\n const previousObservers = prevObserversMap.get(key)\n\n if (previousObservers) {\n previousObservers.push(observer)\n } else {\n prevObserversMap.set(key, [observer])\n }\n })\n\n const observers: Array<QueryObserverMatch> = []\n\n queries.forEach((options) => {\n const defaultedOptions = this.#client.defaultQueryOptions(options)\n const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift()\n const observer =\n match ?? new QueryObserver(this.#client, defaultedOptions)\n\n observers.push({\n defaultedQueryOptions: defaultedOptions,\n observer,\n })\n })\n\n return observers\n }\n\n #onUpdate(observer: QueryObserver, result: QueryObserverResult): void {\n const index = this.#observers.indexOf(observer)\n if (index !== -1) {\n this.#result = this.#result.slice()\n this.#result[index] = result\n this.#notify()\n }\n }\n\n #notify(): void {\n if (this.hasListeners()) {\n const shouldSkipCombine = this.#shouldSkipCombine()\n const previousResult = this.#combinedResult\n const newResult = shouldSkipCombine\n ? previousResult\n : this.#combineResult(\n this.#trackResult(this.#result, this.#observerMatches),\n this.#options?.combine,\n )\n\n if (shouldSkipCombine || previousResult !== newResult) {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(this.#result)\n })\n })\n }\n }\n }\n}\n\ntype QueryObserverMatch = {\n defaultedQueryOptions: DefaultedQueryObserverOptions\n observer: QueryObserver\n}\n"],"mappings":";;;;;;;;;;;AAiBA,SAAS,WAAc,QAAkB,QAA4B;CACnE,MAAM,aAAa,IAAI,IAAI,MAAM;CACjC,OAAO,OAAO,QAAQ,MAAM,CAAC,WAAW,IAAI,CAAC,CAAC;AAChD;;;;;;;;;;;;;;;;;;;AA2CA,IAAa,kBAAb,cAEU,aAAsC;CAC9C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,mBAA8C,CAAC;CAE/C,YACE,QACA,SACA,SACA;EACA,MAAM;EAEN,KAAK,UAAU;EACf,KAAK,WAAW;EAChB,KAAK,WAAW,CAAC;EACjB,KAAK,aAAa,CAAC;EACnB,KAAK,UAAU,CAAC;EAEhB,KAAK,WAAW,OAAO;CACzB;CAEA,cAAuC;EACrC,IAAI,KAAK,UAAU,SAAS,G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;EAC9C,IAAI,UAAU,IAAI;GAChB,KAAK,UAAU,KAAK,QAAQ,MAAM;GAClC,KAAK,QAAQ,SAAS;GACtB,KAAK,QAAQ;EACf;CACF;CAEA,UAAgB;EACd,IAAI,KAAK,aAAa,GAAG;GACvB,MAAM,oBAAoB,KAAK,mBAAmB;GAClD,MAAM,iBAAiB,KAAK;GAC5B,MAAM,YAAY,oBACd,iBACA,KAAK,eACH,KAAK,aAAa,KAAK,SAAS,KAAK,gBAAgB,GACrD,KAAK,UAAU,OACjB;GAEJ,IAAI,qBAAqB,mBAAmB,WAC1C,cAAc,YAAY;IACxB,KAAK,UAAU,SAAS,aAAa;KACnC,SAAS,KAAK,OAAO;IACvB,CAAC;GACH,CAAC;EAEL;CACF;AACF"}
@@ -1,9 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_utils = require("./utils.cjs");
3
+ const require_infiniteQueryBehavior = require("./infiniteQueryBehavior.cjs");
3
4
  const require_notifyManager = require("./notifyManager.cjs");
4
- const require_retryer = require("./retryer.cjs");
5
5
  const require_removable = require("./removable.cjs");
6
- const require_infiniteQueryBehavior = require("./infiniteQueryBehavior.cjs");
6
+ const require_retryer = require("./retryer.cjs");
7
7
  // src/query.ts
8
8
  /**
9
9
  * Represents a single cached query. A `Query` holds the query's key, options,
@@ -507,7 +507,7 @@ var Query = class extends require_removable.Removable {
507
507
  ...fetchState(state.data, this.options),
508
508
  fetchMeta: action.meta ?? null
509
509
  };
510
- case "success":
510
+ case "success": {
511
511
  const newState = {
512
512
  ...state,
513
513
  ...successState(action.data, action.dataUpdatedAt),
@@ -520,7 +520,8 @@ var Query = class extends require_removable.Removable {
520
520
  };
521
521
  this.#revertState = action.manual ? newState : void 0;
522
522
  return newState;
523
- case "error":
523
+ }
524
+ case "error": {
524
525
  const error = action.error;
525
526
  return {
526
527
  ...state,
@@ -533,6 +534,7 @@ var Query = class extends require_removable.Removable {
533
534
  status: "error",
534
535
  isInvalidated: true
535
536
  };
537
+ }
536
538
  case "invalidate": return {
537
539
  ...state,
538
540
  isInvalidated: true
@@ -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;CAKlB;CAEA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CAEA,YAAY,QAA6D;EACvE,MAAM;EAEN,KAAK,uBAAuB;EAC5B,KAAK,kBAAkB,OAAO;EAC9B,KAAK,WAAW,OAAO,OAAO;EAC9B,KAAK,YAAY,CAAC;EAClB,KAAK,UAAU,OAAO;EACtB,KAAK,SAAS,KAAK,QAAQ,cAAc;EACzC,KAAK,WAAW,OAAO;EACvB,KAAK,YAAY,OAAO;EACxB,KAAK,gBAAgB,gBAAgB,KAAK,OAAO;EACjD,KAAK,QAAQ,OAAO,SAAS,KAAK;EAClC,KAAK,WAAW;CAClB;;;;;CAKA,IAAI,OAA8B;EAChC,OAAO,KAAK,QAAQ;CACtB;;;;;;CAOA,IAAI,YAAY;EACd,OAAO,KAAK;CACd;;;;;;CAOA,IAAI,UAAsC;EACxC,OAAO,KAAK,UAAU;CACxB;;;;;;;CAQA,WACE,SACM;EACN,KAAK,UAAU;GAAE,GAAG,KAAK;GAAiB,GAAG;EAAQ;EAErD,IAAI,SAAS,OACX,KAAK,aAAa,QAAQ;EAG5B,KAAK,aAAa,KAAK,QAAQ,MAAM;EAGrC,IAAI,KAAK,SAAS,KAAK,MAAM,SAAS,KAAA,GAAW;GAC/C,MAAM,eAAe,gBAAgB,KAAK,OAAO;GACjD,IAAI,aAAa,SAAS,KAAA,GAAW;IACnC,KAAK,SACH,aAAa,aAAa,MAAM,aAAa,aAAa,CAC5D;IACA,KAAK,gBAAgB;GACvB;EACF;CACF;CAEA,iBAAoC;EAClC,IAAI,CAAC,KAAK,UAAU,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;;;;;;;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.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;CAKlB;CAEA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CAEA,YAAY,QAA6D;EACvE,MAAM;EAEN,KAAK,uBAAuB;EAC5B,KAAK,kBAAkB,OAAO;EAC9B,KAAK,WAAW,OAAO,OAAO;EAC9B,KAAK,YAAY,CAAC;EAClB,KAAK,UAAU,OAAO;EACtB,KAAK,SAAS,KAAK,QAAQ,cAAc;EACzC,KAAK,WAAW,OAAO;EACvB,KAAK,YAAY,OAAO;EACxB,KAAK,gBAAgB,gBAAgB,KAAK,OAAO;EACjD,KAAK,QAAQ,OAAO,SAAS,KAAK;EAClC,KAAK,WAAW;CAClB;;;;;CAKA,IAAI,OAA8B;EAChC,OAAO,KAAK,QAAQ;CACtB;;;;;;CAOA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,cACH,OAAO;KACL,GAAG;KACH,eAAe;IACjB;IACF,KAAK,YACH,OAAO;KACL,GAAG;KACH,GAAG,OAAO;IACZ;GACJ;EACF;EAEA,KAAK,QAAQ,QAAQ,KAAK,KAAK;EAE/B,sBAAA,cAAc,YAAY;GAGxB,KAAK,UAAU,MAAM,CAAC,CAAC,SAAS,aAAa;IAC3C,SAAS,cAAc;GACzB,CAAC;GAED,KAAK,OAAO,OAAO;IAAE,OAAO;IAAM,MAAM;IAAW;GAAO,CAAC;EAC7D,CAAC;CACH;AACF;;;;;;;;;AAUA,SAAgB,WAMd,MACA,SACA;CACA,OAAO;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,8 +1,8 @@
1
1
  import { ensureQueryFn, fetchSignal, noop, replaceData, resolveQueryValue, skipToken, timeUntilStale } from "./utils.js";
2
+ import { infiniteQueryBehavior } from "./infiniteQueryBehavior.js";
2
3
  import { notifyManager } from "./notifyManager.js";
3
- import { CancelledError, canFetch, createRetryer } from "./retryer.js";
4
4
  import { Removable } from "./removable.js";
5
- import { infiniteQueryBehavior } from "./infiniteQueryBehavior.js";
5
+ import { CancelledError, canFetch, createRetryer } from "./retryer.js";
6
6
  // src/query.ts
7
7
  /**
8
8
  * Represents a single cached query. A `Query` holds the query's key, options,
@@ -506,7 +506,7 @@ var Query = class extends Removable {
506
506
  ...fetchState(state.data, this.options),
507
507
  fetchMeta: action.meta ?? null
508
508
  };
509
- case "success":
509
+ case "success": {
510
510
  const newState = {
511
511
  ...state,
512
512
  ...successState(action.data, action.dataUpdatedAt),
@@ -519,7 +519,8 @@ var Query = class extends Removable {
519
519
  };
520
520
  this.#revertState = action.manual ? newState : void 0;
521
521
  return newState;
522
- case "error":
522
+ }
523
+ case "error": {
523
524
  const error = action.error;
524
525
  return {
525
526
  ...state,
@@ -532,6 +533,7 @@ var Query = class extends Removable {
532
533
  status: "error",
533
534
  isInvalidated: true
534
535
  };
536
+ }
535
537
  case "invalidate": return {
536
538
  ...state,
537
539
  isInvalidated: true