@tanstack/query-core 5.103.2 → 5.103.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/legacy/{classPrivateFieldSet2-CV7wyte-.js → classPrivateFieldSet2-CukOTU3U.js} +5 -5
- package/build/legacy/{classPrivateFieldSet2-Bo0ZyOIv.cjs → classPrivateFieldSet2-CvCEk6bM.cjs} +5 -5
- package/build/legacy/{classPrivateMethodInitSpec-CBwa_Y7C.js → classPrivateMethodInitSpec-CgB-WYk3.js} +2 -2
- package/build/legacy/{classPrivateMethodInitSpec-DVhcLejn.cjs → classPrivateMethodInitSpec-Nr6mgZRs.cjs} +2 -2
- package/build/legacy/focusManager.cjs +1 -1
- package/build/legacy/focusManager.d.cts +1 -1
- package/build/legacy/focusManager.d.ts +1 -1
- package/build/legacy/focusManager.js +1 -1
- package/build/legacy/{hydration-Bp57N3SP.d.ts → hydration-B9t5w6NC.d.ts} +11 -4
- package/build/legacy/hydration-B9t5w6NC.d.ts.map +1 -0
- package/build/{modern/hydration-DRcloXEn.d.cts → legacy/hydration-Br9VIGXa.d.cts} +11 -4
- package/build/legacy/hydration-Br9VIGXa.d.cts.map +1 -0
- package/build/legacy/hydration.d.cts +1 -1
- package/build/legacy/hydration.d.ts +1 -1
- package/build/legacy/index.d.cts +1 -1
- package/build/legacy/index.d.ts +1 -1
- package/build/legacy/infiniteQueryBehavior.d.cts +1 -1
- package/build/legacy/infiniteQueryBehavior.d.ts +1 -1
- package/build/legacy/infiniteQueryObserver.d.cts +2 -2
- package/build/legacy/infiniteQueryObserver.d.ts +2 -2
- package/build/legacy/mutation.cjs +2 -2
- package/build/legacy/mutation.d.cts +1 -1
- package/build/legacy/mutation.d.ts +1 -1
- package/build/legacy/mutation.js +2 -2
- package/build/legacy/mutationCache.cjs +1 -1
- package/build/legacy/mutationCache.d.cts +1 -1
- package/build/legacy/mutationCache.d.ts +1 -1
- package/build/legacy/mutationCache.js +1 -1
- package/build/legacy/mutationObserver.cjs +2 -2
- package/build/legacy/mutationObserver.d.cts +1 -1
- package/build/legacy/mutationObserver.d.ts +1 -1
- package/build/legacy/mutationObserver.js +2 -2
- package/build/legacy/onlineManager.cjs +1 -1
- package/build/legacy/onlineManager.d.cts +1 -1
- package/build/legacy/onlineManager.d.ts +1 -1
- package/build/legacy/onlineManager.js +1 -1
- package/build/legacy/queriesObserver.cjs +2 -2
- package/build/legacy/queriesObserver.d.cts +2 -2
- package/build/legacy/queriesObserver.d.cts.map +1 -1
- package/build/legacy/queriesObserver.d.ts +2 -2
- package/build/legacy/queriesObserver.d.ts.map +1 -1
- package/build/legacy/queriesObserver.js +2 -2
- package/build/legacy/query.cjs +2 -2
- package/build/legacy/query.cjs.map +1 -1
- package/build/legacy/query.d.cts +1 -1
- package/build/legacy/query.d.ts +1 -1
- package/build/legacy/query.js +2 -2
- package/build/legacy/query.js.map +1 -1
- package/build/legacy/queryCache.cjs +1 -1
- package/build/legacy/queryCache.cjs.map +1 -1
- package/build/legacy/queryCache.d.cts +1 -1
- package/build/legacy/queryCache.d.ts +1 -1
- package/build/legacy/queryCache.js +1 -1
- package/build/legacy/queryCache.js.map +1 -1
- package/build/legacy/queryClient.cjs +8 -1
- package/build/legacy/queryClient.cjs.map +1 -1
- package/build/legacy/queryClient.d.cts +1 -1
- package/build/legacy/queryClient.d.ts +1 -1
- package/build/legacy/queryClient.js +8 -1
- package/build/legacy/queryClient.js.map +1 -1
- package/build/legacy/queryObserver.cjs +2 -2
- package/build/legacy/queryObserver.cjs.map +1 -1
- package/build/legacy/queryObserver.d.cts +1 -1
- package/build/legacy/queryObserver.d.ts +1 -1
- package/build/legacy/queryObserver.js +2 -2
- package/build/legacy/queryObserver.js.map +1 -1
- package/build/legacy/removable-0GzhW1PK.d.cts +22 -0
- package/build/legacy/removable-0GzhW1PK.d.cts.map +1 -0
- package/build/legacy/removable-0GzhW1PK.d.ts +22 -0
- package/build/legacy/removable-0GzhW1PK.d.ts.map +1 -0
- package/build/legacy/removable.cjs +10 -1
- package/build/legacy/removable.cjs.map +1 -1
- package/build/legacy/removable.d.cts +1 -1
- package/build/legacy/removable.d.ts +1 -1
- package/build/legacy/removable.js +10 -1
- package/build/legacy/removable.js.map +1 -1
- package/build/legacy/retryer.d.cts +1 -1
- package/build/legacy/retryer.d.ts +1 -1
- package/build/legacy/streamedQuery.cjs +0 -7
- package/build/legacy/streamedQuery.cjs.map +1 -1
- package/build/legacy/streamedQuery.d.cts +1 -8
- package/build/legacy/streamedQuery.d.cts.map +1 -1
- package/build/legacy/streamedQuery.d.ts +1 -8
- package/build/legacy/streamedQuery.d.ts.map +1 -1
- package/build/legacy/streamedQuery.js +0 -7
- package/build/legacy/streamedQuery.js.map +1 -1
- package/build/legacy/subscribable-CysQ0tne.d.cts +34 -0
- package/build/legacy/subscribable-CysQ0tne.d.cts.map +1 -0
- package/build/legacy/subscribable-CysQ0tne.d.ts +34 -0
- package/build/legacy/subscribable-CysQ0tne.d.ts.map +1 -0
- package/build/legacy/subscribable.cjs +22 -0
- package/build/legacy/subscribable.cjs.map +1 -1
- package/build/legacy/subscribable.d.cts +1 -1
- package/build/legacy/subscribable.d.ts +1 -1
- package/build/legacy/subscribable.js +22 -0
- package/build/legacy/subscribable.js.map +1 -1
- package/build/legacy/timeoutManager.cjs +1 -1
- package/build/legacy/timeoutManager.js +1 -1
- package/build/legacy/types.cjs.map +1 -1
- package/build/legacy/types.d.cts +1 -1
- package/build/legacy/types.d.ts +1 -1
- package/build/legacy/types.js.map +1 -1
- package/build/legacy/utils.d.cts +1 -1
- package/build/legacy/utils.d.ts +1 -1
- package/build/modern/focusManager.cjs.map +1 -1
- package/build/modern/focusManager.d.cts +1 -1
- package/build/modern/focusManager.d.ts +1 -1
- package/build/modern/focusManager.js.map +1 -1
- package/build/{legacy/hydration-DRcloXEn.d.cts → modern/hydration-B9t5w6NC.d.ts} +11 -4
- package/build/modern/hydration-B9t5w6NC.d.ts.map +1 -0
- package/build/modern/{hydration-Bp57N3SP.d.ts → hydration-Br9VIGXa.d.cts} +11 -4
- package/build/modern/hydration-Br9VIGXa.d.cts.map +1 -0
- package/build/modern/hydration.d.cts +1 -1
- package/build/modern/hydration.d.ts +1 -1
- package/build/modern/index.d.cts +1 -1
- package/build/modern/index.d.ts +1 -1
- package/build/modern/infiniteQueryBehavior.d.cts +1 -1
- package/build/modern/infiniteQueryBehavior.d.ts +1 -1
- package/build/modern/infiniteQueryObserver.d.cts +2 -2
- package/build/modern/infiniteQueryObserver.d.ts +2 -2
- package/build/modern/mutation.cjs.map +1 -1
- package/build/modern/mutation.d.cts +1 -1
- package/build/modern/mutation.d.ts +1 -1
- package/build/modern/mutation.js.map +1 -1
- package/build/modern/mutationCache.cjs.map +1 -1
- package/build/modern/mutationCache.d.cts +1 -1
- package/build/modern/mutationCache.d.ts +1 -1
- package/build/modern/mutationCache.js.map +1 -1
- package/build/modern/mutationObserver.cjs.map +1 -1
- package/build/modern/mutationObserver.d.cts +1 -1
- package/build/modern/mutationObserver.d.ts +1 -1
- package/build/modern/mutationObserver.js.map +1 -1
- package/build/modern/onlineManager.cjs.map +1 -1
- package/build/modern/onlineManager.d.cts +1 -1
- package/build/modern/onlineManager.d.ts +1 -1
- package/build/modern/onlineManager.js.map +1 -1
- package/build/modern/queriesObserver.cjs.map +1 -1
- package/build/modern/queriesObserver.d.cts +2 -2
- package/build/modern/queriesObserver.d.cts.map +1 -1
- package/build/modern/queriesObserver.d.ts +2 -2
- package/build/modern/queriesObserver.d.ts.map +1 -1
- package/build/modern/queriesObserver.js.map +1 -1
- package/build/modern/query.cjs.map +1 -1
- package/build/modern/query.d.cts +1 -1
- package/build/modern/query.d.ts +1 -1
- package/build/modern/query.js.map +1 -1
- package/build/modern/queryCache.cjs.map +1 -1
- package/build/modern/queryCache.d.cts +1 -1
- package/build/modern/queryCache.d.ts +1 -1
- package/build/modern/queryCache.js.map +1 -1
- package/build/modern/queryClient.cjs +7 -0
- package/build/modern/queryClient.cjs.map +1 -1
- package/build/modern/queryClient.d.cts +1 -1
- package/build/modern/queryClient.d.ts +1 -1
- package/build/modern/queryClient.js +7 -0
- package/build/modern/queryClient.js.map +1 -1
- package/build/modern/queryObserver.cjs.map +1 -1
- package/build/modern/queryObserver.d.cts +1 -1
- package/build/modern/queryObserver.d.ts +1 -1
- package/build/modern/queryObserver.js.map +1 -1
- package/build/modern/removable-0GzhW1PK.d.cts +22 -0
- package/build/modern/removable-0GzhW1PK.d.cts.map +1 -0
- package/build/modern/removable-0GzhW1PK.d.ts +22 -0
- package/build/modern/removable-0GzhW1PK.d.ts.map +1 -0
- package/build/modern/removable.cjs +9 -0
- package/build/modern/removable.cjs.map +1 -1
- package/build/modern/removable.d.cts +1 -1
- package/build/modern/removable.d.ts +1 -1
- package/build/modern/removable.js +9 -0
- package/build/modern/removable.js.map +1 -1
- package/build/modern/retryer.d.cts +1 -1
- package/build/modern/retryer.d.ts +1 -1
- package/build/modern/streamedQuery.cjs +0 -7
- package/build/modern/streamedQuery.cjs.map +1 -1
- package/build/modern/streamedQuery.d.cts +1 -8
- package/build/modern/streamedQuery.d.cts.map +1 -1
- package/build/modern/streamedQuery.d.ts +1 -8
- package/build/modern/streamedQuery.d.ts.map +1 -1
- package/build/modern/streamedQuery.js +0 -7
- package/build/modern/streamedQuery.js.map +1 -1
- package/build/modern/subscribable-CysQ0tne.d.cts +34 -0
- package/build/modern/subscribable-CysQ0tne.d.cts.map +1 -0
- package/build/modern/subscribable-CysQ0tne.d.ts +34 -0
- package/build/modern/subscribable-CysQ0tne.d.ts.map +1 -0
- package/build/modern/subscribable.cjs +22 -0
- package/build/modern/subscribable.cjs.map +1 -1
- package/build/modern/subscribable.d.cts +1 -1
- package/build/modern/subscribable.d.ts +1 -1
- package/build/modern/subscribable.js +22 -0
- package/build/modern/subscribable.js.map +1 -1
- package/build/modern/timeoutManager.cjs.map +1 -1
- package/build/modern/timeoutManager.js.map +1 -1
- package/build/modern/types.cjs.map +1 -1
- package/build/modern/types.d.cts +1 -1
- package/build/modern/types.d.ts +1 -1
- package/build/modern/types.js.map +1 -1
- package/build/modern/utils.d.cts +1 -1
- package/build/modern/utils.d.ts +1 -1
- package/package.json +3 -3
- package/src/query.ts +1 -2
- package/src/queryCache.ts +1 -2
- package/src/queryClient.ts +7 -0
- package/src/queryObserver.ts +4 -8
- package/src/removable.ts +9 -0
- package/src/streamedQuery.ts +0 -7
- package/src/subscribable.ts +22 -0
- package/src/types.ts +9 -15
- package/build/legacy/hydration-Bp57N3SP.d.ts.map +0 -1
- package/build/legacy/hydration-DRcloXEn.d.cts.map +0 -1
- package/build/legacy/removable-DeMjhW5M.d.cts +0 -13
- package/build/legacy/removable-DeMjhW5M.d.cts.map +0 -1
- package/build/legacy/removable-DeMjhW5M.d.ts +0 -13
- package/build/legacy/removable-DeMjhW5M.d.ts.map +0 -1
- package/build/legacy/subscribable-CbifVTKz.d.cts +0 -12
- package/build/legacy/subscribable-CbifVTKz.d.cts.map +0 -1
- package/build/legacy/subscribable-CbifVTKz.d.ts +0 -12
- package/build/legacy/subscribable-CbifVTKz.d.ts.map +0 -1
- package/build/modern/hydration-Bp57N3SP.d.ts.map +0 -1
- package/build/modern/hydration-DRcloXEn.d.cts.map +0 -1
- package/build/modern/removable-DeMjhW5M.d.cts +0 -13
- package/build/modern/removable-DeMjhW5M.d.cts.map +0 -1
- package/build/modern/removable-DeMjhW5M.d.ts +0 -13
- package/build/modern/removable-DeMjhW5M.d.ts.map +0 -1
- package/build/modern/subscribable-CbifVTKz.d.cts +0 -12
- package/build/modern/subscribable-CbifVTKz.d.cts.map +0 -1
- package/build/modern/subscribable-CbifVTKz.d.ts +0 -12
- package/build/modern/subscribable-CbifVTKz.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutation.js","names":["#client","#mutationCache","#observers","#retryer","#dispatch"],"sources":["../../src/mutation.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { Removable } from './removable'\nimport { createRetryer } from './retryer'\nimport type {\n DefaultError,\n MutationFunctionContext,\n MutationMeta,\n MutationOptions,\n MutationStatus,\n} from './types'\nimport type { MutationCache } from './mutationCache'\nimport type { MutationObserver } from './mutationObserver'\nimport type { Retryer } from './retryer'\nimport type { QueryClient } from './queryClient'\n\n// TYPES\n\ninterface MutationConfig<TData, TError, TVariables, TOnMutateResult> {\n client: QueryClient\n mutationId: number\n mutationCache: MutationCache\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>\n state?: MutationState<TData, TError, TVariables, TOnMutateResult>\n}\n\n/**\n * The raw state stored on a `Mutation` instance. This is the underlying state\n * that observer results (e.g. `MutationObserverResult`) are derived from.\n */\nexport interface MutationState<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> {\n /**\n * The value returned by `onMutate`, if defined. Passed to `onSuccess`,\n * `onError` and `onSettled` as the mutation's context.\n */\n context: TOnMutateResult | undefined\n /**\n * The last successfully resolved data for the mutation.\n */\n data: TData | undefined\n /**\n * The error object for the mutation, if the last attempt resulted in an error.\n * - Defaults to `null`.\n */\n error: TError | null\n /**\n * The number of times the mutation function has failed for the current attempt.\n */\n failureCount: number\n /**\n * The reason the current attempt failed, as reported by the retryer.\n */\n failureReason: TError | null\n /**\n * Whether the mutation is currently paused (see network mode), or is\n * waiting for another mutation with the same `scope` to finish.\n */\n isPaused: boolean\n /**\n * The status of the mutation.\n */\n status: MutationStatus\n /**\n * The variables the mutation was last called with.\n */\n variables: TVariables | undefined\n /**\n * The timestamp for when the mutation was submitted.\n */\n submittedAt: number\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError | null\n}\n\ninterface PendingAction<TVariables, TOnMutateResult> {\n type: 'pending'\n isPaused: boolean\n variables?: TVariables\n context?: TOnMutateResult\n}\n\ninterface SuccessAction<TData> {\n type: 'success'\n data: TData\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\nexport type Action<TData, TError, TVariables, TOnMutateResult> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | PendingAction<TVariables, TOnMutateResult>\n | PauseAction\n | SuccessAction<TData>\n\n// CLASS\n\n/**\n * Represents a single mutation attempt. A `Mutation` holds the mutation's\n * options, state (data/error/status), and the `MutationObserver`s currently\n * subscribed to it.\n *\n * Instances are created and managed internally by `MutationCache`; application\n * code typically interacts with mutations indirectly through `QueryClient` or\n * a framework hook like `useMutation`. Direct access to a `Mutation` instance\n * is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.\n *\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n * ```\n */\nexport class Mutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> extends Removable {\n state: MutationState<TData, TError, TVariables, TOnMutateResult>\n options!: MutationOptions<TData, TError, TVariables, TOnMutateResult>\n readonly mutationId: number\n\n #client: QueryClient\n #observers: Array<\n MutationObserver<TData, TError, TVariables, TOnMutateResult>\n >\n #mutationCache: MutationCache\n #retryer?: Retryer<TData>\n\n constructor(\n config: MutationConfig<TData, TError, TVariables, TOnMutateResult>,\n ) {\n super()\n\n this.#client = config.client\n this.mutationId = config.mutationId\n this.#mutationCache = config.mutationCache\n this.#observers = []\n this.state = config.state || getDefaultState()\n\n this.setOptions(config.options)\n this.scheduleGc()\n }\n\n /** @internal */\n setOptions(\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n ): void {\n this.options = options\n\n this.updateGcTime(this.options.gcTime)\n }\n\n /**\n * The `meta` object passed in the mutation's options, if any.\n */\n get meta(): MutationMeta | undefined {\n return this.options.meta\n }\n\n /** @internal */\n addObserver(observer: MutationObserver<any, any, any, any>): void {\n if (!this.#observers.includes(observer)) {\n this.#observers.push(observer)\n\n // Stop the mutation from being garbage collected\n this.clearGcTimeout()\n\n this.#mutationCache.notify({\n type: 'observerAdded',\n mutation: this,\n observer,\n })\n }\n }\n\n /** @internal */\n removeObserver(observer: MutationObserver<any, any, any, any>): void {\n this.#observers = this.#observers.filter((x) => x !== observer)\n\n this.scheduleGc()\n\n this.#mutationCache.notify({\n type: 'observerRemoved',\n mutation: this,\n observer,\n })\n }\n\n protected optionalRemove() {\n if (!this.#observers.length) {\n if (this.state.status === 'pending') {\n this.scheduleGc()\n } else {\n this.#mutationCache.remove(this)\n }\n }\n }\n\n /**\n * Resumes a mutation that is currently paused or was restored from a\n * dehydrated, still-`pending` state.\n *\n * - If this mutation has an active retryer (it paused mid-attempt, e.g. due\n * to the network mode or scope-based queuing), its retryer is resumed.\n * - Otherwise, if the mutation's status is still `pending` (e.g. it was\n * dehydrated while an attempt was in flight and never got a retryer in\n * this instance), `execute` is called again with the last known variables.\n * - Otherwise the mutation has already settled and this resolves immediately\n * without running anything again.\n *\n * @example\n * ```ts\n * // typically driven by reconnect handling, e.g. queryClient.resumePausedMutations()\n * const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n * await mutation?.continue()\n * ```\n *\n * @see {@link Mutation#execute}\n */\n continue(): Promise<unknown> {\n return (\n this.#retryer?.continue() ??\n // continuing a mutation assumes that variables are set, mutation must have been dehydrated before.\n // a settled mutation has no retryer to continue and must not run again\n (this.state.status === 'pending'\n ? this.execute(this.state.variables!)\n : Promise.resolve())\n )\n }\n\n /**\n * Runs the mutation function for the given variables through a retryer, and\n * drives the mutation's state and lifecycle callbacks through to settlement.\n *\n * If this mutation's state is already `pending` when `execute` is called\n * (i.e. it was restored, still in-flight, from a dehydrated state), the\n * `onMutate` step is skipped and a `continue` action is dispatched to\n * unpause it; otherwise a `pending` action is dispatched first, then the\n * mutation cache's `onMutate` and the mutation's own `onMutate` option are\n * awaited in that order, and the resulting context is stored.\n *\n * The mutation function is then run (subject to `retry`/`retryDelay`/\n * `networkMode`, and to the mutation cache's scope-based serialization).\n * On success, the cache's `onSuccess`/`onSettled` callbacks run before the\n * mutation's own `onSuccess`/`onSettled` options, a `success` action is\n * dispatched, and the resolved data is returned. On failure, the same\n * cache-then-option ordering is used for `onError`/`onSettled`, but each of\n * those four callbacks is individually caught so that a throwing callback\n * cannot mask the original error; an `error` action is then dispatched and\n * the original error is re-thrown.\n *\n * @example\n * ```ts\n * // Called internally by `MutationObserver.mutate` and `Mutation.continue` —\n * // applications normally trigger mutations through those, not this method.\n * const data = await mutation.execute(variables)\n * ```\n *\n * @see {@link Mutation#continue}\n */\n async execute(variables: TVariables): Promise<TData> {\n const onContinue = () => {\n this.#dispatch({ type: 'continue' })\n }\n\n const mutationFnContext = {\n client: this.#client,\n meta: this.options.meta,\n mutationKey: this.options.mutationKey,\n } satisfies MutationFunctionContext\n\n const retryer = (this.#retryer = createRetryer({\n fn: () => {\n if (!this.options.mutationFn) {\n return Promise.reject(new Error('No mutationFn found'))\n }\n\n return this.options.mutationFn(variables, mutationFnContext)\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue,\n retry: this.options.retry ?? 0,\n retryDelay: this.options.retryDelay,\n networkMode: this.options.networkMode,\n canRun: () => this.#mutationCache.canRun(this),\n }))\n\n const restored = this.state.status === 'pending'\n const isPaused = !retryer.canStart()\n\n try {\n if (restored) {\n // Dispatch continue action to unpause restored mutation\n onContinue()\n } else {\n this.#dispatch({ type: 'pending', variables, isPaused })\n // Notify cache callback\n if (this.#mutationCache.config.onMutate) {\n await this.#mutationCache.config.onMutate(\n variables,\n this as Mutation<unknown, unknown, unknown, unknown>,\n mutationFnContext,\n )\n }\n const context = await this.options.onMutate?.(\n variables,\n mutationFnContext,\n )\n if (context !== this.state.context) {\n this.#dispatch({\n type: 'pending',\n context,\n variables,\n isPaused,\n })\n }\n }\n const data = await retryer.start()\n\n // Notify cache callback\n await this.#mutationCache.config.onSuccess?.(\n data,\n variables,\n this.state.context,\n this as Mutation<unknown, unknown, unknown, unknown>,\n mutationFnContext,\n )\n\n await this.options.onSuccess?.(\n data,\n variables,\n this.state.context!,\n mutationFnContext,\n )\n\n // Notify cache callback\n await this.#mutationCache.config.onSettled?.(\n data,\n null,\n this.state.variables,\n this.state.context,\n this as Mutation<unknown, unknown, unknown, unknown>,\n mutationFnContext,\n )\n\n await this.options.onSettled?.(\n data,\n null,\n variables,\n this.state.context,\n mutationFnContext,\n )\n\n this.#dispatch({ type: 'success', data })\n return data\n } catch (error) {\n try {\n // Notify cache callback\n await this.#mutationCache.config.onError?.(\n error as any,\n variables,\n this.state.context,\n this as Mutation<unknown, unknown, unknown, unknown>,\n mutationFnContext,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n\n try {\n await this.options.onError?.(\n error as TError,\n variables,\n this.state.context,\n mutationFnContext,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n\n try {\n // Notify cache callback\n await this.#mutationCache.config.onSettled?.(\n undefined,\n error as any,\n this.state.variables,\n this.state.context,\n this as Mutation<unknown, unknown, unknown, unknown>,\n mutationFnContext,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n\n try {\n await this.options.onSettled?.(\n undefined,\n error as TError,\n variables,\n this.state.context,\n mutationFnContext,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n\n this.#dispatch({ type: 'error', error: error as TError })\n throw error\n } finally {\n // The settled retryer's promise would otherwise pin this mutation's\n // result, variables and context for as long as the cache keeps it\n if (this.#retryer === retryer) {\n this.#retryer = undefined\n }\n this.#mutationCache.runNext(this)\n }\n }\n\n #dispatch(action: Action<TData, TError, TVariables, TOnMutateResult>): void {\n const reducer = (\n state: MutationState<TData, TError, TVariables, TOnMutateResult>,\n ): MutationState<TData, TError, TVariables, TOnMutateResult> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n failureCount: action.failureCount,\n failureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n isPaused: true,\n }\n case 'continue':\n return {\n ...state,\n isPaused: false,\n }\n case 'pending':\n return {\n ...state,\n context: action.context,\n data: undefined,\n failureCount: 0,\n failureReason: null,\n error: null,\n isPaused: action.isPaused,\n status: 'pending',\n variables: action.variables,\n submittedAt: Date.now(),\n }\n case 'success':\n return {\n ...state,\n data: action.data,\n failureCount: 0,\n failureReason: null,\n error: null,\n status: 'success',\n isPaused: false,\n }\n case 'error':\n return {\n ...state,\n data: undefined,\n error: action.error,\n failureCount: state.failureCount + 1,\n failureReason: action.error,\n isPaused: false,\n status: 'error',\n }\n }\n }\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n this.#observers.forEach((observer) => {\n observer.onMutationUpdate(action)\n })\n this.#mutationCache.notify({\n mutation: this,\n type: 'updated',\n action,\n })\n })\n }\n}\n\nexport function getDefaultState<\n TData,\n TError,\n TVariables,\n TOnMutateResult,\n>(): MutationState<TData, TError, TVariables, TOnMutateResult> {\n return {\n context: undefined,\n data: undefined,\n error: null,\n failureCount: 0,\n failureReason: null,\n isPaused: false,\n status: 'idle',\n variables: undefined,\n submittedAt: 0,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsIA,IAAa,WAAb,cAKU,UAAU;CAKlB;CACA;CAGA;CACA;CAEA,YACE,QACA;EACA,MAAM;EAEN,KAAKA,UAAU,OAAO;EACtB,KAAK,aAAa,OAAO;EACzB,KAAKC,iBAAiB,OAAO;EAC7B,KAAKC,aAAa,CAAC;EACnB,KAAK,QAAQ,OAAO,SAAS,gBAAgB;EAE7C,KAAK,WAAW,OAAO,OAAO;EAC9B,KAAK,WAAW;CAClB;;CAGA,WACE,SACM;EACN,KAAK,UAAU;EAEf,KAAK,aAAa,KAAK,QAAQ,MAAM;CACvC;;;;CAKA,IAAI,OAAiC;EACnC,OAAO,KAAK,QAAQ;CACtB;;CAGA,YAAY,UAAsD;EAChE,IAAI,CAAC,KAAKA,WAAW,SAAS,QAAQ,GAAG;GACvC,KAAKA,WAAW,KAAK,QAAQ;GAG7B,KAAK,eAAe;GAEpB,KAAKD,eAAe,OAA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T,MAAM,KAAA;EACN,OAAO;EACP,cAAc;EACd,eAAe;EACf,UAAU;EACV,QAAQ;EACR,WAAW,KAAA;EACX,aAAa;CACf;AACF"}
|
|
1
|
+
{"version":3,"file":"mutation.js","names":[],"sources":["../../src/mutation.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { Removable } from './removable'\nimport { createRetryer } from './retryer'\nimport type {\n DefaultError,\n MutationFunctionContext,\n MutationMeta,\n MutationOptions,\n MutationStatus,\n} from './types'\nimport type { MutationCache } from './mutationCache'\nimport type { MutationObserver } from './mutationObserver'\nimport type { Retryer } from './retryer'\nimport type { QueryClient } from './queryClient'\n\n// TYPES\n\ninterface MutationConfig<TData, TError, TVariables, TOnMutateResult> {\n client: QueryClient\n mutationId: number\n mutationCache: MutationCache\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>\n state?: MutationState<TData, TError, TVariables, TOnMutateResult>\n}\n\n/**\n * The raw state stored on a `Mutation` instance. This is the underlying state\n * that observer results (e.g. `MutationObserverResult`) are derived from.\n */\nexport interface MutationState<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> {\n /**\n * The value returned by `onMutate`, if defined. Passed to `onSuccess`,\n * `onError` and `onSettled` as the mutation's context.\n */\n context: TOnMutateResult | undefined\n /**\n * The last successfully resolved data for the mutation.\n */\n data: TData | undefined\n /**\n * The error object for the mutation, if the last attempt resulted in an error.\n * - Defaults to `null`.\n */\n error: TError | null\n /**\n * The number of times the mutation function has failed for the current attempt.\n */\n failureCount: number\n /**\n * The reason the current attempt failed, as reported by the retryer.\n */\n failureReason: TError | null\n /**\n * Whether the mutation is currently paused (see network mode), or is\n * waiting for another mutation with the same `scope` to finish.\n */\n isPaused: boolean\n /**\n * The status of the mutation.\n */\n status: MutationStatus\n /**\n * The variables the mutation was last called with.\n */\n variables: TVariables | undefined\n /**\n * The timestamp for when the mutation was submitted.\n */\n submittedAt: number\n}\n\ninterface FailedAction<TError> {\n type: 'failed'\n failureCount: number\n error: TError | null\n}\n\ninterface PendingAction<TVariables, TOnMutateResult> {\n type: 'pending'\n isPaused: boolean\n variables?: TVariables\n context?: TOnMutateResult\n}\n\ninterface SuccessAction<TData> {\n type: 'success'\n data: TData\n}\n\ninterface ErrorAction<TError> {\n type: 'error'\n error: TError\n}\n\ninterface PauseAction {\n type: 'pause'\n}\n\ninterface ContinueAction {\n type: 'continue'\n}\n\nexport type Action<TData, TError, TVariables, TOnMutateResult> =\n | ContinueAction\n | ErrorAction<TError>\n | FailedAction<TError>\n | PendingAction<TVariables, TOnMutateResult>\n | PauseAction\n | SuccessAction<TData>\n\n// CLASS\n\n/**\n * Represents a single mutation attempt. A `Mutation` holds the mutation's\n * options, state (data/error/status), and the `MutationObserver`s currently\n * subscribed to it.\n *\n * Instances are created and managed internally by `MutationCache`; application\n * code typically interacts with mutations indirectly through `QueryClient` or\n * a framework hook like `useMutation`. Direct access to a `Mutation` instance\n * is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.\n *\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n * ```\n */\nexport class Mutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = unknown,\n TOnMutateResult = unknown,\n> extends Removable {\n state: MutationState<TData, TError, TVariables, TOnMutateResult>\n options!: MutationOptions<TData, TError, TVariables, TOnMutateResult>\n readonly mutationId: number\n\n #client: QueryClient\n #observers: Array<\n MutationObserver<TData, TError, TVariables, TOnMutateResult>\n >\n #mutationCache: MutationCache\n #retryer?: Retryer<TData>\n\n constructor(\n config: MutationConfig<TData, TError, TVariables, TOnMutateResult>,\n ) {\n super()\n\n this.#client = config.client\n this.mutationId = config.mutationId\n this.#mutationCache = config.mutationCache\n this.#observers = []\n this.state = config.state || getDefaultState()\n\n this.setOptions(config.options)\n this.scheduleGc()\n }\n\n /** @internal */\n setOptions(\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n ): void {\n this.options = options\n\n this.updateGcTime(this.options.gcTime)\n }\n\n /**\n * The `meta` object passed in the mutation's options, if any.\n */\n get meta(): MutationMeta | undefined {\n return this.options.meta\n }\n\n /** @internal */\n addObserver(observer: MutationObserver<any, any, any, any>): void {\n if (!this.#observers.includes(observer)) {\n this.#observers.push(observer)\n\n // Stop the mutation from being garbage collected\n this.clearGcTimeout()\n\n this.#mutationCache.notify({\n type: 'observerAdded',\n mutation: this,\n observer,\n })\n }\n }\n\n /** @internal */\n removeObserver(observer: MutationObserver<any, any, any, any>): void {\n this.#observers = this.#observers.filter((x) => x !== observer)\n\n this.scheduleGc()\n\n this.#mutationCache.notify({\n type: 'observerRemoved',\n mutation: this,\n observer,\n })\n }\n\n protected optionalRemove() {\n if (!this.#observers.length) {\n if (this.state.status === 'pending') {\n this.scheduleGc()\n } else {\n this.#mutationCache.remove(this)\n }\n }\n }\n\n /**\n * Resumes a mutation that is currently paused or was restored from a\n * dehydrated, still-`pending` state.\n *\n * - If this mutation has an active retryer (it paused mid-attempt, e.g. due\n * to the network mode or scope-based queuing), its retryer is resumed.\n * - Otherwise, if the mutation's status is still `pending` (e.g. it was\n * dehydrated while an attempt was in flight and never got a retryer in\n * this instance), `execute` is called again with the last known variables.\n * - Otherwise the mutation has already settled and this resolves immediately\n * without running anything again.\n *\n * @example\n * ```ts\n * // typically driven by reconnect handling, e.g. queryClient.resumePausedMutations()\n * const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n * await mutation?.continue()\n * ```\n *\n * @see {@link Mutation#execute}\n */\n continue(): Promise<unknown> {\n return (\n this.#retryer?.continue() ??\n // continuing a mutation assumes that variables are set, mutation must have been dehydrated before.\n // a settled mutation has no retryer to continue and must not run again\n (this.state.status === 'pending'\n ? this.execute(this.state.variables!)\n : Promise.resolve())\n )\n }\n\n /**\n * Runs the mutation function for the given variables through a retryer, and\n * drives the mutation's state and lifecycle callbacks through to settlement.\n *\n * If this mutation's state is already `pending` when `execute` is called\n * (i.e. it was restored, still in-flight, from a dehydrated state), the\n * `onMutate` step is skipped and a `continue` action is dispatched to\n * unpause it; otherwise a `pending` action is dispatched first, then the\n * mutation cache's `onMutate` and the mutation's own `onMutate` option are\n * awaited in that order, and the resulting context is stored.\n *\n * The mutation function is then run (subject to `retry`/`retryDelay`/\n * `networkMode`, and to the mutation cache's scope-based serialization).\n * On success, the cache's `onSuccess`/`onSettled` callbacks run before the\n * mutation's own `onSuccess`/`onSettled` options, a `success` action is\n * dispatched, and the resolved data is returned. On failure, the same\n * cache-then-option ordering is used for `onError`/`onSettled`, but each of\n * those four callbacks is individually caught so that a throwing callback\n * cannot mask the original error; an `error` action is then dispatched and\n * the original error is re-thrown.\n *\n * @example\n * ```ts\n * // Called internally by `MutationObserver.mutate` and `Mutation.continue` —\n * // applications normally trigger mutations through those, not this method.\n * const data = await mutation.execute(variables)\n * ```\n *\n * @see {@link Mutation#continue}\n */\n async execute(variables: TVariables): Promise<TData> {\n const onContinue = () => {\n this.#dispatch({ type: 'continue' })\n }\n\n const mutationFnContext = {\n client: this.#client,\n meta: this.options.meta,\n mutationKey: this.options.mutationKey,\n } satisfies MutationFunctionContext\n\n const retryer = (this.#retryer = createRetryer({\n fn: () => {\n if (!this.options.mutationFn) {\n return Promise.reject(new Error('No mutationFn found'))\n }\n\n return this.options.mutationFn(variables, mutationFnContext)\n },\n onFail: (failureCount, error) => {\n this.#dispatch({ type: 'failed', failureCount, error })\n },\n onPause: () => {\n this.#dispatch({ type: 'pause' })\n },\n onContinue,\n retry: this.options.retry ?? 0,\n retryDelay: this.options.retryDelay,\n networkMode: this.options.networkMode,\n canRun: () => this.#mutationCache.canRun(this),\n }))\n\n const restored = this.state.status === 'pending'\n const isPaused = !retryer.canStart()\n\n try {\n if (restored) {\n // Dispatch continue action to unpause restored mutation\n onContinue()\n } else {\n this.#dispatch({ type: 'pending', variables, isPaused })\n // Notify cache callback\n if (this.#mutationCache.config.onMutate) {\n await this.#mutationCache.config.onMutate(\n variables,\n this as Mutation<unknown, unknown, unknown, unknown>,\n mutationFnContext,\n )\n }\n const context = await this.options.onMutate?.(\n variables,\n mutationFnContext,\n )\n if (context !== this.state.context) {\n this.#dispatch({\n type: 'pending',\n context,\n variables,\n isPaused,\n })\n }\n }\n const data = await retryer.start()\n\n // Notify cache callback\n await this.#mutationCache.config.onSuccess?.(\n data,\n variables,\n this.state.context,\n this as Mutation<unknown, unknown, unknown, unknown>,\n mutationFnContext,\n )\n\n await this.options.onSuccess?.(\n data,\n variables,\n this.state.context!,\n mutationFnContext,\n )\n\n // Notify cache callback\n await this.#mutationCache.config.onSettled?.(\n data,\n null,\n this.state.variables,\n this.state.context,\n this as Mutation<unknown, unknown, unknown, unknown>,\n mutationFnContext,\n )\n\n await this.options.onSettled?.(\n data,\n null,\n variables,\n this.state.context,\n mutationFnContext,\n )\n\n this.#dispatch({ type: 'success', data })\n return data\n } catch (error) {\n try {\n // Notify cache callback\n await this.#mutationCache.config.onError?.(\n error as any,\n variables,\n this.state.context,\n this as Mutation<unknown, unknown, unknown, unknown>,\n mutationFnContext,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n\n try {\n await this.options.onError?.(\n error as TError,\n variables,\n this.state.context,\n mutationFnContext,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n\n try {\n // Notify cache callback\n await this.#mutationCache.config.onSettled?.(\n undefined,\n error as any,\n this.state.variables,\n this.state.context,\n this as Mutation<unknown, unknown, unknown, unknown>,\n mutationFnContext,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n\n try {\n await this.options.onSettled?.(\n undefined,\n error as TError,\n variables,\n this.state.context,\n mutationFnContext,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n\n this.#dispatch({ type: 'error', error: error as TError })\n throw error\n } finally {\n // The settled retryer's promise would otherwise pin this mutation's\n // result, variables and context for as long as the cache keeps it\n if (this.#retryer === retryer) {\n this.#retryer = undefined\n }\n this.#mutationCache.runNext(this)\n }\n }\n\n #dispatch(action: Action<TData, TError, TVariables, TOnMutateResult>): void {\n const reducer = (\n state: MutationState<TData, TError, TVariables, TOnMutateResult>,\n ): MutationState<TData, TError, TVariables, TOnMutateResult> => {\n switch (action.type) {\n case 'failed':\n return {\n ...state,\n failureCount: action.failureCount,\n failureReason: action.error,\n }\n case 'pause':\n return {\n ...state,\n isPaused: true,\n }\n case 'continue':\n return {\n ...state,\n isPaused: false,\n }\n case 'pending':\n return {\n ...state,\n context: action.context,\n data: undefined,\n failureCount: 0,\n failureReason: null,\n error: null,\n isPaused: action.isPaused,\n status: 'pending',\n variables: action.variables,\n submittedAt: Date.now(),\n }\n case 'success':\n return {\n ...state,\n data: action.data,\n failureCount: 0,\n failureReason: null,\n error: null,\n status: 'success',\n isPaused: false,\n }\n case 'error':\n return {\n ...state,\n data: undefined,\n error: action.error,\n failureCount: state.failureCount + 1,\n failureReason: action.error,\n isPaused: false,\n status: 'error',\n }\n }\n }\n this.state = reducer(this.state)\n\n notifyManager.batch(() => {\n this.#observers.forEach((observer) => {\n observer.onMutationUpdate(action)\n })\n this.#mutationCache.notify({\n mutation: this,\n type: 'updated',\n action,\n })\n })\n }\n}\n\nexport function getDefaultState<\n TData,\n TError,\n TVariables,\n TOnMutateResult,\n>(): MutationState<TData, TError, TVariables, TOnMutateResult> {\n return {\n context: undefined,\n data: undefined,\n error: null,\n failureCount: 0,\n failureReason: null,\n isPaused: false,\n status: 'idle',\n variables: undefined,\n submittedAt: 0,\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAsIA,IAAa,WAAb,cAKU,UAAU;CAKlB;CACA;CAGA;CACA;CAEA,YACE,QACA;EACA,MAAM;EAEN,KAAK,UAAU,OAAO;EACtB,KAAK,aAAa,OAAO;EACzB,KAAK,iBAAiB,OAAO;EAC7B,KAAK,aAAa,CAAC;EACnB,KAAK,QAAQ,OAAO,SAAS,gBAAgB;EAE7C,KAAK,WAAW,OAAO,OAAO;EAC9B,KAAK,WAAW;CAClB;;CAGA,WACE,SACM;EACN,KAAK,UAAU;EAEf,KAA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AAK,WAAW,SAAS,aAAa;IACpC,SAAS,iBAAiB,MAAM;GAClC,CAAC;GACD,KAAK,eAAe,OAAO;IACzB,UAAU;IACV,MAAM;IACN;GACF,CAAC;EACH,CAAC;CACH;AACF;AAEA,SAAgB,kBAK+C;CAC7D,OAAO;EACL,SAAS,KAAA;EACT,MAAM,KAAA;EACN,OAAO;EACP,cAAc;EACd,eAAe;EACf,UAAU;EACV,QAAQ;EACR,WAAW,KAAA;EACX,aAAa;CACf;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutationCache.cjs","names":["Subscribable","#mutations","#scopes","#mutationId","Mutation","matchMutation","notifyManager","noop"],"sources":["../../src/mutationCache.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { Mutation } from './mutation'\nimport { matchMutation, noop } from './utils'\nimport { Subscribable } from './subscribable'\nimport type { MutationObserver } from './mutationObserver'\nimport type {\n DefaultError,\n MutationFunctionContext,\n MutationOptions,\n NotifyEvent,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Action, MutationState } from './mutation'\nimport type { MutationFilters } from './utils'\n\n// TYPES\n\n/**\n * Global callbacks that fire for every mutation handled by a `MutationCache`, regardless of which\n * component or observer triggered it. They differ from the `defaultOptions` provided to a\n * `QueryClient` in two ways: `defaultOptions` can be overridden by each mutation, while these\n * callbacks are always called, and `onMutate` here does not allow returning a result.\n *\n * If a callback returns a promise, it will be awaited before the mutation continues.\n */\nexport interface MutationCacheConfig {\n /** Called when any mutation in the cache encounters an error. */\n onError?: (\n error: DefaultError,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is successful. */\n onSuccess?: (\n data: unknown,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called before any mutation in the cache executes. */\n onMutate?: (\n variables: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is settled, either successfully or with an error. */\n onSettled?: (\n data: unknown | undefined,\n error: DefaultError | null,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n}\n\ninterface NotifyEventMutationAdded extends NotifyEvent {\n type: 'added'\n mutation: Mutation<any, any, any, any>\n}\ninterface NotifyEventMutationRemoved extends NotifyEvent {\n type: 'removed'\n mutation: Mutation<any, any, any, any>\n}\n\ninterface NotifyEventMutationObserverAdded extends NotifyEvent {\n type: 'observerAdded'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverRemoved extends NotifyEvent {\n type: 'observerRemoved'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent {\n type: 'observerOptionsUpdated'\n mutation?: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any, any>\n}\n\ninterface NotifyEventMutationUpdated extends NotifyEvent {\n type: 'updated'\n mutation: Mutation<any, any, any, any>\n action: Action<any, any, any, any>\n}\n\n/**\n * The event passed to a `MutationCache` subscriber. Fired whenever a mutation is added or removed\n * from the cache, its state is updated, or one of its observers is added, removed, or has its\n * options updated.\n */\nexport type MutationCacheNotifyEvent =\n | NotifyEventMutationAdded\n | NotifyEventMutationRemoved\n | NotifyEventMutationObserverAdded\n | NotifyEventMutationObserverRemoved\n | NotifyEventMutationObserverOptionsUpdated\n | NotifyEventMutationUpdated\n\ntype MutationCacheListener = (event: MutationCacheNotifyEvent) => void\n\n// CLASS\n\n/**\n * The `MutationCache` is the storage for mutations.\n *\n * Normally, you will not interact with the `MutationCache` directly and instead use a\n * `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of\n * safe/known updates to the cache, such as mutations being added, removed, or updated.\n *\n * @example\n * ```ts\n * const unsubscribe = mutationCache.subscribe((event) => {\n * console.log(event.type, event.mutation)\n * })\n * ```\n */\nexport class MutationCache extends Subscribable<MutationCacheListener> {\n #mutations: Set<Mutation<any, any, any, any>>\n #scopes: Map<string, Array<Mutation<any, any, any, any>>>\n #mutationId: number\n\n constructor(public config: MutationCacheConfig = {}) {\n super()\n this.#mutations = new Set()\n this.#scopes = new Map()\n this.#mutationId = 0\n }\n\n /** @internal */\n build<TData, TError, TVariables, TOnMutateResult>(\n client: QueryClient,\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n state?: MutationState<TData, TError, TVariables, TOnMutateResult>,\n ): Mutation<TData, TError, TVariables, TOnMutateResult> {\n const mutation = new Mutation({\n client,\n mutationCache: this,\n mutationId: ++this.#mutationId,\n options: client.defaultMutationOptions(options),\n state,\n })\n\n this.add(mutation)\n\n return mutation\n }\n\n /** @internal */\n add(mutation: Mutation<any, any, any, any>): void {\n this.#mutations.add(mutation)\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const scopedMutations = this.#scopes.get(scope)\n if (scopedMutations) {\n scopedMutations.push(mutation)\n } else {\n this.#scopes.set(scope, [mutation])\n }\n }\n this.notify({ type: 'added', mutation })\n }\n\n /** @internal */\n remove(mutation: Mutation<any, any, any, any>): void {\n if (this.#mutations.delete(mutation)) {\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const scopedMutations = this.#scopes.get(scope)\n if (scopedMutations) {\n if (scopedMutations.length > 1) {\n const index = scopedMutations.indexOf(mutation)\n if (index !== -1) {\n scopedMutations.splice(index, 1)\n }\n } else if (scopedMutations[0] === mutation) {\n this.#scopes.delete(scope)\n }\n }\n }\n }\n\n // Currently we notify the removal even if the mutation was already removed.\n // Consider making this an error or not notifying of the removal depending on the desired semantics.\n this.notify({ type: 'removed', mutation })\n }\n\n /** @internal */\n canRun(mutation: Mutation<any, any, any, any>): boolean {\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const mutationsWithSameScope = this.#scopes.get(scope)\n const firstPendingMutation = mutationsWithSameScope?.find(\n (m) => m.state.status === 'pending',\n )\n // we can run if there is no current pending mutation (start use-case)\n // or if WE are the first pending mutation (continue use-case)\n return !firstPendingMutation || firstPendingMutation === mutation\n } else {\n // For unscoped mutations there are never any pending mutations in front of the\n // current mutation\n return true\n }\n }\n\n /** @internal */\n runNext(mutation: Mutation<any, any, any, any>): Promise<unknown> {\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const foundMutation = this.#scopes\n .get(scope)\n ?.find((m) => m !== mutation && m.state.isPaused)\n\n return foundMutation?.continue() ?? Promise.resolve()\n } else {\n return Promise.resolve()\n }\n }\n\n /**\n * Removes all mutations from the cache.\n *\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * mutationCache.clear()\n * ```\n */\n clear(): void {\n notifyManager.batch(() => {\n this.#mutations.forEach((mutation) => {\n this.notify({ type: 'removed', mutation })\n })\n this.#mutations.clear()\n this.#scopes.clear()\n })\n }\n\n /**\n * Returns all mutations within the cache.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about a mutation in rare scenarios.\n *\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutations = mutationCache.getAll()\n * ```\n */\n getAll(): Array<Mutation> {\n return Array.from(this.#mutations)\n }\n\n /**\n * A slightly more advanced method that can be used to get an existing mutation instance from\n * the cache. If the mutation does not exist, `undefined` is returned.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about a mutation in rare scenarios.\n *\n * @see {@link MutationCache#findAll}\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n * ```\n */\n find<\n TData = unknown,\n TError = DefaultError,\n TVariables = any,\n TOnMutateResult = unknown,\n >(\n filters: MutationFilters,\n ): Mutation<TData, TError, TVariables, TOnMutateResult> | undefined {\n const defaultedFilters = { exact: true, ...filters }\n\n return this.getAll().find((mutation) =>\n matchMutation(defaultedFilters, mutation),\n ) as Mutation<TData, TError, TVariables, TOnMutateResult> | undefined\n }\n\n /**\n * An even more advanced method that can be used to get existing mutation instances from the\n * cache that match the given filters. If no mutations match, an empty array is returned.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about mutations in rare scenarios.\n *\n * @see {@link MutationCache#find}\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })\n * ```\n */\n findAll(filters: MutationFilters = {}): Array<Mutation> {\n return this.getAll().filter((mutation) => matchMutation(filters, mutation))\n }\n\n /** @internal */\n notify(event: MutationCacheNotifyEvent) {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(event)\n })\n })\n }\n\n /** @internal */\n resumePausedMutations(): Promise<unknown> {\n const pausedMutations = this.getAll().filter((x) => x.state.isPaused)\n\n return notifyManager.batch(() =>\n Promise.all(\n pausedMutations.map((mutation) => mutation.continue().catch(noop)),\n ),\n )\n }\n}\n\nfunction scopeFor(mutation: Mutation<any, any, any, any>) {\n return mutation.options.scope?.id\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA2HA,IAAa,gBAAb,cAAmCA,qBAAAA,aAAoC;CACrE;CACA;CACA;CAEA,YAAY,SAAqC,CAAC,GAAG;EACnD,MAAM;EADW,KAAA,SAAA;EAEjB,KAAKC,6BAAa,IAAI,IAAI;EAC1B,KAAKC,0BAAU,IAAI,IAAI;EACvB,KAAKC,cAAc;CACrB;;CAGA,MACE,QACA,SACA,OACsD;EACtD,MAAM,WAAW,IAAIC,iBAAAA,SAAS;GAC5B;GACA,eAAe;GACf,YAAY,EAAE,KAAKD;GACnB,SAAS,OAAO,uBAAuB,OAAO;GAC9C;EACF,CAAC;EAED,KAAK,IAAI,QAAQ;EAEjB,OAAO;CACT;;CAGA,IAAI,UAA8C;EAChD,KAAKF,WAAW,IAAI,QAAQ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CAYA,QAAc;EACZ,sBAAA,cAAc,YAAY;GACxB,KAAKD,WAAW,SAAS,aAAa;IACpC,KAAK,OAAO;KAAE,MAAM;KAAW;IAAS,CAAC;GAC3C,CAAC;GACD,KAAKA,WAAW,MAAM;GACtB,KAAKC,QAAQ,MAAM;EACrB,CAAC;CACH;;;;;;;;;;;;;;CAeA,SAA0B;EACxB,OAAO,MAAM,KAAK,KAAKD,UAAU;CACnC;;;;;;;;;;;;;;;;CAiBA,KAME,SACkE;EAClE,MAAM,mBAAmB;GAAE,OAAO;GAAM,GAAG;EAAQ;EAEnD,OAAO,KAAK,OAAO,CAAC,CAAC,MAAM,aACzBI,cAAAA,cAAc,kBAAkB,QAAQ,CAC1C;CACF;;;;;;;;;;;;;;;;CAiBA,QAAQ,UAA2B,CAAC,GAAoB;EACtD,OAAO,KAAK,OAAO,CAAC,CAAC,QAAQ,aAAaA,cAAAA,cAAc,SAAS,QAAQ,CAAC;CAC5E;;CAGA,OAAO,OAAiC;EACtC,sBAAA,cAAc,YAAY;GACxB,KAAK,UAAU,SAAS,aAAa;IACnC,SAAS,KAAK;GAChB,CAAC;EACH,CAAC;CACH;;CAGA,wBAA0C;EACxC,MAAM,kBAAkB,KAAK,OAAO,CAAC,CAAC,QAAQ,MAAM,EAAE,MAAM,QAAQ;EAEpE,OAAOC,sBAAAA,cAAc,YACnB,QAAQ,IACN,gBAAgB,KAAK,aAAa,SAAS,SAAS,CAAC,CAAC,MAAMC,cAAAA,IAAI,CAAC,CACnE,CACF;CACF;AACF;AAEA,SAAS,SAAS,UAAwC;CACxD,OAAO,SAAS,QAAQ,OAAO;AACjC"}
|
|
1
|
+
{"version":3,"file":"mutationCache.cjs","names":["Subscribable","Mutation","matchMutation","notifyManager","noop"],"sources":["../../src/mutationCache.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { Mutation } from './mutation'\nimport { matchMutation, noop } from './utils'\nimport { Subscribable } from './subscribable'\nimport type { MutationObserver } from './mutationObserver'\nimport type {\n DefaultError,\n MutationFunctionContext,\n MutationOptions,\n NotifyEvent,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Action, MutationState } from './mutation'\nimport type { MutationFilters } from './utils'\n\n// TYPES\n\n/**\n * Global callbacks that fire for every mutation handled by a `MutationCache`, regardless of which\n * component or observer triggered it. They differ from the `defaultOptions` provided to a\n * `QueryClient` in two ways: `defaultOptions` can be overridden by each mutation, while these\n * callbacks are always called, and `onMutate` here does not allow returning a result.\n *\n * If a callback returns a promise, it will be awaited before the mutation continues.\n */\nexport interface MutationCacheConfig {\n /** Called when any mutation in the cache encounters an error. */\n onError?: (\n error: DefaultError,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is successful. */\n onSuccess?: (\n data: unknown,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called before any mutation in the cache executes. */\n onMutate?: (\n variables: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is settled, either successfully or with an error. */\n onSettled?: (\n data: unknown | undefined,\n error: DefaultError | null,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n}\n\ninterface NotifyEventMutationAdded extends NotifyEvent {\n type: 'added'\n mutation: Mutation<any, any, any, any>\n}\ninterface NotifyEventMutationRemoved extends NotifyEvent {\n type: 'removed'\n mutation: Mutation<any, any, any, any>\n}\n\ninterface NotifyEventMutationObserverAdded extends NotifyEvent {\n type: 'observerAdded'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverRemoved extends NotifyEvent {\n type: 'observerRemoved'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent {\n type: 'observerOptionsUpdated'\n mutation?: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any, any>\n}\n\ninterface NotifyEventMutationUpdated extends NotifyEvent {\n type: 'updated'\n mutation: Mutation<any, any, any, any>\n action: Action<any, any, any, any>\n}\n\n/**\n * The event passed to a `MutationCache` subscriber. Fired whenever a mutation is added or removed\n * from the cache, its state is updated, or one of its observers is added, removed, or has its\n * options updated.\n */\nexport type MutationCacheNotifyEvent =\n | NotifyEventMutationAdded\n | NotifyEventMutationRemoved\n | NotifyEventMutationObserverAdded\n | NotifyEventMutationObserverRemoved\n | NotifyEventMutationObserverOptionsUpdated\n | NotifyEventMutationUpdated\n\ntype MutationCacheListener = (event: MutationCacheNotifyEvent) => void\n\n// CLASS\n\n/**\n * The `MutationCache` is the storage for mutations.\n *\n * Normally, you will not interact with the `MutationCache` directly and instead use a\n * `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of\n * safe/known updates to the cache, such as mutations being added, removed, or updated.\n *\n * @example\n * ```ts\n * const unsubscribe = mutationCache.subscribe((event) => {\n * console.log(event.type, event.mutation)\n * })\n * ```\n */\nexport class MutationCache extends Subscribable<MutationCacheListener> {\n #mutations: Set<Mutation<any, any, any, any>>\n #scopes: Map<string, Array<Mutation<any, any, any, any>>>\n #mutationId: number\n\n constructor(public config: MutationCacheConfig = {}) {\n super()\n this.#mutations = new Set()\n this.#scopes = new Map()\n this.#mutationId = 0\n }\n\n /** @internal */\n build<TData, TError, TVariables, TOnMutateResult>(\n client: QueryClient,\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n state?: MutationState<TData, TError, TVariables, TOnMutateResult>,\n ): Mutation<TData, TError, TVariables, TOnMutateResult> {\n const mutation = new Mutation({\n client,\n mutationCache: this,\n mutationId: ++this.#mutationId,\n options: client.defaultMutationOptions(options),\n state,\n })\n\n this.add(mutation)\n\n return mutation\n }\n\n /** @internal */\n add(mutation: Mutation<any, any, any, any>): void {\n this.#mutations.add(mutation)\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const scopedMutations = this.#scopes.get(scope)\n if (scopedMutations) {\n scopedMutations.push(mutation)\n } else {\n this.#scopes.set(scope, [mutation])\n }\n }\n this.notify({ type: 'added', mutation })\n }\n\n /** @internal */\n remove(mutation: Mutation<any, any, any, any>): void {\n if (this.#mutations.delete(mutation)) {\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const scopedMutations = this.#scopes.get(scope)\n if (scopedMutations) {\n if (scopedMutations.length > 1) {\n const index = scopedMutations.indexOf(mutation)\n if (index !== -1) {\n scopedMutations.splice(index, 1)\n }\n } else if (scopedMutations[0] === mutation) {\n this.#scopes.delete(scope)\n }\n }\n }\n }\n\n // Currently we notify the removal even if the mutation was already removed.\n // Consider making this an error or not notifying of the removal depending on the desired semantics.\n this.notify({ type: 'removed', mutation })\n }\n\n /** @internal */\n canRun(mutation: Mutation<any, any, any, any>): boolean {\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const mutationsWithSameScope = this.#scopes.get(scope)\n const firstPendingMutation = mutationsWithSameScope?.find(\n (m) => m.state.status === 'pending',\n )\n // we can run if there is no current pending mutation (start use-case)\n // or if WE are the first pending mutation (continue use-case)\n return !firstPendingMutation || firstPendingMutation === mutation\n } else {\n // For unscoped mutations there are never any pending mutations in front of the\n // current mutation\n return true\n }\n }\n\n /** @internal */\n runNext(mutation: Mutation<any, any, any, any>): Promise<unknown> {\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const foundMutation = this.#scopes\n .get(scope)\n ?.find((m) => m !== mutation && m.state.isPaused)\n\n return foundMutation?.continue() ?? Promise.resolve()\n } else {\n return Promise.resolve()\n }\n }\n\n /**\n * Removes all mutations from the cache.\n *\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * mutationCache.clear()\n * ```\n */\n clear(): void {\n notifyManager.batch(() => {\n this.#mutations.forEach((mutation) => {\n this.notify({ type: 'removed', mutation })\n })\n this.#mutations.clear()\n this.#scopes.clear()\n })\n }\n\n /**\n * Returns all mutations within the cache.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about a mutation in rare scenarios.\n *\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutations = mutationCache.getAll()\n * ```\n */\n getAll(): Array<Mutation> {\n return Array.from(this.#mutations)\n }\n\n /**\n * A slightly more advanced method that can be used to get an existing mutation instance from\n * the cache. If the mutation does not exist, `undefined` is returned.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about a mutation in rare scenarios.\n *\n * @see {@link MutationCache#findAll}\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n * ```\n */\n find<\n TData = unknown,\n TError = DefaultError,\n TVariables = any,\n TOnMutateResult = unknown,\n >(\n filters: MutationFilters,\n ): Mutation<TData, TError, TVariables, TOnMutateResult> | undefined {\n const defaultedFilters = { exact: true, ...filters }\n\n return this.getAll().find((mutation) =>\n matchMutation(defaultedFilters, mutation),\n ) as Mutation<TData, TError, TVariables, TOnMutateResult> | undefined\n }\n\n /**\n * An even more advanced method that can be used to get existing mutation instances from the\n * cache that match the given filters. If no mutations match, an empty array is returned.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about mutations in rare scenarios.\n *\n * @see {@link MutationCache#find}\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })\n * ```\n */\n findAll(filters: MutationFilters = {}): Array<Mutation> {\n return this.getAll().filter((mutation) => matchMutation(filters, mutation))\n }\n\n /** @internal */\n notify(event: MutationCacheNotifyEvent) {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(event)\n })\n })\n }\n\n /** @internal */\n resumePausedMutations(): Promise<unknown> {\n const pausedMutations = this.getAll().filter((x) => x.state.isPaused)\n\n return notifyManager.batch(() =>\n Promise.all(\n pausedMutations.map((mutation) => mutation.continue().catch(noop)),\n ),\n )\n }\n}\n\nfunction scopeFor(mutation: Mutation<any, any, any, any>) {\n return mutation.options.scope?.id\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA2HA,IAAa,gBAAb,cAAmCA,qBAAAA,aAAoC;CACrE;CACA;CACA;CAEA,YAAY,SAAqC,CAAC,GAAG;EACnD,MAAM;EADW,KAAA,SAAA;EAEjB,KAAK,6BAAa,IAAI,IAAI;EAC1B,KAAK,0BAAU,IAAI,IAAI;EACvB,KAAK,cAAc;CACrB;;CAGA,MACE,QACA,SACA,OACsD;EACtD,MAAM,WAAW,IAAIC,iBAAAA,SAAS;GAC5B;GACA,eAAe;GACf,YAAY,EAAE,KAAK;GACnB,SAAS,OAAO,uBAAuB,OAAO;GAC9C;EACF,CAAC;EAED,KAAK,IAAI,QAAQ;EAEjB,OAAO;CACT;;CAGA,IAAI,UAA8C;EAChD,KAAK,WAAW,IAAI,QAAQ;EAC5B,MAAM,QAAQ,SAAS,QAAQ;EAC/B,IAAI,OAAO,UAAU,UAAU;GAC7B,MAAM,kBAAkB,KAAK,QAAQ,IAAI,KAAK;GAC9C,IAAI,iBACF,gBAAgB,KAAK,QAAQ;QAE7B,KAAK,QAAQ,IAAI,OAAO,CAAC,QAAQ,CAAC;EAEtC;EACA,KAAK,OAAO;GAAE,MAAM;GAAS;EAAS,CAAC;CACzC;;CAGA,OAAO,UAA8C;EACnD,IAAI,KAAK,WAAW,OAAO,QAAQ,GAAG;GACpC,MAAM,QAAQ,SAAS,QAAQ;GAC/B,IAAI,OAAO,UAAU,UAAU;IAC7B,MAAM,kBAAkB,KAAK,QAAQ,IAAI,KAAK;IAC9C,IAAI,iBAAiB;KACnB,IAAI,gBAAgB,SAAS,GAAG;MAC9B,MAAM,QAAQ,gBAAgB,QAAQ,QAAQ;MAC9C,IAAI,UAAU,IACZ,gBAAgB,OAAO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E;;CAGA,OAAO,OAAiC;EACtC,sBAAA,cAAc,YAAY;GACxB,KAAK,UAAU,SAAS,aAAa;IACnC,SAAS,KAAK;GAChB,CAAC;EACH,CAAC;CACH;;CAGA,wBAA0C;EACxC,MAAM,kBAAkB,KAAK,OAAO,CAAC,CAAC,QAAQ,MAAM,EAAE,MAAM,QAAQ;EAEpE,OAAOC,sBAAAA,cAAc,YACnB,QAAQ,IACN,gBAAgB,KAAK,aAAa,SAAS,SAAS,CAAC,CAAC,MAAMC,cAAAA,IAAI,CAAC,CACnE,CACF;CACF;AACF;AAEA,SAAS,SAAS,UAAwC;CACxD,OAAO,SAAS,QAAQ,OAAO;AACjC"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Gn as MutationCacheConfig, Kn as MutationCacheNotifyEvent, Wn as MutationCache } from "./hydration-
|
|
1
|
+
import { Gn as MutationCacheConfig, Kn as MutationCacheNotifyEvent, Wn as MutationCache } from "./hydration-Br9VIGXa.cjs";
|
|
2
2
|
export { MutationCache, MutationCacheConfig, MutationCacheNotifyEvent };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { Gn as MutationCacheConfig, Kn as MutationCacheNotifyEvent, Wn as MutationCache } from "./hydration-
|
|
1
|
+
import { Gn as MutationCacheConfig, Kn as MutationCacheNotifyEvent, Wn as MutationCache } from "./hydration-B9t5w6NC.js";
|
|
2
2
|
export { MutationCache, MutationCacheConfig, MutationCacheNotifyEvent };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutationCache.js","names":["#mutations","#scopes","#mutationId"],"sources":["../../src/mutationCache.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { Mutation } from './mutation'\nimport { matchMutation, noop } from './utils'\nimport { Subscribable } from './subscribable'\nimport type { MutationObserver } from './mutationObserver'\nimport type {\n DefaultError,\n MutationFunctionContext,\n MutationOptions,\n NotifyEvent,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Action, MutationState } from './mutation'\nimport type { MutationFilters } from './utils'\n\n// TYPES\n\n/**\n * Global callbacks that fire for every mutation handled by a `MutationCache`, regardless of which\n * component or observer triggered it. They differ from the `defaultOptions` provided to a\n * `QueryClient` in two ways: `defaultOptions` can be overridden by each mutation, while these\n * callbacks are always called, and `onMutate` here does not allow returning a result.\n *\n * If a callback returns a promise, it will be awaited before the mutation continues.\n */\nexport interface MutationCacheConfig {\n /** Called when any mutation in the cache encounters an error. */\n onError?: (\n error: DefaultError,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is successful. */\n onSuccess?: (\n data: unknown,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called before any mutation in the cache executes. */\n onMutate?: (\n variables: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is settled, either successfully or with an error. */\n onSettled?: (\n data: unknown | undefined,\n error: DefaultError | null,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n}\n\ninterface NotifyEventMutationAdded extends NotifyEvent {\n type: 'added'\n mutation: Mutation<any, any, any, any>\n}\ninterface NotifyEventMutationRemoved extends NotifyEvent {\n type: 'removed'\n mutation: Mutation<any, any, any, any>\n}\n\ninterface NotifyEventMutationObserverAdded extends NotifyEvent {\n type: 'observerAdded'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverRemoved extends NotifyEvent {\n type: 'observerRemoved'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent {\n type: 'observerOptionsUpdated'\n mutation?: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any, any>\n}\n\ninterface NotifyEventMutationUpdated extends NotifyEvent {\n type: 'updated'\n mutation: Mutation<any, any, any, any>\n action: Action<any, any, any, any>\n}\n\n/**\n * The event passed to a `MutationCache` subscriber. Fired whenever a mutation is added or removed\n * from the cache, its state is updated, or one of its observers is added, removed, or has its\n * options updated.\n */\nexport type MutationCacheNotifyEvent =\n | NotifyEventMutationAdded\n | NotifyEventMutationRemoved\n | NotifyEventMutationObserverAdded\n | NotifyEventMutationObserverRemoved\n | NotifyEventMutationObserverOptionsUpdated\n | NotifyEventMutationUpdated\n\ntype MutationCacheListener = (event: MutationCacheNotifyEvent) => void\n\n// CLASS\n\n/**\n * The `MutationCache` is the storage for mutations.\n *\n * Normally, you will not interact with the `MutationCache` directly and instead use a\n * `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of\n * safe/known updates to the cache, such as mutations being added, removed, or updated.\n *\n * @example\n * ```ts\n * const unsubscribe = mutationCache.subscribe((event) => {\n * console.log(event.type, event.mutation)\n * })\n * ```\n */\nexport class MutationCache extends Subscribable<MutationCacheListener> {\n #mutations: Set<Mutation<any, any, any, any>>\n #scopes: Map<string, Array<Mutation<any, any, any, any>>>\n #mutationId: number\n\n constructor(public config: MutationCacheConfig = {}) {\n super()\n this.#mutations = new Set()\n this.#scopes = new Map()\n this.#mutationId = 0\n }\n\n /** @internal */\n build<TData, TError, TVariables, TOnMutateResult>(\n client: QueryClient,\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n state?: MutationState<TData, TError, TVariables, TOnMutateResult>,\n ): Mutation<TData, TError, TVariables, TOnMutateResult> {\n const mutation = new Mutation({\n client,\n mutationCache: this,\n mutationId: ++this.#mutationId,\n options: client.defaultMutationOptions(options),\n state,\n })\n\n this.add(mutation)\n\n return mutation\n }\n\n /** @internal */\n add(mutation: Mutation<any, any, any, any>): void {\n this.#mutations.add(mutation)\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const scopedMutations = this.#scopes.get(scope)\n if (scopedMutations) {\n scopedMutations.push(mutation)\n } else {\n this.#scopes.set(scope, [mutation])\n }\n }\n this.notify({ type: 'added', mutation })\n }\n\n /** @internal */\n remove(mutation: Mutation<any, any, any, any>): void {\n if (this.#mutations.delete(mutation)) {\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const scopedMutations = this.#scopes.get(scope)\n if (scopedMutations) {\n if (scopedMutations.length > 1) {\n const index = scopedMutations.indexOf(mutation)\n if (index !== -1) {\n scopedMutations.splice(index, 1)\n }\n } else if (scopedMutations[0] === mutation) {\n this.#scopes.delete(scope)\n }\n }\n }\n }\n\n // Currently we notify the removal even if the mutation was already removed.\n // Consider making this an error or not notifying of the removal depending on the desired semantics.\n this.notify({ type: 'removed', mutation })\n }\n\n /** @internal */\n canRun(mutation: Mutation<any, any, any, any>): boolean {\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const mutationsWithSameScope = this.#scopes.get(scope)\n const firstPendingMutation = mutationsWithSameScope?.find(\n (m) => m.state.status === 'pending',\n )\n // we can run if there is no current pending mutation (start use-case)\n // or if WE are the first pending mutation (continue use-case)\n return !firstPendingMutation || firstPendingMutation === mutation\n } else {\n // For unscoped mutations there are never any pending mutations in front of the\n // current mutation\n return true\n }\n }\n\n /** @internal */\n runNext(mutation: Mutation<any, any, any, any>): Promise<unknown> {\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const foundMutation = this.#scopes\n .get(scope)\n ?.find((m) => m !== mutation && m.state.isPaused)\n\n return foundMutation?.continue() ?? Promise.resolve()\n } else {\n return Promise.resolve()\n }\n }\n\n /**\n * Removes all mutations from the cache.\n *\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * mutationCache.clear()\n * ```\n */\n clear(): void {\n notifyManager.batch(() => {\n this.#mutations.forEach((mutation) => {\n this.notify({ type: 'removed', mutation })\n })\n this.#mutations.clear()\n this.#scopes.clear()\n })\n }\n\n /**\n * Returns all mutations within the cache.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about a mutation in rare scenarios.\n *\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutations = mutationCache.getAll()\n * ```\n */\n getAll(): Array<Mutation> {\n return Array.from(this.#mutations)\n }\n\n /**\n * A slightly more advanced method that can be used to get an existing mutation instance from\n * the cache. If the mutation does not exist, `undefined` is returned.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about a mutation in rare scenarios.\n *\n * @see {@link MutationCache#findAll}\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n * ```\n */\n find<\n TData = unknown,\n TError = DefaultError,\n TVariables = any,\n TOnMutateResult = unknown,\n >(\n filters: MutationFilters,\n ): Mutation<TData, TError, TVariables, TOnMutateResult> | undefined {\n const defaultedFilters = { exact: true, ...filters }\n\n return this.getAll().find((mutation) =>\n matchMutation(defaultedFilters, mutation),\n ) as Mutation<TData, TError, TVariables, TOnMutateResult> | undefined\n }\n\n /**\n * An even more advanced method that can be used to get existing mutation instances from the\n * cache that match the given filters. If no mutations match, an empty array is returned.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about mutations in rare scenarios.\n *\n * @see {@link MutationCache#find}\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })\n * ```\n */\n findAll(filters: MutationFilters = {}): Array<Mutation> {\n return this.getAll().filter((mutation) => matchMutation(filters, mutation))\n }\n\n /** @internal */\n notify(event: MutationCacheNotifyEvent) {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(event)\n })\n })\n }\n\n /** @internal */\n resumePausedMutations(): Promise<unknown> {\n const pausedMutations = this.getAll().filter((x) => x.state.isPaused)\n\n return notifyManager.batch(() =>\n Promise.all(\n pausedMutations.map((mutation) => mutation.continue().catch(noop)),\n ),\n )\n }\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wBAA0C;EACxC,MAAM,kBAAkB,KAAK,OAAO,CAAC,CAAC,QAAQ,MAAM,EAAE,MAAM,QAAQ;EAEpE,OAAO,cAAc,YACnB,QAAQ,IACN,gBAAgB,KAAK,aAAa,SAAS,SAAS,CAAC,CAAC,MAAM,IAAI,CAAC,CACnE,CACF;CACF;AACF;AAEA,SAAS,SAAS,UAAwC;CACxD,OAAO,SAAS,QAAQ,OAAO;AACjC"}
|
|
1
|
+
{"version":3,"file":"mutationCache.js","names":[],"sources":["../../src/mutationCache.ts"],"sourcesContent":["import { notifyManager } from './notifyManager'\nimport { Mutation } from './mutation'\nimport { matchMutation, noop } from './utils'\nimport { Subscribable } from './subscribable'\nimport type { MutationObserver } from './mutationObserver'\nimport type {\n DefaultError,\n MutationFunctionContext,\n MutationOptions,\n NotifyEvent,\n} from './types'\nimport type { QueryClient } from './queryClient'\nimport type { Action, MutationState } from './mutation'\nimport type { MutationFilters } from './utils'\n\n// TYPES\n\n/**\n * Global callbacks that fire for every mutation handled by a `MutationCache`, regardless of which\n * component or observer triggered it. They differ from the `defaultOptions` provided to a\n * `QueryClient` in two ways: `defaultOptions` can be overridden by each mutation, while these\n * callbacks are always called, and `onMutate` here does not allow returning a result.\n *\n * If a callback returns a promise, it will be awaited before the mutation continues.\n */\nexport interface MutationCacheConfig {\n /** Called when any mutation in the cache encounters an error. */\n onError?: (\n error: DefaultError,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is successful. */\n onSuccess?: (\n data: unknown,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called before any mutation in the cache executes. */\n onMutate?: (\n variables: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n /** Called when any mutation in the cache is settled, either successfully or with an error. */\n onSettled?: (\n data: unknown | undefined,\n error: DefaultError | null,\n variables: unknown,\n onMutateResult: unknown,\n mutation: Mutation<unknown, unknown, unknown>,\n context: MutationFunctionContext,\n ) => Promise<unknown> | unknown\n}\n\ninterface NotifyEventMutationAdded extends NotifyEvent {\n type: 'added'\n mutation: Mutation<any, any, any, any>\n}\ninterface NotifyEventMutationRemoved extends NotifyEvent {\n type: 'removed'\n mutation: Mutation<any, any, any, any>\n}\n\ninterface NotifyEventMutationObserverAdded extends NotifyEvent {\n type: 'observerAdded'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverRemoved extends NotifyEvent {\n type: 'observerRemoved'\n mutation: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any>\n}\n\ninterface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent {\n type: 'observerOptionsUpdated'\n mutation?: Mutation<any, any, any, any>\n observer: MutationObserver<any, any, any, any>\n}\n\ninterface NotifyEventMutationUpdated extends NotifyEvent {\n type: 'updated'\n mutation: Mutation<any, any, any, any>\n action: Action<any, any, any, any>\n}\n\n/**\n * The event passed to a `MutationCache` subscriber. Fired whenever a mutation is added or removed\n * from the cache, its state is updated, or one of its observers is added, removed, or has its\n * options updated.\n */\nexport type MutationCacheNotifyEvent =\n | NotifyEventMutationAdded\n | NotifyEventMutationRemoved\n | NotifyEventMutationObserverAdded\n | NotifyEventMutationObserverRemoved\n | NotifyEventMutationObserverOptionsUpdated\n | NotifyEventMutationUpdated\n\ntype MutationCacheListener = (event: MutationCacheNotifyEvent) => void\n\n// CLASS\n\n/**\n * The `MutationCache` is the storage for mutations.\n *\n * Normally, you will not interact with the `MutationCache` directly and instead use a\n * `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of\n * safe/known updates to the cache, such as mutations being added, removed, or updated.\n *\n * @example\n * ```ts\n * const unsubscribe = mutationCache.subscribe((event) => {\n * console.log(event.type, event.mutation)\n * })\n * ```\n */\nexport class MutationCache extends Subscribable<MutationCacheListener> {\n #mutations: Set<Mutation<any, any, any, any>>\n #scopes: Map<string, Array<Mutation<any, any, any, any>>>\n #mutationId: number\n\n constructor(public config: MutationCacheConfig = {}) {\n super()\n this.#mutations = new Set()\n this.#scopes = new Map()\n this.#mutationId = 0\n }\n\n /** @internal */\n build<TData, TError, TVariables, TOnMutateResult>(\n client: QueryClient,\n options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,\n state?: MutationState<TData, TError, TVariables, TOnMutateResult>,\n ): Mutation<TData, TError, TVariables, TOnMutateResult> {\n const mutation = new Mutation({\n client,\n mutationCache: this,\n mutationId: ++this.#mutationId,\n options: client.defaultMutationOptions(options),\n state,\n })\n\n this.add(mutation)\n\n return mutation\n }\n\n /** @internal */\n add(mutation: Mutation<any, any, any, any>): void {\n this.#mutations.add(mutation)\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const scopedMutations = this.#scopes.get(scope)\n if (scopedMutations) {\n scopedMutations.push(mutation)\n } else {\n this.#scopes.set(scope, [mutation])\n }\n }\n this.notify({ type: 'added', mutation })\n }\n\n /** @internal */\n remove(mutation: Mutation<any, any, any, any>): void {\n if (this.#mutations.delete(mutation)) {\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const scopedMutations = this.#scopes.get(scope)\n if (scopedMutations) {\n if (scopedMutations.length > 1) {\n const index = scopedMutations.indexOf(mutation)\n if (index !== -1) {\n scopedMutations.splice(index, 1)\n }\n } else if (scopedMutations[0] === mutation) {\n this.#scopes.delete(scope)\n }\n }\n }\n }\n\n // Currently we notify the removal even if the mutation was already removed.\n // Consider making this an error or not notifying of the removal depending on the desired semantics.\n this.notify({ type: 'removed', mutation })\n }\n\n /** @internal */\n canRun(mutation: Mutation<any, any, any, any>): boolean {\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const mutationsWithSameScope = this.#scopes.get(scope)\n const firstPendingMutation = mutationsWithSameScope?.find(\n (m) => m.state.status === 'pending',\n )\n // we can run if there is no current pending mutation (start use-case)\n // or if WE are the first pending mutation (continue use-case)\n return !firstPendingMutation || firstPendingMutation === mutation\n } else {\n // For unscoped mutations there are never any pending mutations in front of the\n // current mutation\n return true\n }\n }\n\n /** @internal */\n runNext(mutation: Mutation<any, any, any, any>): Promise<unknown> {\n const scope = scopeFor(mutation)\n if (typeof scope === 'string') {\n const foundMutation = this.#scopes\n .get(scope)\n ?.find((m) => m !== mutation && m.state.isPaused)\n\n return foundMutation?.continue() ?? Promise.resolve()\n } else {\n return Promise.resolve()\n }\n }\n\n /**\n * Removes all mutations from the cache.\n *\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * mutationCache.clear()\n * ```\n */\n clear(): void {\n notifyManager.batch(() => {\n this.#mutations.forEach((mutation) => {\n this.notify({ type: 'removed', mutation })\n })\n this.#mutations.clear()\n this.#scopes.clear()\n })\n }\n\n /**\n * Returns all mutations within the cache.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about a mutation in rare scenarios.\n *\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutations = mutationCache.getAll()\n * ```\n */\n getAll(): Array<Mutation> {\n return Array.from(this.#mutations)\n }\n\n /**\n * A slightly more advanced method that can be used to get an existing mutation instance from\n * the cache. If the mutation does not exist, `undefined` is returned.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about a mutation in rare scenarios.\n *\n * @see {@link MutationCache#findAll}\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutation = mutationCache.find({ mutationKey: ['addPost'] })\n * ```\n */\n find<\n TData = unknown,\n TError = DefaultError,\n TVariables = any,\n TOnMutateResult = unknown,\n >(\n filters: MutationFilters,\n ): Mutation<TData, TError, TVariables, TOnMutateResult> | undefined {\n const defaultedFilters = { exact: true, ...filters }\n\n return this.getAll().find((mutation) =>\n matchMutation(defaultedFilters, mutation),\n ) as Mutation<TData, TError, TVariables, TOnMutateResult> | undefined\n }\n\n /**\n * An even more advanced method that can be used to get existing mutation instances from the\n * cache that match the given filters. If no mutations match, an empty array is returned.\n *\n * This is not typically needed for most applications, but can come in handy when needing more\n * information about mutations in rare scenarios.\n *\n * @see {@link MutationCache#find}\n * @example\n * ```ts\n * const mutationCache = queryClient.getMutationCache()\n *\n * const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })\n * ```\n */\n findAll(filters: MutationFilters = {}): Array<Mutation> {\n return this.getAll().filter((mutation) => matchMutation(filters, mutation))\n }\n\n /** @internal */\n notify(event: MutationCacheNotifyEvent) {\n notifyManager.batch(() => {\n this.listeners.forEach((listener) => {\n listener(event)\n })\n })\n }\n\n /** @internal */\n resumePausedMutations(): Promise<unknown> {\n const pausedMutations = this.getAll().filter((x) => x.state.isPaused)\n\n return notifyManager.batch(() =>\n Promise.all(\n pausedMutations.map((mutation) => mutation.continue().catch(noop)),\n ),\n )\n }\n}\n\nfunction scopeFor(mutation: Mutation<any, any, any, any>) {\n return mutation.options.scope?.id\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2HA,IAAa,gBAAb,cAAmC,aAAoC;CACrE;CACA;CACA;CAEA,YAAY,SAAqC,CAAC,GAAG;EACnD,MAAM;EADW,KAAA,SAAA;EAEjB,KAAK,6BAAa,IAAI,IAAI;EAC1B,KAAK,0BAAU,IAAI,IAAI;EACvB,KAAK,cAAc;CACrB;;CAGA,MACE,QACA,SACA,OACsD;EACtD,MAAM,WAAW,IAAI,SAAS;GAC5B;GACA,eAAe;GACf,YAAY,EAAE,KAAK;GACnB,SAAS,OAAO,uBAAuB,OAAO;GAC9C;EACF,CAAC;EAED,KAAK,IAAI,QAAQ;EAEjB,OAAO;CACT;;CAGA,IAAI,UAA8C;EAChD,KAAK,WAAW,IAAI,QAAQ;EAC5B,MAAM,QAAQ,SAAS,QAAQ;EAC/B,IAAI,OAAO,UAAU,UAAU;GAC7B,MAAM,kBAAkB,KAAK,QAAQ,IAAI,KAAK;GAC9C,IAAI,iBACF,gBAA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ACtB,KAAK,QAAQ,MAAM;EACrB,CAAC;CACH;;;;;;;;;;;;;;CAeA,SAA0B;EACxB,OAAO,MAAM,KAAK,KAAK,UAAU;CACnC;;;;;;;;;;;;;;;;CAiBA,KAME,SACkE;EAClE,MAAM,mBAAmB;GAAE,OAAO;GAAM,GAAG;EAAQ;EAEnD,OAAO,KAAK,OAAO,CAAC,CAAC,MAAM,aACzB,cAAc,kBAAkB,QAAQ,CAC1C;CACF;;;;;;;;;;;;;;;;CAiBA,QAAQ,UAA2B,CAAC,GAAoB;EACtD,OAAO,KAAK,OAAO,CAAC,CAAC,QAAQ,aAAa,cAAc,SAAS,QAAQ,CAAC;CAC5E;;CAGA,OAAO,OAAiC;EACtC,cAAc,YAAY;GACxB,KAAK,UAAU,SAAS,aAAa;IACnC,SAAS,KAAK;GAChB,CAAC;EACH,CAAC;CACH;;CAGA,wBAA0C;EACxC,MAAM,kBAAkB,KAAK,OAAO,CAAC,CAAC,QAAQ,MAAM,EAAE,MAAM,QAAQ;EAEpE,OAAO,cAAc,YACnB,QAAQ,IACN,gBAAgB,KAAK,aAAa,SAAS,SAAS,CAAC,CAAC,MAAM,IAAI,CAAC,CACnE,CACF;CACF;AACF;AAEA,SAAS,SAAS,UAAwC;CACxD,OAAO,SAAS,QAAQ,OAAO;AACjC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutationObserver.cjs","names":["Subscribable","#client","#updateResult","shallowEqualObjects","#currentMutation","hashKey","#notify","#currentResult","#mutateOptions","getDefaultState"],"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 *\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 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 *\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 onSubscribe(): void {\n if (this.listeners.size === 1 && this.#currentMutation) {\n this.#currentMutation.addObserver(this)\n\n this.#updateResult()\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.hasListeners()) {\n this.#currentMutation?.removeObserver(this)\n }\n }\n\n /** @internal */\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 */\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 *\n * @example\n * ```ts\n * observer.reset()\n * ```\n *\n * @see {@link MutationObserver#mutate}\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 *\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 if (this.#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 this.#mutateOptions.onSuccess?.(\n action.data,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n try {\n this.#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 this.#mutateOptions.onError?.(\n action.error,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n try {\n this.#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":";;;;;;;;;;;;;;;;;;;;;AAqCA,IAAa,mBAAb,cAKUA,qBAAAA,aAER;CAGA;CACA,iBAKI,KAAA;CACJ;CACA;CAEA,YACE,QACA,SAMA;EACA,MAAM;EAEN,KAAKC,UAAU;EACf,KAAK,WAAW,OAAO;EACvB,KAAK,YAAY;EACjB,KAAKC,cAAc;CACrB;CAEA,cAA8B;EAC5B,KAAK,SAAS,KAAK,OAAO,KAAK,IAAI;EACnC,KAAK,QAAQ,KAAK,MAAM,KAAK,IAAI;CACnC;;;;;;;;;;;;;;;;;CAkBA,WACE,SAMA;EACA,MAAM,cAAc,KAAK;EAGzB,KAAK,UAAU,KAAKD,QAAQ,uBAAuB,OAAO;EAC1D,IAAI,CAACE,cAAAA,oBAAoB,KAAK,SAAS,WAAW,GAChD,KAAKF,QAAQ,iBAAiB,CAAC,CAAC,OAAO;GACrC,MAAM;GACN,UAAU,KAAKG;GACf,UAAU;EACZ,CAAC;EAGH,IACE,aAAa,eACb,KAAK,QAAQ,eACbC,cAAAA,QAAQ,YAAY,WAAW,MAAMA,cAAAA,QAAQ,KAAK,QAAQ,WAAW,GAErE,KAAK,MAAM;OACN,IAAI,KAAKD,kBAAkB,MAAM,WAAW,WACjD,KAAKA,iBAAiB,WAAW,KAAK,OAAO;CAEjD;CAEA,cAA8B;EAC5B,IAAI,KAAK,UAAU,SAAS,KAAK,KAAKA,kBAAkB;GACtD,KAAKA,iBAAiB,YAAY,IAAI;GAEtC,KAAKF,cAAc;EACrB;CACF;CAEA,gBAAgC;EAC9B,IAAI,CAAC,KAAK,aAAa,GACrB,KAAKE,kBAAkB,eAAe,IAAI;CAE9C;;CAGA,iBACE,QACM;EACN,KAAKF,cAAc;EAEnB,KAAKI,QAAQ,MAAM;CACrB;;;;;;CAOA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S,SAAS;KACnC,IAAI;MACF,KAAKA,eAAe,UAClB,OAAO,OACP,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;KACA,IAAI;MACF,KAAKA,eAAe,YAClB,KAAA,GACA,OAAO,OACP,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;IACF;GACF;GAGA,KAAK,UAAU,SAAS,aAAa;IACnC,SAAS,KAAKD,cAAc;GAC9B,CAAC;EACH,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"mutationObserver.cjs","names":["Subscribable","shallowEqualObjects","hashKey","getDefaultState"],"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 *\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 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 *\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 onSubscribe(): void {\n if (this.listeners.size === 1 && this.#currentMutation) {\n this.#currentMutation.addObserver(this)\n\n this.#updateResult()\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.hasListeners()) {\n this.#currentMutation?.removeObserver(this)\n }\n }\n\n /** @internal */\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 */\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 *\n * @example\n * ```ts\n * observer.reset()\n * ```\n *\n * @see {@link MutationObserver#mutate}\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 *\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 if (this.#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 this.#mutateOptions.onSuccess?.(\n action.data,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n try {\n this.#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 this.#mutateOptions.onError?.(\n action.error,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n try {\n this.#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":";;;;;;;;;;;;;;;;;;;;;AAqCA,IAAa,mBAAb,cAKUA,qBAAAA,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;CAEA,cAA8B;EAC5B,KAAK,SAAS,KAAK,OAAO,KAAK,IAAI;EACnC,KAAK,QAAQ,KAAK,MAAM,KAAK,IAAI;CACnC;;;;;;;;;;;;;;;;;CAkBA,WACE,SAMA;EACA,MAAM,cAAc,KAAK;EAGzB,KAAK,UAAU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WAAW;GAC5B,WAAW,MAAM,WAAW;GAC5B,SAAS,MAAM,WAAW;GAC1B,QAAQ,MAAM,WAAW;GACzB,QAAQ,KAAK;GACb,OAAO,KAAK;EACd;CACF;CAEA,QAAQ,QAAmE;EACzE,sBAAA,cAAc,YAAY;GAExB,IAAI,KAAK,kBAAkB,KAAK,aAAa,GAAG;IAC9C,MAAM,YAAY,KAAK,eAAe;IACtC,MAAM,iBAAiB,KAAK,eAAe;IAE3C,MAAM,UAAU;KACd,QAAQ,KAAK;KACb,MAAM,KAAK,QAAQ;KACnB,aAAa,KAAK,QAAQ;IAC5B;IAEA,IAAI,QAAQ,SAAS,WAAW;KAC9B,IAAI;MACF,KAAK,eAAe,YAClB,OAAO,MACP,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;KACA,IAAI;MACF,KAAK,eAAe,YAClB,OAAO,MACP,MACA,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;IACF,OAAO,IAAI,QAAQ,SAAS,SAAS;KACnC,IAAI;MACF,KAAK,eAAe,UAClB,OAAO,OACP,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;KACA,IAAI;MACF,KAAK,eAAe,YAClB,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,2 +1,2 @@
|
|
|
1
|
-
import { qn as MutationObserver } from "./hydration-
|
|
1
|
+
import { qn as MutationObserver } from "./hydration-Br9VIGXa.cjs";
|
|
2
2
|
export { MutationObserver };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { qn as MutationObserver } from "./hydration-
|
|
1
|
+
import { qn as MutationObserver } from "./hydration-B9t5w6NC.js";
|
|
2
2
|
export { MutationObserver };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutationObserver.js","names":["#client","#updateResult","#currentMutation","#notify","#currentResult","#mutateOptions"],"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 *\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 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 *\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 onSubscribe(): void {\n if (this.listeners.size === 1 && this.#currentMutation) {\n this.#currentMutation.addObserver(this)\n\n this.#updateResult()\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.hasListeners()) {\n this.#currentMutation?.removeObserver(this)\n }\n }\n\n /** @internal */\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 */\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 *\n * @example\n * ```ts\n * observer.reset()\n * ```\n *\n * @see {@link MutationObserver#mutate}\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 *\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 if (this.#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 this.#mutateOptions.onSuccess?.(\n action.data,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n try {\n this.#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 this.#mutateOptions.onError?.(\n action.error,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n try {\n this.#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":";;;;;;;;;;;;;;;;;;;;AAqCA,IAAa,mBAAb,cAKU,aAER;CAGA;CACA,iBAKI,KAAA;CACJ;CACA;CAEA,YACE,QACA,SAMA;EACA,MAAM;EAEN,KAAKA,UAAU;EACf,KAAK,WAAW,OAAO;EACvB,KAAK,YAAY;EACjB,KAAKC,cAAc;CACrB;CAEA,cAA8B;EAC5B,KAAK,SAAS,KAAK,OAAO,KAAK,IAAI;EACnC,KAAK,QAAQ,KAAK,MAAM,KAAK,IAAI;CACnC;;;;;;;;;;;;;;;;;CAkBA,WACE,SAMA;EACA,MAAM,cAAc,KAAK;EAGzB,KAAK,UAAU,KAAKD,QAAQ,uBAAuB,OAAO;EAC1D,IAAI,CAAC,oBAAoB,KAAK,SAAS,WAAW,GAChD,KAAKA,QAAQ,iBAAiB,CAAC,CAAC,OAAO;GACrC,MAAM;GACN,UAAU,KAAKE;GACf,UAAU;EACZ,CAAC;EAGH,IACE,aAAa,eACb,KAAK,QAAQ,eACb,QAAQ,YAAY,WAAW,MAAM,QAAQ,KAAK,QAAQ,WAAW,GAErE,KAAK,MAAM;OACN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UAAU;KACd,QAAQ,KAAKJ;KACb,MAAM,KAAK,QAAQ;KACnB,aAAa,KAAK,QAAQ;IAC5B;IAEA,IAAI,QAAQ,SAAS,WAAW;KAC9B,IAAI;MACF,KAAKK,eAAe,YAClB,OAAO,MACP,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;KACA,IAAI;MACF,KAAKA,eAAe,YAClB,OAAO,MACP,MACA,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;IACF,OAAO,IAAI,QAAQ,SAAS,SAAS;KACnC,IAAI;MACF,KAAKA,eAAe,UAClB,OAAO,OACP,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;KACA,IAAI;MACF,KAAKA,eAAe,YAClB,KAAA,GACA,OAAO,OACP,WACA,gBACA,OACF;KACF,SAAS,GAAG;MACV,QAAa,OAAO,CAAC;KACvB;IACF;GACF;GAGA,KAAK,UAAU,SAAS,aAAa;IACnC,SAAS,KAAKD,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 { 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 *\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 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 *\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 onSubscribe(): void {\n if (this.listeners.size === 1 && this.#currentMutation) {\n this.#currentMutation.addObserver(this)\n\n this.#updateResult()\n }\n }\n\n protected onUnsubscribe(): void {\n if (!this.hasListeners()) {\n this.#currentMutation?.removeObserver(this)\n }\n }\n\n /** @internal */\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 */\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 *\n * @example\n * ```ts\n * observer.reset()\n * ```\n *\n * @see {@link MutationObserver#mutate}\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 *\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 if (this.#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 this.#mutateOptions.onSuccess?.(\n action.data,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n try {\n this.#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 this.#mutateOptions.onError?.(\n action.error,\n variables,\n onMutateResult,\n context,\n )\n } catch (e) {\n void Promise.reject(e)\n }\n try {\n this.#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":";;;;;;;;;;;;;;;;;;;;AAqCA,IAAa,mBAAb,cAKU,aAER;CAGA;CACA,iBAKI,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,CAAC;EACH,CAAC;CACH;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"onlineManager.cjs","names":["Subscribable"
|
|
1
|
+
{"version":3,"file":"onlineManager.cjs","names":["Subscribable"],"sources":["../../src/onlineManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (online: boolean) => void\ntype SetupFn = (setOnline: Listener) => (() => void) | undefined\n\n/**\n * The `OnlineManager` manages the online state within TanStack Query. It can\n * be used to change the default event listeners or to manually change the\n * online state.\n *\n * By default, the `onlineManager` assumes an active network connection, and\n * listens to the `online` and `offline` events on the `window` object to\n * detect changes.\n */\nexport class OnlineManager extends Subscribable<Listener> {\n #online = true\n #cleanup?: () => void\n\n #setup: SetupFn\n\n constructor() {\n super()\n this.#setup = (onOnline) => {\n // addEventListener does not exist in React Native, but window does\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (typeof window !== 'undefined' && window.addEventListener) {\n const onlineListener = () => onOnline(true)\n const offlineListener = () => onOnline(false)\n // Listen to online\n window.addEventListener('online', onlineListener, false)\n window.addEventListener('offline', offlineListener, false)\n\n return () => {\n // Be sure to unsubscribe if a new handler is set\n window.removeEventListener('online', onlineListener)\n window.removeEventListener('offline', offlineListener)\n }\n }\n\n return\n }\n }\n\n protected onSubscribe(): void {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup)\n }\n }\n\n protected onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.()\n this.#cleanup = undefined\n }\n }\n\n /**\n * `setEventListener` can be used to set a custom event listener that will\n * be used to determine the online state. The provided `setup` function\n * receives a `setOnline` callback that should be called with a `boolean`\n * whenever the online state changes.\n *\n * @example\n * ```ts\n * import NetInfo from '@react-native-community/netinfo'\n * import { onlineManager } from '@tanstack/query-core'\n *\n * onlineManager.setEventListener((setOnline) => {\n * return NetInfo.addEventListener((state) => {\n * setOnline(!!state.isConnected)\n * })\n * })\n * ```\n */\n setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup(this.setOnline.bind(this))\n }\n\n /**\n * `setOnline` can be used to manually set the online state.\n *\n * @example\n * ```ts\n * import { onlineManager } from '@tanstack/query-core'\n *\n * // Set to online\n * onlineManager.setOnline(true)\n *\n * // Set to offline\n * onlineManager.setOnline(false)\n * ```\n */\n setOnline(online: boolean): void {\n const changed = this.#online !== online\n\n if (changed) {\n this.#online = online\n this.listeners.forEach((listener) => {\n listener(online)\n })\n }\n }\n\n /**\n * `isOnline` can be used to get the current online state.\n */\n isOnline(): boolean {\n return this.#online\n }\n}\n\n/**\n * Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.\n */\nexport const onlineManager = new OnlineManager()\n"],"mappings":";;;;;;;;;;;;AAcA,IAAa,gBAAb,cAAmCA,qBAAAA,aAAuB;CACxD,UAAU;CACV;CAEA;CAEA,cAAc;EACZ,MAAM;EACN,KAAK,UAAU,aAAa;GAG1B,IAAI,OAAO,WAAW,eAAe,OAAO,kBAAkB;IAC5D,MAAM,uBAAuB,SAAS,IAAI;IAC1C,MAAM,wBAAwB,SAAS,KAAK;IAE5C,OAAO,iBAAiB,UAAU,gBAAgB,KAAK;IACvD,OAAO,iBAAiB,WAAW,iBAAiB,KAAK;IAEzD,aAAa;KAEX,OAAO,oBAAoB,UAAU,cAAc;KACnD,OAAO,oBAAoB,WAAW,eAAe;IACvD;GACF;EAGF;CACF;CAEA,cAA8B;EAC5B,IAAI,CAAC,KAAK,UACR,KAAK,iBAAiB,KAAK,MAAM;CAErC;CAEA,gBAA0B;EACxB,IAAI,CAAC,KAAK,aAAa,GAAG;GACxB,KAAK,WAAW;GAChB,KAAK,WAAW,KAAA;EAClB;CACF;;;;;;;;;;;;;;;;;;;CAoBA,iBAAiB,OAAsB;EACrC,KAAK,SAAS;EACd,KAAK,WAAW;EAChB,KAAK,WAAW,MAAM,KAAK,UAAU,KAAK,IAAI,CAAC;CACjD;;;;;;;;;;;;;;;CAgBA,UAAU,QAAuB;EAG/B,IAFgB,KAAK,YAAY,QAEpB;GACX,KAAK,UAAU;GACf,KAAK,UAAU,SAAS,aAAa;IACnC,SAAS,MAAM;GACjB,CAAC;EACH;CACF;;;;CAKA,WAAoB;EAClB,OAAO,KAAK;CACd;AACF;;;;AAKA,MAAa,gBAAgB,IAAI,cAAc"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as Subscribable } from "./subscribable-
|
|
1
|
+
import { t as Subscribable } from "./subscribable-CysQ0tne.cjs";
|
|
2
2
|
//#region src/onlineManager.d.ts
|
|
3
3
|
type Listener = (online: boolean) => void;
|
|
4
4
|
type SetupFn = (setOnline: Listener) => (() => void) | undefined;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as Subscribable } from "./subscribable-
|
|
1
|
+
import { t as Subscribable } from "./subscribable-CysQ0tne.js";
|
|
2
2
|
//#region src/onlineManager.d.ts
|
|
3
3
|
type Listener = (online: boolean) => void;
|
|
4
4
|
type SetupFn = (setOnline: Listener) => (() => void) | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"onlineManager.js","names":[
|
|
1
|
+
{"version":3,"file":"onlineManager.js","names":[],"sources":["../../src/onlineManager.ts"],"sourcesContent":["import { Subscribable } from './subscribable'\n\ntype Listener = (online: boolean) => void\ntype SetupFn = (setOnline: Listener) => (() => void) | undefined\n\n/**\n * The `OnlineManager` manages the online state within TanStack Query. It can\n * be used to change the default event listeners or to manually change the\n * online state.\n *\n * By default, the `onlineManager` assumes an active network connection, and\n * listens to the `online` and `offline` events on the `window` object to\n * detect changes.\n */\nexport class OnlineManager extends Subscribable<Listener> {\n #online = true\n #cleanup?: () => void\n\n #setup: SetupFn\n\n constructor() {\n super()\n this.#setup = (onOnline) => {\n // addEventListener does not exist in React Native, but window does\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (typeof window !== 'undefined' && window.addEventListener) {\n const onlineListener = () => onOnline(true)\n const offlineListener = () => onOnline(false)\n // Listen to online\n window.addEventListener('online', onlineListener, false)\n window.addEventListener('offline', offlineListener, false)\n\n return () => {\n // Be sure to unsubscribe if a new handler is set\n window.removeEventListener('online', onlineListener)\n window.removeEventListener('offline', offlineListener)\n }\n }\n\n return\n }\n }\n\n protected onSubscribe(): void {\n if (!this.#cleanup) {\n this.setEventListener(this.#setup)\n }\n }\n\n protected onUnsubscribe() {\n if (!this.hasListeners()) {\n this.#cleanup?.()\n this.#cleanup = undefined\n }\n }\n\n /**\n * `setEventListener` can be used to set a custom event listener that will\n * be used to determine the online state. The provided `setup` function\n * receives a `setOnline` callback that should be called with a `boolean`\n * whenever the online state changes.\n *\n * @example\n * ```ts\n * import NetInfo from '@react-native-community/netinfo'\n * import { onlineManager } from '@tanstack/query-core'\n *\n * onlineManager.setEventListener((setOnline) => {\n * return NetInfo.addEventListener((state) => {\n * setOnline(!!state.isConnected)\n * })\n * })\n * ```\n */\n setEventListener(setup: SetupFn): void {\n this.#setup = setup\n this.#cleanup?.()\n this.#cleanup = setup(this.setOnline.bind(this))\n }\n\n /**\n * `setOnline` can be used to manually set the online state.\n *\n * @example\n * ```ts\n * import { onlineManager } from '@tanstack/query-core'\n *\n * // Set to online\n * onlineManager.setOnline(true)\n *\n * // Set to offline\n * onlineManager.setOnline(false)\n * ```\n */\n setOnline(online: boolean): void {\n const changed = this.#online !== online\n\n if (changed) {\n this.#online = online\n this.listeners.forEach((listener) => {\n listener(online)\n })\n }\n }\n\n /**\n * `isOnline` can be used to get the current online state.\n */\n isOnline(): boolean {\n return this.#online\n }\n}\n\n/**\n * Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.\n */\nexport const onlineManager = new OnlineManager()\n"],"mappings":";;;;;;;;;;;AAcA,IAAa,gBAAb,cAAmC,aAAuB;CACxD,UAAU;CACV;CAEA;CAEA,cAAc;EACZ,MAAM;EACN,KAAK,UAAU,aAAa;GAG1B,IAAI,OAAO,WAAW,eAAe,OAAO,kBAAkB;IAC5D,MAAM,uBAAuB,SAAS,IAAI;IAC1C,MAAM,wBAAwB,SAAS,KAAK;IAE5C,OAAO,iBAAiB,UAAU,gBAAgB,KAAK;IACvD,OAAO,iBAAiB,WAAW,iBAAiB,KAAK;IAEzD,aAAa;KAEX,OAAO,oBAAoB,UAAU,cAAc;KACnD,OAAO,oBAAoB,WAAW,eAAe;IACvD;GACF;EAGF;CACF;CAEA,cAA8B;EAC5B,IAAI,CAAC,KAAK,UACR,KAAK,iBAAiB,KAAK,MAAM;CAErC;CAEA,gBAA0B;EACxB,IAAI,CAAC,KAAK,aAAa,GAAG;GACxB,KAAK,WAAW;GAChB,KAAK,WAAW,KAAA;EAClB;CACF;;;;;;;;;;;;;;;;;;;CAoBA,iBAAiB,OAAsB;EACrC,KAAK,SAAS;EACd,KAAK,WAAW;EAChB,KAAK,WAAW,MAAM,KAAK,UAAU,KAAK,IAAI,CAAC;CACjD;;;;;;;;;;;;;;;CAgBA,UAAU,QAAuB;EAG/B,IAFgB,KAAK,YAAY,QAEpB;GACX,KAAK,UAAU;GACf,KAAK,UAAU,SAAS,aAAa;IACnC,SAAS,MAAM;GACjB,CAAC;EACH;CACF;;;;CAKA,WAAoB;EAClB,OAAO,KAAK;CACd;AACF;;;;AAKA,MAAa,gBAAgB,IAAI,cAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queriesObserver.cjs","names":["Subscribable","#client","#options","#queries","#observers","#result","#onUpdate","#findMatchingObservers","shallowEqualObjects","#observerMatches","#notify","#combineResult","#trackResult","#lastQueryHashes","#lastResult","#lastCombine","#combinedResult","replaceEqualDeep","QueryObserver","#shouldSkipCombine"],"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\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\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 *\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 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 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 *\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 *\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 */\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 */\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 */\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":";;;;;;AAWA,SAAS,WAAc,QAAkB,QAA4B;CACnE,MAAM,aAAa,IAAI,IAAI,MAAM;CACjC,OAAO,OAAO,QAAQ,MAAM,CAAC,WAAW,IAAI,CAAC,CAAC;AAChD;;;;;;;;;;;;;;;;;;;;AAyCA,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,KAAKC,UAAU;EACf,KAAKC,WAAW;EAChB,KAAKC,WAAW,CAAC;EACjB,KAAKC,aAAa,CAAC;EACnB,KAAKC,UAAU,CAAC;EAEhB,KAAK,WAAW,OAAO;CACzB;CAEA,cAA8B;EAC5B,IAAI,KAAK,UAAU,SAAS,GAC1B,KAAKD,WAAW,SAAS,aAAa;GACpC,SAAS,WA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AQ,KAAKG,WAAW,QAAQ,QAAQ;EAC9C,IAAI,UAAU,IAAI;GAChB,KAAKC,UAAU,KAAKA,QAAQ,MAAM;GAClC,KAAKA,QAAQ,SAAS;GACtB,KAAKK,QAAQ;EACf;CACF;CAEA,UAAgB;EACd,IAAI,KAAK,aAAa,GAAG;GACvB,MAAM,oBAAoB,KAAKS,mBAAmB;GAClD,MAAM,iBAAiB,KAAKH;GAC5B,MAAM,YAAY,oBACd,iBACA,KAAKL,eACH,KAAKC,aAAa,KAAKP,SAAS,KAAKI,gBAAgB,GACrD,KAAKP,UAAU,OACjB;GAEJ,IAAI,qBAAqB,mBAAmB,WAC1C,sBAAA,cAAc,YAAY;IACxB,KAAK,UAAU,SAAS,aAAa;KACnC,SAAS,KAAKG,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 {\n DefaultedQueryObserverOptions,\n QueryObserverOptions,\n QueryObserverResult,\n} from './types'\nimport type { QueryClient } from './queryClient'\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\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 *\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 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 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 *\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 *\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 */\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 */\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 */\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":";;;;;;AAWA,SAAS,WAAc,QAAkB,QAA4B;CACnE,MAAM,aAAa,IAAI,IAAI,MAAM;CACjC,OAAO,OAAO,QAAQ,MAAM,CAAC,WAAW,IAAI,CAAC,CAAC;AAChD;;;;;;;;;;;;;;;;;;;;AAyCA,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,cAA8B;EAC5B,IAAI,KAAK,UAAU,SAAS,GAC1B,KAAK,WAAW,SAAS,aAAa;GACpC,SAAS,WAAW,WAAW;IAC7B,KAAK,UAAU,UAAU,MAAM;GACjC,CAAC;EACH,CAAC;CAEL;CAEA,gBAAgC;EAC9B,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;;;;;;;;;;;;;;;CAgBA,WACE,SACA,SACM;EACN,KAAK,WAAW;EAChB,KAAK,WAAW;EAEhB,IAAI,QAAQ,IAAI,aAAa,cAAc;GACzC,MAAM,cAAc,QAAQ,KACzB,UAAU,KAAK,QAAQ,oBAAoB,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C;GACH,CAAC;EAEL;CACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as Subscribable } from "./subscribable-
|
|
2
|
-
import { $n as Query, At as QueryObserverOptions, Pt as QueryObserverResult, on as QueryClient, rr as QueryObserver } from "./hydration-
|
|
1
|
+
import { t as Subscribable } from "./subscribable-CysQ0tne.cjs";
|
|
2
|
+
import { $n as Query, At as QueryObserverOptions, Pt as QueryObserverResult, on as QueryClient, rr as QueryObserver } from "./hydration-Br9VIGXa.cjs";
|
|
3
3
|
//#region src/queriesObserver.d.ts
|
|
4
4
|
type QueriesObserverListener = (result: Array<QueryObserverResult>) => void;
|
|
5
5
|
type CombineFn<TCombinedResult> = (result: Array<QueryObserverResult>) => TCombinedResult;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queriesObserver.d.cts","names":[],"sources":["../../src/queriesObserver.ts"],"mappings":";;;KAgBK,2BAA2B,QAAQ,MAAM;KAEzC,UAAU,oBACb,QAAQ,MAAM,yBACX;UAEY,uBACf,kBAAkB,MAAM;;;;;;;;;EAUxB,UAAU,UAAU;;;;;;;;;;;;;;;;;;;;;cAsBT,gBACX,kBAAkB,MAAM,8BAChB,aAAa;;EAanB,YAAA,QAAQ,aACR,SAAS,MAAM,gDACf,UAAU,uBAAuB;YAazB;YAUA;;;;;EAUV;;;;;;;;;;;;;;;EAqBA,WACE,SAAS,MAAM,uBACf,UAAU,uBAAuB;;;;;;;;;;;;EAiFnC,oBAAoB,MAAM;;;;;EAQ1B,
|
|
1
|
+
{"version":3,"file":"queriesObserver.d.cts","names":["_$__query0.Query"],"sources":["../../src/queriesObserver.ts"],"mappings":";;;KAgBK,2BAA2B,QAAQ,MAAM;KAEzC,UAAU,oBACb,QAAQ,MAAM,yBACX;UAEY,uBACf,kBAAkB,MAAM;;;;;;;;;EAUxB,UAAU,UAAU;;;;;;;;;;;;;;;;;;;;;cAsBT,gBACX,kBAAkB,MAAM,8BAChB,aAAa;;EAanB,YAAA,QAAQ,aACR,SAAS,MAAM,gDACf,UAAU,uBAAuB;YAazB;YAUA;;;;;EAUV;;;;;;;;;;;;;;;EAqBA,WACE,SAAS,MAAM,uBACf,UAAU,uBAAuB;;;;;;;;;;;;EAiFnC,oBAAoB,MAAM;;;;;EAQ1B,cAAUA,eAAA;;;;;;EASV,gBAAY,uBAAA;;;;;;;;EAWZ,oBACE,SAAS,MAAM,uBACf,SAAS,UAAU,gCAEnB,WAAW,MAAM,sBACjB,gBAAgB,IAAI,MAAM,yBAAyB,iBACnD,mBAAmB,MAAM"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as Subscribable } from "./subscribable-
|
|
2
|
-
import { $n as Query, At as QueryObserverOptions, Pt as QueryObserverResult, on as QueryClient, rr as QueryObserver } from "./hydration-
|
|
1
|
+
import { t as Subscribable } from "./subscribable-CysQ0tne.js";
|
|
2
|
+
import { $n as Query, At as QueryObserverOptions, Pt as QueryObserverResult, on as QueryClient, rr as QueryObserver } from "./hydration-B9t5w6NC.js";
|
|
3
3
|
//#region src/queriesObserver.d.ts
|
|
4
4
|
type QueriesObserverListener = (result: Array<QueryObserverResult>) => void;
|
|
5
5
|
type CombineFn<TCombinedResult> = (result: Array<QueryObserverResult>) => TCombinedResult;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"queriesObserver.d.ts","names":[],"sources":["../../src/queriesObserver.ts"],"mappings":";;;KAgBK,2BAA2B,QAAQ,MAAM;KAEzC,UAAU,oBACb,QAAQ,MAAM,yBACX;UAEY,uBACf,kBAAkB,MAAM;;;;;;;;;EAUxB,UAAU,UAAU;;;;;;;;;;;;;;;;;;;;;cAsBT,gBACX,kBAAkB,MAAM,8BAChB,aAAa;;EAanB,YAAA,QAAQ,aACR,SAAS,MAAM,gDACf,UAAU,uBAAuB;YAazB;YAUA;;;;;EAUV;;;;;;;;;;;;;;;EAqBA,WACE,SAAS,MAAM,uBACf,UAAU,uBAAuB;;;;;;;;;;;;EAiFnC,oBAAoB,MAAM;;;;;EAQ1B,
|
|
1
|
+
{"version":3,"file":"queriesObserver.d.ts","names":["_$__query0.Query"],"sources":["../../src/queriesObserver.ts"],"mappings":";;;KAgBK,2BAA2B,QAAQ,MAAM;KAEzC,UAAU,oBACb,QAAQ,MAAM,yBACX;UAEY,uBACf,kBAAkB,MAAM;;;;;;;;;EAUxB,UAAU,UAAU;;;;;;;;;;;;;;;;;;;;;cAsBT,gBACX,kBAAkB,MAAM,8BAChB,aAAa;;EAanB,YAAA,QAAQ,aACR,SAAS,MAAM,gDACf,UAAU,uBAAuB;YAazB;YAUA;;;;;EAUV;;;;;;;;;;;;;;;EAqBA,WACE,SAAS,MAAM,uBACf,UAAU,uBAAuB;;;;;;;;;;;;EAiFnC,oBAAoB,MAAM;;;;;EAQ1B,cAAUA,eAAA;;;;;;EASV,gBAAY,uBAAA;;;;;;;;EAWZ,oBACE,SAAS,MAAM,uBACf,SAAS,UAAU,gCAEnB,WAAW,MAAM,sBACjB,gBAAgB,IAAI,MAAM,yBAAyB,iBACnD,mBAAmB,MAAM"}
|