diff --git a/.changeset/react-query-pluggable.md b/.changeset/react-query-pluggable.md
new file mode 100644
index 00000000000..aa648f0d60c
--- /dev/null
+++ b/.changeset/react-query-pluggable.md
@@ -0,0 +1,16 @@
+---
+'@tanstack/query-core-pluggable': minor
+'@tanstack/react-query-pluggable': minor
+---
+
+Add an experimental ESM-only pair for React. `@tanstack/react-query-pluggable` depends on `@tanstack/query-core-pluggable`. Prepare each `useQuery` call with `queryOptions`, `suspenseQueryOptions`, `infiniteQueryOptions`, or `suspenseInfiniteQueryOptions`. Each factory selects the observer and return type. The Suspense factories delegate an initial fetch to the nearest boundary.
+
+Import optional features such as `refetchInterval`, `select`, `placeholderData`, and `serialScope` where the application uses them. Call the v6 imperative readers as `query(client, options)` and `infiniteQuery(client, options)`. Both use fresh cached data and fetch when stale. Other client operations follow the same client-first convention, including `invalidateQueries(client, filters)`. Mutation hooks acquire their cache on demand. Use `getMutationCache(client)` for direct access.
+
+The single-query reader gets its render behavior from the factory. Import result predicates such as `isSuccess(result)`, `isLoading(result)`, and `isFetchingNextPage(result)` wherever a component needs them. They narrow the result for TypeScript. Use `countFetchingQueries(client)` to count fetching queries across a cache. For a variable-length list, use `useQueries` or `useSuspenseQueries`.
+
+Cache-wide lookups and query-state checks are named imports, including `findCachedQuery(cache, filters)`, `findCachedQueries(cache, filters)`, `clearQueryCache(cache)`, and `isQueryActive(query)`.
+
+Four methods on an individual cache entry are now named imports. Use `invalidateCachedQuery(entry)` to mark it invalidated, `resetCachedQuery(entry)` to cancel its fetch and restore its initial state, `getQueryObserverCount(entry)` to count subscribed observers, and `isQueryFetched(entry)` to check for a data or error update. For a filtered operation that also refetches eligible active queries by default, use `invalidateQueries(client, filters)` or `resetQueries(client, filters)`. Inside a component, `isFetched(result)` reads the update history from the hook result.
+
+Ordinary readers handle failures inline by default. Import `throwOnError` and set `throwOnError: [throwOnError, true]` or `throwOnError: [throwOnError, predicate]` to opt into React error boundaries. Suspense readers include boundary handling automatically. Ordinary queries retain default structural sharing. The infinite query fetcher prepares page requests only when the application uses pagination.
diff --git a/.github/workflows/react-query-bundle-size.yml b/.github/workflows/react-query-bundle-size.yml
new file mode 100644
index 00000000000..043888e83d7
--- /dev/null
+++ b/.github/workflows/react-query-bundle-size.yml
@@ -0,0 +1,104 @@
+name: React Query app bundle size
+
+on:
+ pull_request:
+ paths:
+ - '.github/workflows/react-query-bundle-size.yml'
+ - 'integrations/react/bundle-size/**'
+ - 'packages/query-core/**'
+ - 'packages/query-core-pluggable/**'
+ - 'packages/react-query/**'
+ - 'packages/react-query-pluggable/**'
+ - 'scripts/getTsdownConfig.js'
+ - '.nvmrc'
+ - 'package.json'
+ - 'pnpm-lock.yaml'
+ - 'pnpm-workspace.yaml'
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.event.number }}
+ cancel-in-progress: true
+
+permissions: {}
+
+jobs:
+ measure:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ outputs:
+ report: ${{ steps.measure.outputs.report }}
+ analyzer_url: ${{ steps.analyzer.outputs.artifact-url }}
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ persist-credentials: false
+ - uses: TanStack/config/.github/setup@e4b48f16568324f76f467aa4c2aac2f05db632c3
+ - name: Check out the unmodified PR base
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ ref: ${{ github.event.pull_request.base.sha }}
+ path: .bundle-base
+ persist-credentials: false
+ - name: Install and build the baseline adapter
+ working-directory: .bundle-base
+ run: |
+ pnpm --filter root --filter '@tanstack/react-query...' install --frozen-lockfile
+ pnpm --filter '@tanstack/react-query...' run build
+ - name: Build workspace dependencies
+ run: pnpm --filter '@tanstack/query-integration-react-bundle-size^...' run build
+ - name: Type-check the benchmark and both adapters' screens
+ working-directory: integrations/react/bundle-size
+ run: pnpm run test:types
+ - name: Build and measure production apps
+ id: measure
+ env:
+ QUERY_BASE_CHECKOUT: ${{ github.workspace }}/.bundle-base
+ working-directory: integrations/react/bundle-size
+ run: |
+ pnpm run measure
+ cat dist/report.md >> "$GITHUB_STEP_SUMMARY"
+ jq -Rsr '"report=" + tojson' dist/report.md >> "$GITHUB_OUTPUT"
+ - name: Install Chromium
+ working-directory: integrations/react/bundle-size
+ run: pnpm run browser:install
+ - name: Exercise production apps in Chromium
+ working-directory: integrations/react/bundle-size
+ run: pnpm run test:browser
+ - name: Upload interactive bundle treemaps
+ id: analyzer
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: react-query-bundle-analyzer
+ path: integrations/react/bundle-size/dist/analyzer/
+ if-no-files-found: error
+ retention-days: 30
+ comment:
+ if: github.event.pull_request.head.repo.full_name == github.repository
+ needs: measure
+ runs-on: ubuntu-latest
+ permissions:
+ pull-requests: write
+ steps:
+ - name: Update bundle size comment
+ env:
+ GH_TOKEN: ${{ github.token }}
+ REPO: ${{ github.repository }}
+ PR_NUMBER: ${{ github.event.number }}
+ REPORT: ${{ needs.measure.outputs.report }}
+ ANALYZER_URL: ${{ needs.measure.outputs.analyzer_url }}
+ run: |
+ comments="repos/$REPO/issues/$PR_NUMBER/comments"
+ marker=''
+ id=$(gh api --paginate --slurp "$comments?per_page=100" |
+ jq -r --arg marker "$marker" '[.[][] | select(.user.login == "github-actions[bot]" and (.body | startswith($marker)))][0].id // empty')
+ endpoint="$comments"
+ method=POST
+ if [[ -n "$id" ]]; then
+ endpoint="repos/$REPO/issues/comments/$id"
+ method=PATCH
+ fi
+ jq -n --arg marker "$marker" --argjson report "$REPORT" --arg analyzer "$ANALYZER_URL" \
+ '{body: ($marker + "\n" + $report + "\n[Download the interactive bundle treemaps](" + $analyzer + ")")}' |
+ gh api --silent --method "$method" "$endpoint" --input -
diff --git a/integrations/react/bundle-size/.gitignore b/integrations/react/bundle-size/.gitignore
new file mode 100644
index 00000000000..7a6c09645fe
--- /dev/null
+++ b/integrations/react/bundle-size/.gitignore
@@ -0,0 +1 @@
+.vitest/
diff --git a/integrations/react/bundle-size/README.md b/integrations/react/bundle-size/README.md
new file mode 100644
index 00000000000..10a5db0db0b
--- /dev/null
+++ b/integrations/react/bundle-size/README.md
@@ -0,0 +1,76 @@
+# React Query app bundle size
+
+This workspace builds four browser apps against each adapter’s public package entry point. The read-only app fetches a book list with `useQuery(options)` in v6 and `useQuery(queryOptions(options))` in the pluggable adapter. The paginated app uses the query, infinite-query and mutation option factories to fetch additional pages and save bookmarks in browser storage. The polling app refreshes regular and infinite queries, both with and without Suspense. The pluggable app calls `useQuery` with `queryOptions(options)`, `infiniteQueryOptions(options)`, `suspenseQueryOptions(options)` or `suspenseInfiniteQueryOptions(options)` for each subscriber. The browser test holds the first responses until both dedicated Suspense boundaries show their fallbacks, then checks the resolved data and subsequent refetches. The options app keeps the previous page while fetching, selects the displayed titles, saves bookmarks in a serial scope, and invalidates the bookmark list. Each app uses the default client. The original adapter accepts a numeric interval. The pluggable adapter imports its interval scheduler through the `refetchInterval` option helper.
+
+CI builds the original adapter and its dependencies from the PR's base commit. The stock pair is `@tanstack/react-query` and `@tanstack/query-core`. The experimental pair is `@tanstack/react-query-pluggable` and `@tanstack/query-core-pluggable`. The experimental packages, fixture, bundler and React dependencies come from the PR head. The report records both commit IDs.
+
+## What the PR comment measures
+
+The opening table compares the gzipped Query runtime for each workload. It shows the byte difference and percentage change from v6. The next table lists implementations shipped by v6 that the pluggable build omits for each workload. The comparison checks emitted modules, retained exports and the source map symbols of v6’s built-in polling, selection, placeholder and scope handling. For bulk cache operations it also checks v6's emitted public method names. Expand the Query runtime table for the minified, gzip level 9 and Brotli quality 11 byte counts.
+
+Vite builds the same HTML and React entry points with React, React DOM and their subpaths external. Rolldown groups the retained modules from the adapter and its core package into one ESM chunk. The app and its workload-specific helpers stay in a separate entry chunk. The benchmark measures and compresses the emitted Query chunk directly, including its ESM import and export bindings. Each percentage uses the stock pair’s chunk for the same workload and encoding.
+
+The read-only app displays a failed query through its returned result. Its Query chunk must omit the error reset boundary, render-time error handling and the `shouldThrowError` predicate. The emitted JavaScript must also omit calls to the boundary’s `clearReset` API. The polling app includes the reset boundary for its Suspense queries. A separate consumer builds an ordinary `useQuery` with `throwOnError: [throwOnError, true]`. It must retain the boundary handling and exclude Suspense fetching. All four pluggable workloads must retain `replaceData` and `replaceEqualDeep`, which implement default structural sharing.
+
+The pluggable options app calls `invalidateQueries(client, { queryKey: ['bookmarks'] })`. Every named client operation takes the client first. The benchmark checks retained exports to verify that importing `QueryClient` leaves out `query(client, options)`, `infiniteQuery(client, options)`, `setQueryData` and bulk operations, and that each named operation is available when imported.
+
+For each app, the benchmark verifies that the isolated Query chunk contains the same retained Query module IDs and exports as the deployable browser build and imports only React peer entry points. Both builds reject runtime modules from the other pair or another checkout. Individual probes import operations directly from the public `@tanstack/query-core-pluggable` entry using the React adapter’s dependency scope. Both the read-only and polling apps construct a `QueryClient` and use queries. The pluggable build must retain the query cache and observer and exclude the mutation cache, mutation and mutation observer. Both bookmark apps call `useMutation` and must retain all three mutation modules. The ordinary and infinite option factories select their respective observers. The pluggable adapter exposes `useQuery` for all four modes. Its bundle contains no `useBaseQuery` wrapper, and the bare `useQuery` export leaves out both concrete observers. The benchmark checks the minified Query chunk for the optimistic fetch `Promise.race` in the Suspense workload and its absence in the other three. Each Suspense option factory is also tested independently against its ordinary counterpart. The read-only app excludes the infinite observer, both Suspense factories and their common policy. The polling app exercises all four factories. A separate probe verifies that `suspenseQueryOptions` excludes the infinite factory and observer, and that `suspenseInfiniteQueryOptions` excludes the regular-only factories. Pagination and polling retain the infinite query builder, observer and page fetcher. The read-only and selection apps exclude the page fetcher. Chromium exercises the included implementation by requesting and rendering the second page. All four hook-driven apps exclude both imperative operations. The regular operation is the named `query` export of the client module. Hook-driven apps still retain the core `Query` class. The `infiniteQuery` operation adds page fetching when imported. Additional checks cover polling, infinite queries, selection, placeholder data, serial queues and bulk cache operations. Individual public export probes also check selection, placeholder data and serial queues. The query cache lookups (`findCachedQuery` and `findCachedQueries`), `clearQueryCache`, and active, disabled, static and stale query predicates are measured as named core exports. The invalidation workload retains the filters and refetch predicates it calls, including `invalidateCachedQuery`, `getQueryObserverCount` and `isQueryFetched`. The other three workloads omit these functions. All four omit `resetCachedQuery`; a separate public import probe verifies that it remains available. The benchmark checks all fourteen query result helpers in isolation, then verifies the exact set retained by each screen. The read-only and options apps import `isPending` and `isError`. Pagination additionally imports `isFetching`, and polling reads the query data without any status helpers. The React hydration boundary only restores queries. The universal `hydrate` also restores serial queues from saved mutations.
+
+The PR comment links to the workflow artifact containing an interactive HTML bundle analyzer for each package and workload. Open `dist/analyzer//.html` locally after running the benchmark. Select the `query-runtime` chunk to explore its constituent sources. The treemap shows module contributions from source maps. The tables use actual compressed chunk bytes.
+
+## Lazy route navigation
+
+Open the catalog, visit Bookmarks, load a second page, then return to the catalog. One React root and one `QueryClientProvider` stay mounted for the whole visit. The shell imports the catalog at startup. `React.lazy` loads the bookmarks screen on its first render, and a React `Suspense` boundary shows a fallback while that JavaScript arrives. The catalog uses an ordinary data query.
+
+For the above-the-fold (ATF) and below-the-fold (BTF) layout, open the same app with `?layout=scroll`. The catalog renders immediately. An `IntersectionObserver` mounts the bookmarks component the first time its shelf intersects the viewport. Merely placing a mounted `React.lazy` component below the fold would request its module on the initial render. The navigation and scroll examples share the same dynamic import and emitted files. [React shell and viewport trigger](./src/lazy/main.tsx)
+
+The catalog imports its ordinary-query helper from a dedicated module. Keeping pagination and mutation imports on the bookmarks side gives the bundler a route boundary to follow. In stock v6 the shared client constructs a mutation cache, and its core fetch path references infinite-page behavior. The pluggable pair can defer both implementations until the bookmarks component loads. [v6 client](../../../packages/query-core/src/queryClient.ts) · [v6 fetch path](../../../packages/query-core/src/query.ts) · [Catalog hook](./src/pluggable-catalog.ts) · [Paginated hook](./src/pluggable-query.ts)
+
+The lazy-route table reports Query bytes for the cold catalog, the first trip to Bookmarks, both screens together, and the return trip. Each URL is counted once in the cumulative total. A larger incremental download on the second route can go along with a smaller first load when more of the feature's code can wait for the click. Read the phase rows alongside the total. [Measurement](./lazyRoutes.ts) · [Chromium navigation test](./browser/lazyRoutes.test.ts)
+
+| To explore | Example code |
+| --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
+| Reading a list and handling pending and error states | [Catalog](./src/query.tsx) |
+| Fetching another page and saving a bookmark | [Paginated list and mutation](./src/paginated.tsx) |
+| Selecting titles, showing placeholders and invalidating after queued writes | [Screen](./src/options.tsx) · [v6 options](./src/v6-options.ts) · [Pluggable options](./src/pluggable-options.ts) |
+| Polling regular, infinite and Suspense queries | [Polling screen](./src/polling.tsx) · [Pluggable interval](./src/pluggable-interval.ts) |
+
+## Microfrontend navigation
+
+A shell loads the catalog first and the paginated bookmarks screen on navigation. Both remotes use the host’s React and React DOM and create a client when mounted. In the independent deployment, each remote is built on its own and has a separate Query URL. In the shared deployment, the shell serves one ESM Query chunk containing both routes’ imports. The table reports the gzip bytes of the Query URLs needed for the catalog alone and for the complete journey. Chromium verifies the requests on both visits and on returning to the catalog. The measured bytes describe JavaScript transfer. They do not measure cross-client data caching.
+
+## Run locally
+
+After installing workspace dependencies, build the packages, type-check the fixture, and measure both adapters from the repository root.
+
+```sh
+pnpm --filter '@tanstack/query-integration-react-bundle-size^...' run build
+pnpm --filter @tanstack/query-integration-react-bundle-size run test:types
+pnpm --filter @tanstack/query-integration-react-bundle-size run measure
+```
+
+`test:types` checks the measurement tools, microfrontend host and browser tests. It checks the workload apps and remotes against both adapters' public types. The command also opens the app, remote and adapter hooks in the TypeScript language server to check that the editor resolves the same imports.
+
+To reproduce the CI comparison, use a clean worktree of the base commit. Replace `BASE_SHA` with the base commit from the report.
+
+```sh
+git worktree add --detach ../query-bundle-base BASE_SHA
+pnpm --dir ../query-bundle-base --filter root --filter '@tanstack/react-query...' install --frozen-lockfile
+pnpm --dir ../query-bundle-base --filter '@tanstack/react-query...' run build
+QUERY_BASE_CHECKOUT="$PWD/../query-bundle-base" pnpm --filter @tanstack/query-integration-react-bundle-size run measure
+```
+
+Read the summary and detailed tables in `integrations/react/bundle-size/dist/report.md`. Serve a directory under `dist//` to try the built app.
+
+To try the lazy routes, run `pnpm exec vite preview --outDir dist` from this directory after measuring. Open `/lazy-routes/react-query/` or `/lazy-routes/react-query-pluggable/` on the printed URL. Append `?layout=scroll` to try scrolling to the shelf. The Network panel shows which JavaScript each visit requests.
+
+Run the production apps, lazy routes and microfrontend journeys in Chromium after measuring.
+
+```sh
+cd integrations/react/bundle-size
+pnpm exec playwright install chromium
+pnpm test:browser
+pnpm test:browser:ui
+```
+
+The last command starts Vitest in watch mode with a browser UI for inspecting and rerunning each adapter’s scenarios.
diff --git a/integrations/react/bundle-size/analyze.ts b/integrations/react/bundle-size/analyze.ts
new file mode 100644
index 00000000000..da0e68c5392
--- /dev/null
+++ b/integrations/react/bundle-size/analyze.ts
@@ -0,0 +1,19 @@
+import path from 'node:path'
+import { visualizer } from 'rollup-plugin-visualizer'
+
+export function adapterTreemap(screen: string, packageName: string) {
+ const name = path.posix.basename(packageName)
+ return visualizer({
+ filename: path.join(
+ import.meta.dirname,
+ 'dist/analyzer',
+ screen,
+ name + '.html',
+ ),
+ title: `${packageName} · ${screen}`,
+ template: 'treemap',
+ sourcemap: true,
+ // Make source names comparable across the PR base and head checkouts.
+ projectRoot: /^.*\/(?=(?:packages|integrations)\/)/,
+ })
+}
diff --git a/integrations/react/bundle-size/browser/apps.test.ts b/integrations/react/bundle-size/browser/apps.test.ts
new file mode 100644
index 00000000000..f09e6949000
--- /dev/null
+++ b/integrations/react/bundle-size/browser/apps.test.ts
@@ -0,0 +1,152 @@
+import { afterEach, assert, describe, expect, it } from 'vitest'
+import { commands } from 'vitest/browser'
+
+const adapters = ['react-query', 'react-query-pluggable'] as const
+type Adapter = (typeof adapters)[number]
+type Scenario = 'query' | 'paginated' | 'options' | 'polling'
+
+function mountApp(scenario: Scenario, adapter: Adapter) {
+ const frame = document.createElement('iframe')
+ frame.title = adapter
+ frame.src = `/${scenario}/${adapter}/index.html`
+ document.body.append(frame)
+ return frame
+}
+
+async function openApp(scenario: Scenario, adapter: Adapter) {
+ const frame = mountApp(scenario, adapter)
+ await expect
+ .poll(() => frame.contentDocument?.querySelector('li')?.textContent)
+ .toContain('Middlemarch')
+ const app = frame.contentDocument
+ assert(app, 'Missing document for ' + frame.src)
+ return app
+}
+
+afterEach(() => {
+ document.querySelector('iframe')?.remove()
+ localStorage.removeItem('bookmark')
+ localStorage.removeItem('bookmarks')
+})
+
+describe.each(adapters)('@tanstack/%s', (adapter) => {
+ it('renders a fetched reading list', async () => {
+ const app = await openApp('query', adapter)
+ expect(
+ Array.from(app.querySelectorAll('li'), (row) => row.textContent),
+ ).toEqual(['Middlemarch', 'Persuasion'])
+ })
+
+ it('loads the next page and saves a bookmark', async () => {
+ const app = await openApp('paginated', adapter)
+ const more = Array.from(app.querySelectorAll('button')).find(
+ (button) => button.textContent === 'Load more',
+ )
+ assert(more, 'Missing Load more button')
+ more.click()
+ await expect.poll(() => app.querySelectorAll('li').length).toBe(4)
+ const third = app.querySelectorAll('li')[2]
+ assert(third, 'Missing third book')
+ expect(third.textContent).toContain('Villette')
+ const bookmark = third.querySelector('button')
+ assert(bookmark, 'Missing bookmark button')
+ bookmark.click()
+ await expect
+ .poll(() => app.body.textContent)
+ .toContain('Bookmarked: Villette')
+ expect(localStorage.getItem('bookmark')).toBe('Villette')
+ })
+
+ it('retains the previous selection, queues bookmarks and refreshes the cache', async () => {
+ const app = await openApp('options', adapter)
+ const view = app.defaultView
+ assert(view, 'Missing app window')
+ const originalFetch = view.fetch.bind(view)
+ const gate = Promise.withResolvers()
+ view.fetch = async (...args) => {
+ if (String(args[0]).endsWith('books-2.json')) await gate.promise
+ return originalFetch(...args)
+ }
+ const button = (label: string) => {
+ const element = Array.from(app.querySelectorAll('button')).find(
+ (item) => item.textContent === label,
+ )
+ assert(element, 'Missing button: ' + label)
+ return element
+ }
+ try {
+ button('Next page').click()
+ await expect
+ .poll(() => app.querySelector('[role="status"]')?.textContent)
+ .toBe('Showing the previous page')
+ expect(app.querySelector('ul')?.textContent).toContain('Middlemarch')
+ } finally {
+ gate.resolve()
+ view.fetch = originalFetch
+ }
+ await expect
+ .poll(() => app.querySelector('ul')?.textContent)
+ .toContain('Villette')
+ button('Bookmark this page').click()
+ await expect
+ .poll(() => app.body.textContent)
+ .toContain('Bookmarks: Villette, North and South')
+ expect(
+ Array.from(app.querySelectorAll('ol li'), (item) => item.textContent),
+ ).toEqual([
+ 'Saving Villette',
+ 'Saved Villette',
+ 'Saving North and South',
+ 'Saved North and South',
+ ])
+ })
+
+ it('periodically refetches regular, infinite and suspense queries', async () => {
+ await commands.holdPollingBooks(adapter)
+ const frame = mountApp('polling', adapter)
+ try {
+ await commands.waitForPollingRequest(adapter)
+ await expect
+ .poll(() =>
+ Array.from(
+ frame.contentDocument?.querySelectorAll('[role="status"]') ?? [],
+ (element) => element.textContent,
+ ),
+ )
+ .toEqual(['Loading suspense query…', 'Loading suspense pages…'])
+ } finally {
+ await commands.releasePollingBooks(adapter)
+ }
+ const app = frame.contentDocument
+ assert(app, 'Missing polling app')
+ await expect
+ .poll(() =>
+ Array.from(app.querySelectorAll('li'), (item) =>
+ item.textContent.includes('Middlemarch'),
+ ),
+ )
+ .toEqual([true, true, true, true])
+ const timestamps = () =>
+ Array.from(app.querySelectorAll('time'), (time) => time.dateTime)
+ await expect.poll(() => timestamps().length).toBe(4)
+ // Two successive refreshes for every hook distinguish interval polling from a mount refetch.
+ for (let refresh = 0; refresh < 2; refresh++) {
+ const previous = timestamps()
+ await expect
+ .poll(
+ () => {
+ const current = timestamps()
+ return (
+ current.length === 4 &&
+ current.every((value, index) => {
+ const lastUpdate = previous[index]
+ return lastUpdate !== undefined && value > lastUpdate
+ })
+ )
+ },
+ { timeout: 4000 },
+ )
+ .toBe(true)
+ }
+ })
+})
diff --git a/integrations/react/bundle-size/browser/lazyRoutes.test.ts b/integrations/react/bundle-size/browser/lazyRoutes.test.ts
new file mode 100644
index 00000000000..c4a374b1ac2
--- /dev/null
+++ b/integrations/react/bundle-size/browser/lazyRoutes.test.ts
@@ -0,0 +1,144 @@
+import { afterEach, assert, describe, expect, it, vi } from 'vitest'
+
+interface RequestManifest {
+ catalog: Array
+ bookmarks: Array
+ routeEntries: { catalog: string; bookmarks: string }
+}
+
+async function openCatalog(adapter: string, layout: 'routes' | 'scroll') {
+ const prefix = '/lazy-routes/' + adapter + '/'
+ const response = await fetch(prefix + 'query-requests.json')
+ assert(response.ok, 'Missing measured Query requests for ' + adapter)
+ const manifest: RequestManifest = await response.json()
+
+ const frame = document.createElement('iframe')
+ frame.height = '500'
+ frame.width = '640'
+ frame.src =
+ prefix + 'index.html' + (layout === 'scroll' ? '?layout=scroll' : '')
+ document.body.append(frame)
+ await expect
+ .poll(() => frame.contentDocument?.querySelector('li')?.textContent)
+ .toBe('Middlemarch')
+ const app = frame.contentDocument
+ const view = app?.defaultView
+ assert(app && view, 'Missing lazy app')
+
+ const resources = () =>
+ view.performance.getEntriesByType('resource').flatMap((entry) => {
+ const url = new URL(entry.name)
+ return url.pathname.startsWith(prefix)
+ ? [{ file: url.pathname.slice(prefix.length), start: entry.startTime }]
+ : []
+ })
+ const queryFiles = () =>
+ resources()
+ .map(({ file }) => file)
+ .filter((file) => /^assets\/query-(catalog|bookmarks)-/.test(file))
+ .sort()
+ const copiesOf = (file: string) =>
+ resources().filter((entry) => entry.file === file).length
+ await expect.poll(queryFiles).toEqual([...manifest.catalog].sort())
+ await expect.poll(() => copiesOf(manifest.routeEntries.catalog)).toBe(1)
+ expect(copiesOf(manifest.routeEntries.bookmarks)).toBe(0)
+ await expect.poll(() => copiesOf('books-1.json')).toBe(1)
+
+ const allQueryFiles = [...manifest.catalog, ...manifest.bookmarks].sort()
+ async function expectDeferredRequests(start: number) {
+ await expect.poll(queryFiles).toEqual(allQueryFiles)
+ for (const file of [
+ manifest.routeEntries.bookmarks,
+ ...manifest.bookmarks,
+ ]) {
+ await expect.poll(() => copiesOf(file)).toBe(1)
+ const resource = resources().find((entry) => entry.file === file)
+ assert(resource)
+ expect(resource.start).toBeGreaterThanOrEqual(start)
+ }
+ }
+ function expectReusedFiles() {
+ expect(queryFiles()).toEqual(allQueryFiles)
+ expect(copiesOf(manifest.routeEntries.catalog)).toBe(1)
+ expect(copiesOf(manifest.routeEntries.bookmarks)).toBe(1)
+ }
+ return { app, view, copiesOf, expectDeferredRequests, expectReusedFiles }
+}
+
+function click(parent: ParentNode, label: string) {
+ const button = [...parent.querySelectorAll('button')].find(
+ (item) => item.textContent === label,
+ )
+ assert(button, 'Missing button ' + label)
+ button.click()
+}
+
+afterEach(() => {
+ document.querySelector('iframe')?.remove()
+ localStorage.removeItem('bookmark')
+})
+
+describe.each(['react-query', 'react-query-pluggable'])(
+ '%s lazy bookmarks',
+ (adapter) => {
+ it('downloads bookmarks on navigation and reuses its code and cached pages on revisit', async () => {
+ const { app, view, copiesOf, expectDeferredRequests, expectReusedFiles } =
+ await openCatalog(adapter, 'routes')
+ const beforeNavigation = view.performance.now()
+ click(app, 'Bookmarks')
+ await expect
+ .poll(() => app.querySelector('li button')?.textContent)
+ .toBe('Bookmark')
+ await expectDeferredRequests(beforeNavigation)
+ click(app, 'Load more')
+ await expect.poll(() => app.querySelectorAll('li').length).toBe(4)
+ const villette = [...app.querySelectorAll('li')].find((row) =>
+ row.textContent.includes('Villette'),
+ )
+ assert(villette, 'Missing second page of books')
+ click(villette, 'Bookmark')
+ await expect
+ .poll(() => app.body.textContent)
+ .toContain('Bookmarked: Villette')
+ await expect.poll(() => copiesOf('books-1.json')).toBe(2)
+ await expect.poll(() => copiesOf('books-2.json')).toBe(1)
+
+ const revisitFetch = vi.spyOn(view, 'fetch')
+ click(app, 'Catalog')
+ await expect
+ .poll(() => app.querySelector('li')?.textContent)
+ .toBe('Middlemarch')
+ click(app, 'Bookmarks')
+ await expect.poll(() => app.querySelectorAll('li').length).toBe(4)
+ await expect
+ .poll(() => app.body.textContent)
+ .toContain('Bookmarked: Villette')
+ expect(revisitFetch).not.toHaveBeenCalled()
+ expectReusedFiles()
+ })
+
+ it('downloads the below-fold shelf when scrolled into view and reuses its code on a second scroll', async () => {
+ const { app, view, expectDeferredRequests, expectReusedFiles } =
+ await openCatalog(adapter, 'scroll')
+ const shelf = app.querySelector('#bookmarks-shelf')
+ assert(shelf, 'Missing bookmarks shelf')
+ const top = () => shelf.getBoundingClientRect().top
+ expect(top()).toBeGreaterThanOrEqual(view.innerHeight)
+ expect(shelf.querySelector('li button')).toBeNull()
+ const beforeScroll = view.performance.now()
+ shelf.scrollIntoView()
+ await expect.poll(top).toBeLessThan(view.innerHeight)
+ await expect
+ .poll(() => shelf.querySelector('li')?.textContent)
+ .toContain('Middlemarch')
+ await expectDeferredRequests(beforeScroll)
+
+ view.scrollTo(0, 0)
+ await expect.poll(top).toBeGreaterThanOrEqual(view.innerHeight)
+ shelf.scrollIntoView()
+ await expect.poll(top).toBeLessThan(view.innerHeight)
+ expect(shelf.querySelector('li button')?.textContent).toBe('Bookmark')
+ expectReusedFiles()
+ })
+ },
+)
diff --git a/integrations/react/bundle-size/browser/microfrontend.test.ts b/integrations/react/bundle-size/browser/microfrontend.test.ts
new file mode 100644
index 00000000000..13df9ec9505
--- /dev/null
+++ b/integrations/react/bundle-size/browser/microfrontend.test.ts
@@ -0,0 +1,49 @@
+import { afterEach, assert, describe, expect, it } from 'vitest'
+
+afterEach(() => document.querySelector('iframe')?.remove())
+
+describe.each(['react-query', 'react-query-pluggable'])(
+ '%s microfrontends',
+ (adapter) => {
+ it.each(['independent', 'shared'])(
+ 'loads each Query URL once with %s chunks',
+ async (deployment) => {
+ const prefix = '/microfrontends/' + adapter + '/' + deployment + '/'
+ const frame = document.createElement('iframe')
+ frame.src = prefix + 'index.html'
+ document.body.append(frame)
+ const list = () =>
+ frame.contentDocument?.querySelector('li')?.textContent
+ const queryUrls = () => {
+ const view = frame.contentWindow
+ assert(view, 'Missing microfrontend window')
+ return view.performance
+ .getEntriesByType('resource')
+ .map((resource) => new URL(resource.name).pathname)
+ .filter((pathname) => pathname.endsWith('/query-runtime.js'))
+ }
+ const navigate = (id: string) => {
+ const button =
+ frame.contentDocument?.querySelector(id)
+ assert(button, 'Missing route button ' + id)
+ button.click()
+ }
+ await expect.poll(list).toBe('Middlemarch')
+ const expected = [
+ prefix +
+ (deployment === 'shared' ? '' : 'query/') +
+ 'query-runtime.js',
+ ]
+ expect(queryUrls()).toEqual(expected)
+ navigate('#bookmarks')
+ await expect.poll(list).toContain('Bookmark')
+ if (deployment === 'independent')
+ expected.push(prefix + 'paginated/query-runtime.js')
+ expect(queryUrls()).toEqual(expected)
+ navigate('#catalog')
+ await expect.poll(list).toBe('Middlemarch')
+ expect(queryUrls()).toEqual(expected)
+ },
+ )
+ },
+)
diff --git a/integrations/react/bundle-size/check-editor.ts b/integrations/react/bundle-size/check-editor.ts
new file mode 100644
index 00000000000..65ce5f103ec
--- /dev/null
+++ b/integrations/react/bundle-size/check-editor.ts
@@ -0,0 +1,54 @@
+import assert from 'node:assert/strict'
+import { spawnSync } from 'node:child_process'
+import { createRequire } from 'node:module'
+import { resolve } from 'node:path'
+import type ts from 'typescript'
+
+const files = [
+ 'src/main.tsx',
+ 'src/remote.tsx',
+ 'src/v6-query.ts',
+ 'src/pluggable-query.ts',
+]
+const requests = files.flatMap((name, index) => {
+ const file = resolve(import.meta.dirname, name)
+ return ['open', 'semanticDiagnosticsSync'].map((command, offset) =>
+ JSON.stringify({
+ seq: index * 2 + offset + 1,
+ type: 'request',
+ command,
+ arguments: { file },
+ }),
+ )
+})
+const tsserver = createRequire(import.meta.url).resolve(
+ 'typescript/lib/tsserver.js',
+)
+const run = spawnSync(
+ process.execPath,
+ [tsserver, '--disableAutomaticTypingAcquisition'],
+ {
+ input: requests.join('\n') + '\n',
+ encoding: 'utf8',
+ },
+)
+if (run.error) throw run.error
+assert.equal(run.status, 0, run.stderr)
+
+// tsserver frames each JSON message with a Content-Length header.
+const diagnostics: Array =
+ run.stdout
+ .split('\n')
+ .filter((line) => line.startsWith('{'))
+ .map((line) => JSON.parse(line))
+ .filter((message) => message.command === 'semanticDiagnosticsSync')
+for (const [index, file] of files.entries()) {
+ const report = diagnostics.find(
+ (response) => response.request_seq === index * 2 + 2,
+ )
+ assert.ok(
+ report?.success,
+ report?.message ?? `Missing editor diagnostics for ${file}`,
+ )
+ assert.deepEqual(report.body, [], file)
+}
diff --git a/integrations/react/bundle-size/host/navigation.ts b/integrations/react/bundle-size/host/navigation.ts
new file mode 100644
index 00000000000..743c2e26214
--- /dev/null
+++ b/integrations/react/bundle-size/host/navigation.ts
@@ -0,0 +1,24 @@
+export type MountRemote = (container: Element) => () => void
+
+const container = document.querySelector('main')
+const catalog = document.querySelector('#catalog')
+const bookmarks = document.querySelector('#bookmarks')
+if (!container || !catalog || !bookmarks)
+ throw new Error('Missing reading list shell')
+
+let unmount: ReturnType | undefined
+
+async function openRoute(button: HTMLButtonElement, main: HTMLElement) {
+ const entry = button.dataset.entry
+ if (!entry) throw new Error('Missing remote entry for ' + button.id)
+ const url = new URL(entry, document.baseURI)
+ const remote: { mount: MountRemote } = await import(
+ /* @vite-ignore */ url.href
+ )
+ unmount?.()
+ unmount = remote.mount(main)
+}
+
+catalog.onclick = () => openRoute(catalog, container)
+bookmarks.onclick = () => openRoute(bookmarks, container)
+await openRoute(catalog, container)
diff --git a/integrations/react/bundle-size/index.html b/integrations/react/bundle-size/index.html
new file mode 100644
index 00000000000..5536836fde7
--- /dev/null
+++ b/integrations/react/bundle-size/index.html
@@ -0,0 +1,12 @@
+
+
+
+
+
+ Reading list
+
+
+
+
+
+
diff --git a/integrations/react/bundle-size/lazyRoutes.ts b/integrations/react/bundle-size/lazyRoutes.ts
new file mode 100644
index 00000000000..e63a10b4961
--- /dev/null
+++ b/integrations/react/bundle-size/lazyRoutes.ts
@@ -0,0 +1,342 @@
+import assert from 'node:assert/strict'
+import { readFile, writeFile } from 'node:fs/promises'
+import { SourceMap } from 'node:module'
+import path from 'node:path'
+import { gzipSync } from 'node:zlib'
+import { build, normalizePath } from 'vite'
+import type { Rolldown } from 'vite'
+
+type Chunk = Rolldown.OutputChunk
+type Adapter = '@tanstack/react-query' | '@tanstack/react-query-pluggable'
+type Phase = 'catalog' | 'bookmarks'
+const phases = ['catalog', 'bookmarks'] as const
+const queryPackage =
+ /\/(?:packages|node_modules\/@tanstack)\/(?:query-core|react-query)(?:-pluggable)?\//
+
+// Follow static imports only. The bookmark route starts a second traversal
+// when React.lazy invokes its dynamic import.
+function routeGraph(chunks: Array) {
+ const byName = new Map(chunks.map((chunk) => [chunk.fileName, chunk]))
+ function dependencies(entry: Chunk) {
+ const reached = new Set()
+ function visit(chunk: Chunk) {
+ if (reached.has(chunk)) return
+ reached.add(chunk)
+ for (const file of chunk.imports) {
+ const dependency = byName.get(file)
+ assert(dependency, `Missing static dependency ${file}`)
+ visit(dependency)
+ }
+ }
+ visit(entry)
+ return reached
+ }
+ const entries = chunks.filter((chunk) => chunk.isEntry)
+ assert.equal(entries.length, 1, 'Expected one application entry')
+ const [catalog] = entries
+ const bookmarks = chunks.find((chunk) =>
+ chunk.facadeModuleId?.endsWith('/src/paginated.tsx'),
+ )
+ assert(
+ catalog && bookmarks && bookmarks.isDynamicEntry,
+ 'Missing lazy route entries',
+ )
+ const initial = dependencies(catalog)
+ assert(!initial.has(bookmarks), 'Bookmarks was loaded with the catalog')
+ assert(
+ [...initial].some((chunk) =>
+ chunk.dynamicImports.includes(bookmarks.fileName),
+ ),
+ 'Missing dynamic import to bookmarks',
+ )
+ const deferred = new Set(
+ [...dependencies(bookmarks)].filter((chunk) => !initial.has(chunk)),
+ )
+ assert.equal(
+ initial.size + deferred.size,
+ chunks.length,
+ 'Unmeasured application chunk',
+ )
+ return {
+ catalog: initial,
+ bookmarks: deferred,
+ entries: { catalog: catalog.fileName, bookmarks: bookmarks.fileName },
+ }
+}
+
+function queryExports(chunks: Set, owns: (id: string) => boolean) {
+ const exports = new Map>()
+ for (const chunk of chunks) {
+ for (const [id, module] of Object.entries(chunk.modules)) {
+ if (!module.renderedLength) continue
+ assert(
+ !queryPackage.test(id) || owns(id),
+ `Unexpected Query package ${id}`,
+ )
+ if (owns(id)) {
+ assert(!exports.has(id), `Query module appears in two chunks: ${id}`)
+ exports.set(id, new Set(module.renderedExports))
+ }
+ }
+ }
+ return exports
+}
+
+// Final minification can discard functions after Rolldown has recorded its
+// rendered exports. Compare the Query sources still mapped to output bytes.
+function mappedQuerySources(
+ chunks: Set,
+ outDir: string,
+ owns: (id: string) => boolean,
+) {
+ const sources = new Set()
+ for (const chunk of chunks) {
+ if (!Object.keys(chunk.modules).some(owns)) continue
+ const map = chunk.map
+ assert(map, `Missing source map for ${chunk.fileName}`)
+ const querySources = new Map()
+ for (const source of map.sources) {
+ const id = normalizePath(
+ path.resolve(outDir, path.dirname(chunk.fileName), source),
+ )
+ if (owns(id)) querySources.set(source, id)
+ }
+ const trace = new SourceMap({ ...map, sourceRoot: '' })
+ for (const [line, content] of chunk.code.split('\n').entries()) {
+ for (let column = 0; column < content.length; column++) {
+ const entry = trace.findEntry(line, column)
+ if (!('originalSource' in entry)) continue
+ const source = querySources.get(entry.originalSource)
+ if (source) sources.add(source)
+ }
+ }
+ }
+ assert(sources.size > 0, 'Expected mapped Query bytes on this route')
+ return sources
+}
+
+async function measureAdapter(
+ root: string,
+ source: string,
+ adapter: Adapter,
+ owners: ReadonlyArray,
+) {
+ const pluggable = adapter === '@tanstack/react-query-pluggable'
+ const owns = (id: string) =>
+ owners.some((directory) => id.startsWith(directory))
+ const name = path.posix.basename(adapter)
+ const outDir = path.join(root, 'dist/lazy-routes', name)
+ const packageScope = path.join(source, 'packages', name, 'package.json')
+ async function routeBuild(groups?: Record>>) {
+ const result = await build({
+ root: path.join(root, 'src/lazy'),
+ publicDir: path.join(root, 'public'),
+ base: './',
+ configFile: false,
+ mode: 'production',
+ logLevel: 'warn',
+ resolve: {
+ dedupe: ['react', 'react-dom'],
+ alias: {
+ '#catalog-hooks': path.join(
+ root,
+ 'src',
+ pluggable ? 'pluggable-catalog.ts' : 'v6-catalog.ts',
+ ),
+ '#query-hooks': path.join(
+ root,
+ 'src',
+ pluggable ? 'pluggable-query.ts' : 'v6-query.ts',
+ ),
+ },
+ },
+ plugins: [
+ {
+ name: 'resolve-lazy-route-adapter',
+ enforce: 'pre',
+ resolveId(id) {
+ if (id === '#adapter')
+ return this.resolve(adapter, packageScope, { skipSelf: true })
+ return null
+ },
+ },
+ ],
+ build: {
+ outDir,
+ emptyOutDir: true,
+ write: !!groups,
+ sourcemap: 'hidden',
+ reportCompressedSize: false,
+ rolldownOptions: {
+ checks: { moduleLevelDirective: false },
+ ...(groups && {
+ output: {
+ codeSplitting: {
+ groups: [
+ // Query imports React, and the shell imports Query. Keep React and
+ // its CommonJS interop outside the shell to avoid a chunk cycle.
+ {
+ name: 'react-vendor',
+ test: (id: string) =>
+ /\/node_modules\/(?:react|react-dom|scheduler)\//.test(
+ id,
+ ) || id.includes('rolldown/runtime'),
+ includeDependenciesRecursively: true,
+ },
+ ...phases.map((phase) => ({
+ name: `query-${phase}`,
+ test: (id: string) => groups[phase].has(id),
+ includeDependenciesRecursively: false,
+ })),
+ ],
+ },
+ },
+ }),
+ },
+ },
+ })
+ assert('output' in result)
+ return result.output.filter((output) => output.type === 'chunk')
+ }
+ const ordinary = routeGraph(await routeBuild())
+ const groups = {
+ catalog: queryExports(ordinary.catalog, owns),
+ bookmarks: queryExports(ordinary.bookmarks, owns),
+ }
+ assert(
+ [...groups.catalog.keys()].every((id) => !groups.bookmarks.has(id)),
+ 'A Query module was assigned to both routes',
+ )
+ for (const dir of owners)
+ assert(
+ [...groups.catalog.keys()].some((id) => id.startsWith(dir)),
+ `Missing eager runtime from ${dir}`,
+ )
+ const published = routeGraph(await routeBuild(groups))
+ const requests = {
+ catalog: [] as Array,
+ bookmarks: [] as Array,
+ routeEntries: published.entries,
+ }
+ const bytes = { catalog: 0, bookmarks: 0 }
+ for (const phase of phases) {
+ const chunks = published[phase]
+ assert.deepEqual(
+ queryExports(chunks, owns),
+ groups[phase],
+ `${name} changed retained Query exports for ${phase}`,
+ )
+ const sources = mappedQuerySources(ordinary[phase], outDir, owns)
+ assert.deepEqual(
+ mappedQuerySources(chunks, outDir, owns),
+ sources,
+ `${name} changed emitted Query sources for ${phase}`,
+ )
+ // v6 constructs a mutation cache on startup and includes its infinite fetch behavior.
+ // The pluggable pair first needs both when the bookmarks route opens.
+ const firstVisit: Record = {
+ mutationCache: pluggable ? 'bookmarks' : 'catalog',
+ infiniteQueryBehavior: pluggable ? 'bookmarks' : 'catalog',
+ mutationObserver: 'bookmarks',
+ useMutation: 'bookmarks',
+ infiniteQueryObserver: 'bookmarks',
+ }
+ for (const [feature, visit] of Object.entries(firstVisit)) {
+ assert.equal(
+ [...sources].some((id) => path.basename(id) === feature + '.js'),
+ visit === phase,
+ `${name} ${phase}: ${feature}`,
+ )
+ }
+ for (const chunk of chunks) {
+ const ids = Object.entries(chunk.modules)
+ .filter(([, module]) => module.renderedLength > 0)
+ .map(([id]) => id)
+ if (!ids.some(owns)) continue
+ assert.equal(chunk.name, `query-${phase}`)
+ assert(
+ !chunk.imports.some(
+ (file) =>
+ file === published.entries.catalog ||
+ file === published.entries.bookmarks,
+ ),
+ `Query runtime imports an application entry: ${chunk.fileName}`,
+ )
+ assert(ids.every(owns), `Foreign code in ${chunk.fileName}`)
+ const file = await readFile(path.join(outDir, chunk.fileName))
+ assert.equal(
+ file.toString('utf8'),
+ chunk.code,
+ `Emitted contents differ for ${chunk.fileName}`,
+ )
+ bytes[phase] += gzipSync(file, { level: 9 }).length
+ requests[phase].push(chunk.fileName)
+ }
+ assert(requests[phase].length, `No Query requests for ${phase}`)
+ }
+ await writeFile(
+ path.join(outDir, 'query-requests.json'),
+ JSON.stringify(requests),
+ )
+ return bytes
+}
+
+export async function measureLazyRoutes({
+ root,
+ checkout,
+ baseCheckout,
+ baseline,
+ pluggable,
+ runtimeOwners,
+ formatChange,
+}: {
+ root: string
+ checkout: string
+ baseCheckout?: string
+ baseline: Adapter
+ pluggable: Adapter
+ runtimeOwners: (source: string, adapter: Adapter) => ReadonlyArray
+ formatChange: (bytes: number, baselineBytes: number) => string
+}) {
+ const source = baseCheckout ?? checkout
+ const stock = await measureAdapter(
+ root,
+ source,
+ baseline,
+ runtimeOwners(source, baseline),
+ )
+ const experiment = await measureAdapter(
+ root,
+ checkout,
+ pluggable,
+ runtimeOwners(checkout, pluggable),
+ )
+ const rows = [
+ ['Cold catalog', stock.catalog, experiment.catalog],
+ [
+ 'First bookmarks render (additional)',
+ stock.bookmarks,
+ experiment.bookmarks,
+ ],
+ [
+ 'Catalog and bookmarks (cumulative)',
+ stock.catalog + stock.bookmarks,
+ experiment.catalog + experiment.bookmarks,
+ ],
+ ['Return to catalog (additional, checked in Chromium)', 0, 0],
+ ] as const
+ return [
+ '### Lazy bookmarks on navigation or scroll',
+ '',
+ 'One React app keeps its QueryClient mounted. The catalog loads at startup. React.lazy imports the same bookmarks module when the user opens the route or scrolls the shelf into view. Each Query-only file is gzipped individually at level 9. The benchmark checks module and export placement against Vite’s default production build. The cumulative row counts each URL once.',
+ '',
+ 'The v6 catalog includes the mutation cache and infinite fetch behavior. Pluggable downloads those with bookmarks. Both apps defer the mutation hook and infinite observer until bookmarks are first rendered.',
+ '',
+ '| User action | React Query v6 | React Query Pluggable | Change vs v6 |',
+ '| --- | ---: | ---: | ---: |',
+ ...rows.map(
+ ([visit, base, next]) =>
+ `| ${visit} | ${base.toLocaleString('en-US')} B | ${next.toLocaleString('en-US')} B | ${base ? formatChange(next, base) : '0 B'} |`,
+ ),
+ ].join('\n')
+}
diff --git a/integrations/react/bundle-size/measure.ts b/integrations/react/bundle-size/measure.ts
new file mode 100644
index 00000000000..e63f2398447
--- /dev/null
+++ b/integrations/react/bundle-size/measure.ts
@@ -0,0 +1,954 @@
+import assert from 'node:assert/strict'
+import { execFileSync } from 'node:child_process'
+import { realpath, writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import { brotliCompressSync, constants, gzipSync } from 'node:zlib'
+import { build, normalizePath } from 'vite'
+import { adapterTreemap } from './analyze.ts'
+import { measureLazyRoutes } from './lazyRoutes.ts'
+import { measureMicrofrontends } from './microfrontends.ts'
+import type { Rolldown } from 'vite'
+
+const root = import.meta.dirname
+const checkout = path.resolve(root, '../../..')
+const baseCheckout = process.env.QUERY_BASE_CHECKOUT
+ ? await realpath(process.env.QUERY_BASE_CHECKOUT)
+ : undefined
+const basePackage =
+ baseCheckout && path.join(baseCheckout, 'packages/react-query')
+const baseline = '@tanstack/react-query'
+const pluggable = '@tanstack/react-query-pluggable'
+const pluggableCore = '@tanstack/query-core-pluggable'
+type Adapter = typeof baseline | typeof pluggable
+type Chunk = Rolldown.OutputChunk
+type ModuleEntry = [id: string, module: Chunk['modules'][string]]
+const workloads = [
+ { screen: 'query', title: 'Read-only list' },
+ { screen: 'paginated', title: 'Paginated bookmarks' },
+ {
+ screen: 'options',
+ title: 'Selection, serial bookmarks and invalidation',
+ },
+ {
+ screen: 'polling',
+ title: 'Polling',
+ },
+] as const
+type Screen = (typeof workloads)[number]['screen']
+
+const otherFrameworks = [
+ /\/(?:packages|node_modules\/@tanstack)\/(?:angular|lit|preact|solid|svelte|vue)-query[^/]*\//,
+ /\/node_modules\/(?:@angular|@lit|@vue|lit|lit-element|lit-html|preact|solid-js|svelte|vue)\//,
+]
+
+function buildDirectory(directory: string, packageName: string) {
+ return (
+ normalizePath(
+ path.join(
+ directory,
+ 'packages',
+ path.posix.basename(packageName),
+ 'build',
+ ),
+ ) + '/'
+ )
+}
+
+function runtimeOwners(directory: string, adapter: Adapter) {
+ const core = adapter === baseline ? '@tanstack/query-core' : pluggableCore
+ return [adapter, core].map((name) => buildDirectory(directory, name))
+}
+
+const pluggableOwners = runtimeOwners(checkout, pluggable)
+const pluggableCoreDirectory = buildDirectory(checkout, pluggableCore)
+function rendersFeature(id: string, feature: string) {
+ return (
+ id.endsWith(`/${feature}.js`) &&
+ pluggableOwners.some((dir) => id.startsWith(dir))
+ )
+}
+
+async function buildApp(
+ packageName: Adapter,
+ screen: Screen,
+ belongsToAdapter?: (id: string) => boolean,
+) {
+ const outDir = path.join(
+ root,
+ 'dist',
+ screen,
+ path.posix.basename(packageName),
+ )
+ const result = await build({
+ root,
+ base: './',
+ configFile: false,
+ mode: 'production',
+ logLevel: 'warn',
+ plugins: [
+ ...(belongsToAdapter ? [adapterTreemap(screen, packageName)] : []),
+ {
+ name: 'resolve-benchmark-adapter',
+ enforce: 'pre',
+ resolveId(id, importer) {
+ if (id !== '#adapter') return
+ // Resolve the public browser export using the requested checkout's package scope.
+ const from =
+ packageName === baseline && basePackage
+ ? path.join(basePackage, 'package.json')
+ : importer
+ return this.resolve(packageName, from, { skipSelf: true })
+ },
+ },
+ ],
+ resolve: {
+ dedupe: ['react', 'react-dom'],
+ alias: {
+ '#catalog-hooks': path.join(
+ root,
+ 'src',
+ packageName === pluggable ? 'pluggable-catalog.ts' : 'v6-catalog.ts',
+ ),
+ '#query-hooks': path.join(
+ root,
+ 'src',
+ packageName === pluggable ? 'pluggable-query.ts' : 'v6-query.ts',
+ ),
+ '#polling-option': path.join(
+ root,
+ 'src',
+ packageName === pluggable
+ ? 'pluggable-interval.ts'
+ : 'numeric-interval.ts',
+ ),
+ '#feature-options': path.join(
+ root,
+ 'src',
+ packageName === pluggable ? 'pluggable-options.ts' : 'v6-options.ts',
+ ),
+ '#screen': path.join(root, 'src', `${screen}.tsx`),
+ },
+ },
+ build: {
+ outDir,
+ write: !belongsToAdapter,
+ sourcemap: belongsToAdapter ? 'hidden' : false,
+ reportCompressedSize: false,
+ // All modules in these apps execute on the client.
+ rolldownOptions: {
+ checks: { moduleLevelDirective: false },
+ ...(belongsToAdapter && {
+ external: reactPeer,
+ output: {
+ codeSplitting: {
+ groups: [
+ {
+ name: 'query-runtime',
+ test: belongsToAdapter,
+ includeDependenciesRecursively: false,
+ },
+ ],
+ },
+ },
+ }),
+ },
+ },
+ })
+ assert('output' in result, 'Expected a single application build')
+ const chunks = result.output.filter((output) => output.type === 'chunk')
+ if (!chunks.some((chunk) => chunk.isEntry)) {
+ throw new Error(`Missing browser entry chunk for ${packageName}`)
+ }
+ return chunks
+}
+
+function renderedModules(chunks: Array): Array {
+ return chunks.flatMap((chunk) =>
+ Object.entries(chunk.modules).filter(
+ ([, module]) => module.renderedLength > 0,
+ ),
+ )
+}
+
+// These operations can retain the named helpers they use internally.
+const filterPredicates = [
+ 'isQueryActive',
+ 'isQueryStale',
+ 'getQueryObserverCount',
+]
+const filteredQueries = ['findCachedQueries', ...filterPredicates]
+const refetchFilters = [
+ ...filteredQueries,
+ 'isQueryDisabled',
+ 'isQueryStatic',
+ 'isQueryFetched',
+]
+const bulkOperations: Record> = {
+ getQueriesData: filteredQueries,
+ setQueriesData: ['setQueryData', ...filteredQueries],
+ removeQueries: filteredQueries,
+ resetQueries: ['resetCachedQuery', 'refetchQueries', ...refetchFilters],
+ cancelQueries: filteredQueries,
+ invalidateQueries: [
+ 'invalidateCachedQuery',
+ 'refetchQueries',
+ ...refetchFilters,
+ ],
+ refetchQueries: refetchFilters,
+}
+const cacheHelpers: Record> = {
+ findCachedQuery: filterPredicates,
+ findCachedQueries: filterPredicates,
+ clearQueryCache: [],
+ isQueryActive: [],
+ isQueryDisabled: ['isQueryActive', 'isQueryFetched', 'getQueryObserverCount'],
+ isQueryStatic: ['getQueryObserverCount'],
+ isQueryStale: ['getQueryObserverCount'],
+ isQueryFetched: [],
+ getQueryObserverCount: [],
+ resetCachedQuery: [],
+ invalidateCachedQuery: [],
+}
+
+const resultHelpers = [
+ 'isPending',
+ 'isSuccess',
+ 'isError',
+ 'isFetching',
+ 'isPaused',
+ 'isLoading',
+ 'isRefetching',
+ 'isLoadingError',
+ 'isRefetchError',
+ 'isFetched',
+ 'isFetchingNextPage',
+ 'isFetchingPreviousPage',
+ 'isFetchNextPageError',
+ 'isFetchPreviousPageError',
+]
+
+function checkResultHelpers(
+ modules: Array,
+ expected: Array,
+ context: string,
+) {
+ const included = modules
+ .filter(([id]) => rendersFeature(id, 'queryResult'))
+ .flatMap(([, module]) => module.renderedExports)
+ assert.deepEqual(
+ new Set(included),
+ new Set(expected),
+ `${context} retained unexpected query result helpers`,
+ )
+}
+
+function checkOptimisticFetch(
+ chunks: Array,
+ expected: boolean,
+ context: string,
+) {
+ // Inspect the emitted Query JS. This catches a race left inside an otherwise
+ // essential class even if the dedicated Suspense module was tree-shaken.
+ const included = chunks.some(({ code }) => /\bPromise\.race\s*\(/.test(code))
+ assert.equal(
+ included,
+ expected,
+ `${context} retained optimistic fetch race: ${included}`,
+ )
+}
+
+function checkErrorReset(
+ chunks: Array,
+ expected: boolean,
+ context: string,
+) {
+ // The generic reader must not keep a call to the public boundary reset API.
+ const included = chunks.some(({ code }) => /\.clearReset\b/.test(code))
+ assert.equal(
+ included,
+ expected,
+ `${context} retained error-boundary reset access: ${included}`,
+ )
+}
+
+function checkClientOperations(
+ modules: Array,
+ workload: string,
+ required?: string,
+) {
+ const tracked = new Set([
+ ...Object.keys(bulkOperations),
+ ...Object.keys(cacheHelpers),
+ 'infiniteQuery',
+ 'query',
+ 'setQueryData',
+ ])
+ const operations = new Set(
+ modules
+ .filter(([id]) => id.startsWith(pluggableCoreDirectory))
+ .flatMap(([, module]) =>
+ module.renderedExports.filter((name) => tracked.has(name)),
+ ),
+ )
+ const allowed = [
+ required,
+ ...(required
+ ? (bulkOperations[required] ?? cacheHelpers[required] ?? [])
+ : []),
+ ...(required === 'infiniteQuery' ? ['query'] : []),
+ ]
+ for (const name of operations) {
+ assert(
+ allowed.includes(name),
+ `${workload} retained unused client operation ${name}`,
+ )
+ }
+ if (required)
+ assert(operations.has(required), `${workload} is missing ${required}`)
+ if (required === 'invalidateQueries') {
+ for (const used of [
+ 'invalidateCachedQuery',
+ 'getQueryObserverCount',
+ 'isQueryFetched',
+ ])
+ assert(operations.has(used), `${workload} is missing ${used}`)
+ }
+}
+
+// Query modules may only come from the two packages built in the selected checkout.
+function checkPairOwnership(
+ modules: Array,
+ owners: Array,
+ context: string,
+) {
+ const foreign = modules.find(
+ ([id]) =>
+ /\/(?:packages|node_modules\/@tanstack)\/(?:query-core|react-query)(?:-pluggable)?\//.test(
+ id,
+ ) && !owners.some((dir) => id.startsWith(dir)),
+ )
+ if (foreign)
+ throw new Error(
+ `${context} retained Query code outside the selected package pair: ${foreign[0]}`,
+ )
+}
+
+function checkApp(chunks: Array, packageName: Adapter, screen: Screen) {
+ if (packageName === pluggable) {
+ const retained = renderedModules(chunks)
+ const modules = retained.map(([id]) => id)
+ const foreignRuntime = modules.find((id) =>
+ otherFrameworks.some((pattern) => pattern.test(id)),
+ )
+ if (foreignRuntime) {
+ throw new Error(
+ `${packageName} bundled unexpected runtime code: ${foreignRuntime}`,
+ )
+ }
+ if (
+ chunks.some((chunk) =>
+ chunk.moduleIds.some(
+ (id) =>
+ id.endsWith('/build/runtime/index.js') ||
+ rendersFeature(id, 'useBaseQuery'),
+ ),
+ )
+ ) {
+ throw new Error(
+ `${packageName} included an internal runtime barrel or useBaseQuery in the app`,
+ )
+ }
+ const usesMutations = screen === 'paginated' || screen === 'options'
+ const usesPages = screen === 'paginated' || screen === 'polling'
+ const features = {
+ queryClient: true,
+ queryCache: true,
+ query: true,
+ queryObserver: true,
+ mutationCache: usesMutations,
+ mutation: usesMutations,
+ mutationObserver: usesMutations,
+ suspenseQueryOptions: screen === 'polling',
+ suspenseInfiniteQueryOptions: screen === 'polling',
+ suspense: screen === 'polling',
+ QueryErrorResetBoundary: screen === 'polling',
+ errorBoundaryUtils: screen === 'polling',
+ fetchOptimistic: screen === 'polling',
+ refetchInterval: screen === 'polling',
+ infiniteQuery: false,
+ queryOptions: true,
+ infiniteQueryOptions: usesPages,
+ infiniteQueryObserver: usesPages,
+ infiniteQueryBehavior: usesPages,
+ select: screen === 'options',
+ placeholderData: screen === 'options',
+ serialScope: screen === 'options',
+ cacheOperations: screen === 'options',
+ queryCacheOperations: screen === 'options',
+ queryPredicates: screen === 'options',
+ }
+ for (const [feature, expected] of Object.entries(features)) {
+ const included = modules.some((id) => rendersFeature(id, feature))
+ if (included !== expected) {
+ throw new Error(
+ `Unexpected ${feature} implementation in ${screen}: included=${included}`,
+ )
+ }
+ }
+ const pageFetcher = retained.some(
+ ([id, module]) =>
+ rendersFeature(id, 'infiniteQueryBehavior') &&
+ module.renderedExports.includes('createInfiniteFetch'),
+ )
+ assert.equal(pageFetcher, usesPages, `${screen} infinite page fetcher`)
+ const utilities = retained
+ .filter(([id]) => rendersFeature(id, 'utils'))
+ .flatMap(([, module]) => module.renderedExports)
+ assert(
+ utilities.includes('replaceEqualDeep') &&
+ utilities.includes('replaceData'),
+ `${screen} is missing default structural sharing`,
+ )
+ if (screen === 'query') {
+ assert(
+ !modules.some((id) => rendersFeature(id, 'throwOnError')),
+ 'Read-only list retained the optional throwOnError implementation',
+ )
+ assert(
+ !utilities.includes('shouldThrowError'),
+ 'Read-only list retained the error boundary predicate',
+ )
+ }
+ const selectedStatus = screen === 'polling' ? [] : ['isPending', 'isError']
+ if (screen === 'paginated') selectedStatus.push('isFetching')
+ checkResultHelpers(retained, selectedStatus, screen)
+ checkClientOperations(
+ retained,
+ screen,
+ screen === 'options' ? 'invalidateQueries' : undefined,
+ )
+ }
+}
+
+const reactPeer = /^react(?:-dom)?(?:\/|$)/
+
+function retainedExports(modules: Array) {
+ return new Map(
+ modules.map(([id, module]) => [id, new Set(module.renderedExports)]),
+ )
+}
+
+// v6 keeps some features inside classes. The emitted chunk's source map names
+// their retained implementations even when the production minifier renames them.
+function workloadFeatures(
+ packageName: Adapter,
+ chunk: Chunk,
+ modules: Array,
+) {
+ const files = new Set(modules.map(([id]) => path.basename(id, '.js')))
+ assert(chunk.map, 'Expected a source map for the attributed Query chunk')
+ const symbols = new Set(chunk.map.names)
+ const exports = new Set(
+ modules.flatMap(([, module]) => module.renderedExports),
+ )
+ const stock = packageName === baseline
+ const bulk = [
+ 'getQueriesData',
+ 'setQueriesData',
+ 'cancelQueries',
+ 'resetQueries',
+ ]
+ const features = {
+ 'Manual cached-query reset': stock
+ ? /\breset\(\)\{[^}]*\bthis\.resetState\b/.test(chunk.code)
+ : exports.has('resetCachedQuery'),
+ 'Cached-query invalidation and observer/fetch checks': stock
+ ? ['invalidate', 'getObserversCount', 'isFetched'].every((method) =>
+ chunk.code.includes(`${method}(){`),
+ )
+ : [
+ 'invalidateCachedQuery',
+ 'getQueryObserverCount',
+ 'isQueryFetched',
+ ].some((operation) => exports.has(operation)),
+ 'Mutation cache': files.has('mutationCache'),
+ 'Serial mutation queues': stock
+ ? symbols.has('scopeFor')
+ : files.has('serialScope'),
+ 'Infinite page fetching': files.has('infiniteQueryBehavior'),
+ 'Interval polling': stock
+ ? symbols.has('#updateRefetchInterval')
+ : files.has('refetchInterval'),
+ 'Result selection and placeholder data': stock
+ ? symbols.has('selection') && symbols.has('#resolvePlaceholder')
+ : files.has('select') || files.has('placeholderData'),
+ 'Optimistic observer fetch (`fetchOptimistic`)': stock
+ ? chunk.code.includes('fetchOptimistic(')
+ : files.has('fetchOptimistic'),
+ 'Query error reset handling': files.has('QueryErrorResetBoundary'),
+ 'Bulk cache reads, writes, cancellation and reset': stock
+ ? bulk.every((method) => chunk.code.includes(`${method}(`))
+ : bulk.some((operation) => exports.has(operation)),
+ }
+ return Object.entries(features)
+ .filter(([, included]) => included)
+ .map(([name]) => name)
+}
+
+async function measure(packageName: Adapter, screen: Screen) {
+ const app = await buildApp(packageName, screen)
+ checkApp(app, packageName, screen)
+
+ // Only published package JS from the appropriate checkout may enter the
+ // Query chunk. Keep the original app entrypoint so it drives tree-shaking.
+ const source =
+ packageName === baseline && baseCheckout ? baseCheckout : checkout
+ const owners = runtimeOwners(source, packageName)
+ const belongsToAdapter = (id: string) =>
+ owners.some((dir) => id.startsWith(dir))
+ checkPairOwnership(
+ renderedModules(app),
+ owners,
+ `${packageName} ${screen} app`,
+ )
+ const attributed = await buildApp(packageName, screen, belongsToAdapter)
+ checkPairOwnership(
+ renderedModules(attributed),
+ owners,
+ `${packageName} ${screen} attribution`,
+ )
+ const library = attributed.filter((chunk) => chunk.name === 'query-runtime')
+ const [queryChunk] = library
+ assert(
+ queryChunk && library.length === 1,
+ `Expected one Query chunk in ${packageName} ${screen}`,
+ )
+ if (packageName === pluggable) {
+ checkOptimisticFetch(library, screen === 'polling', screen)
+ checkErrorReset(library, screen === 'polling', screen)
+ }
+ const actual = renderedModules(library)
+ const expected = renderedModules(app).filter(([id]) => belongsToAdapter(id))
+ for (const dir of owners) {
+ if (!expected.some(([id]) => id.startsWith(dir))) {
+ throw new Error(`Missing Query runtime from ${dir} in ${screen}`)
+ }
+ }
+ assert.deepEqual(
+ retainedExports(actual),
+ retainedExports(expected),
+ `Query modules or exports differ from the production ${packageName} ${screen} app`,
+ )
+ if (
+ renderedModules(attributed.filter((chunk) => chunk !== queryChunk)).some(
+ ([id]) => belongsToAdapter(id),
+ ) ||
+ [...queryChunk.imports, ...queryChunk.dynamicImports].some(
+ (id) => !reactPeer.test(id),
+ )
+ ) {
+ throw new Error(
+ `Query runtime spans additional chunks in ${packageName} ${screen}`,
+ )
+ }
+ const largestModules = actual
+ .sort(([, a], [, b]) => b.renderedLength - a.renderedLength)
+ .slice(0, 5)
+ .map(([id]) =>
+ normalizePath(path.relative(path.join(source, 'packages'), id)),
+ )
+ const js = Buffer.from(queryChunk.code)
+ return {
+ name: packageName,
+ library: {
+ raw: js.length,
+ gzip: gzipSync(js, { level: 9 }).length,
+ brotli: brotliCompressSync(js, {
+ params: { [constants.BROTLI_PARAM_QUALITY]: 11 },
+ }).length,
+ },
+ largestModules,
+ features: workloadFeatures(packageName, queryChunk, actual),
+ }
+}
+
+// A combined app cannot tell whether each projection pulls in its sibling,
+// or whether rendering a boundary pulls in paused-mutation restoration.
+async function checkPluggableExports() {
+ const adapter = await import('@tanstack/react-query-pluggable')
+ const { QueryClient, QueriesObserver, notifyManager } = adapter
+ for (const alias of [
+ 'fetchQuery',
+ 'fetchInfiniteQuery',
+ 'suspense',
+ 'suspenseQuery',
+ 'useBaseQuery',
+ 'useInfiniteQuery',
+ 'useSuspenseQuery',
+ 'useSuspenseInfiniteQuery',
+ ]) {
+ assert(!Object.hasOwn(adapter, alias), `Unexpected retired export ${alias}`)
+ }
+ const client = new QueryClient()
+ const key = ['public-export-probe']
+ const initial = await adapter.query(client, {
+ queryKey: key,
+ queryFn: () => ({ titles: ['A'], page: 1 }),
+ })
+ const updated = adapter.setQueryData(client, key, {
+ titles: ['A'],
+ page: 2,
+ })
+ assert(updated)
+ assert.equal(updated.page, 2)
+ assert.strictEqual(
+ updated.titles,
+ initial.titles,
+ 'Default structural sharing',
+ )
+ assert.deepEqual(
+ await adapter.infiniteQuery(client, {
+ queryKey: ['public-infinite-export-probe'],
+ initialPageParam: 0,
+ queryFn: ({ pageParam }) => pageParam,
+ getNextPageParam: () => undefined,
+ }),
+ { pages: [0], pageParams: [0] },
+ )
+ assert.deepEqual(
+ Object.getOwnPropertyNames(QueryClient.prototype),
+ ['constructor'],
+ 'QueryClient operations must be independently importable',
+ )
+ if (
+ 'getQueries' in QueriesObserver.prototype ||
+ 'setBatchNotifyFunction' in notifyManager
+ ) {
+ throw new Error(
+ `${pluggable} exposed another adapter's observer or batch notification API`,
+ )
+ }
+ for (const [type, members] of [
+ [adapter.QueryObserver, ['fetchOptimistic']],
+ [adapter.QueryCache, ['find', 'findAll', 'clear']],
+ [
+ adapter.Query,
+ [
+ 'isActive',
+ 'isDisabled',
+ 'isStatic',
+ 'isStale',
+ 'reset',
+ 'invalidate',
+ 'getObserversCount',
+ 'isFetched',
+ ],
+ ],
+ ] as const) {
+ for (const member of members)
+ assert(
+ !(member in type.prototype),
+ `${type.name}.${member} would ship to every consumer`,
+ )
+ }
+ const reactExports = {
+ useQuery: [],
+ queryOptions: ['queryOptions', 'queryObserver'],
+ infiniteQueryOptions: [
+ 'infiniteQueryOptions',
+ 'infiniteQueryObserver',
+ 'queryObserver',
+ 'infiniteQueryBehavior',
+ ],
+ mutationOptions: [],
+ throwOnError: [
+ 'queryOptions',
+ 'queryObserver',
+ 'throwOnError',
+ 'QueryErrorResetBoundary',
+ 'errorBoundaryUtils',
+ ],
+ suspenseQueryOptions: [
+ 'suspenseQueryOptions',
+ 'queryObserver',
+ 'suspense',
+ 'QueryErrorResetBoundary',
+ 'errorBoundaryUtils',
+ 'fetchOptimistic',
+ ],
+ suspenseInfiniteQueryOptions: [
+ 'suspenseInfiniteQueryOptions',
+ 'infiniteQueryObserver',
+ 'queryObserver',
+ 'infiniteQueryBehavior',
+ 'suspense',
+ 'QueryErrorResetBoundary',
+ 'errorBoundaryUtils',
+ 'fetchOptimistic',
+ ],
+ HydrationBoundary: ['infiniteQueryBehavior'],
+ }
+ const coreExports = {
+ ...Object.fromEntries(resultHelpers.map((name) => [name, ['queryResult']])),
+ fetchOptimistic: ['fetchOptimistic'],
+ infiniteQuery: ['infiniteQuery', 'infiniteQueryBehavior'],
+ QueryClient: [],
+ query: [],
+ setQueryData: [],
+ getMutationCache: ['mutationCache'],
+ select: ['select', 'projectResult'],
+ placeholderData: ['placeholderData', 'projectResult'],
+ serialScope: ['serialScope'],
+ findCachedQuery: ['queryCacheOperations', 'queryPredicates'],
+ findCachedQueries: ['queryCacheOperations', 'queryPredicates'],
+ clearQueryCache: ['queryCacheOperations'],
+ isQueryActive: ['queryPredicates'],
+ isQueryDisabled: ['queryPredicates'],
+ isQueryStatic: ['queryPredicates'],
+ isQueryStale: ['queryPredicates'],
+ isQueryFetched: ['queryPredicates'],
+ getQueryObserverCount: ['queryPredicates'],
+ resetCachedQuery: [],
+ invalidateCachedQuery: [],
+ ...Object.fromEntries(
+ Object.keys(bulkOperations).map((name) => [
+ name,
+ ['cacheOperations', 'queryCacheOperations', 'queryPredicates'],
+ ]),
+ ),
+ dehydrate: [],
+ hydrate: [
+ 'infiniteQueryBehavior',
+ 'mutation',
+ 'mutationCache',
+ 'serialScope',
+ ],
+ }
+ const expected: Record> = {
+ ...reactExports,
+ ...coreExports,
+ }
+ const features = new Set(Object.values(expected).flat())
+ const entry = path.join(root, 'public-export-probe.ts')
+ for (const [name, required] of Object.entries(expected)) {
+ const coreOnly = Object.hasOwn(coreExports, name)
+ const source = coreOnly ? pluggableCore : pluggable
+ const results = await build({
+ root,
+ configFile: false,
+ logLevel: 'error',
+ plugins: [
+ {
+ name: 'import-one-public-export',
+ resolveId(id) {
+ if (id === entry) return id
+ if (id === pluggableCore) {
+ const importer = path.join(
+ checkout,
+ 'packages/react-query-pluggable/package.json',
+ )
+ return this.resolve(id, importer, { skipSelf: true })
+ }
+ return undefined
+ },
+ load(id) {
+ if (id !== entry) return
+ if (name === 'throwOnError') {
+ return `
+ import { queryOptions, throwOnError, useQuery } from '${source}'
+ export function useThrowingQuery() {
+ return useQuery(queryOptions({ queryKey: ['boundary-probe'], queryFn: () => 1, throwOnError: [throwOnError, true] }))
+ }
+ `
+ }
+ return `export { ${name} } from '${source}'`
+ },
+ },
+ ],
+ build: {
+ write: false,
+ lib: { entry, formats: ['es'], fileName: 'probe' },
+ rolldownOptions: {
+ external: reactPeer,
+ checks: { moduleLevelDirective: false },
+ },
+ },
+ })
+ assert(Array.isArray(results), 'Expected an ESM library build')
+ const chunks = results.flatMap(({ output }) =>
+ output.filter((file) => file.type === 'chunk'),
+ )
+ const modules = renderedModules(chunks)
+ const owners = coreOnly ? [pluggableCoreDirectory] : pluggableOwners
+ checkPairOwnership(modules, owners, `Importing ${name} from ${source}`)
+ if (
+ coreOnly &&
+ !modules.some(([id]) => id.startsWith(pluggableCoreDirectory))
+ ) {
+ throw new Error(
+ `Core export ${name} did not render any code from ${source}`,
+ )
+ }
+ if (
+ coreOnly &&
+ chunks.some((chunk) =>
+ [...chunk.imports, ...chunk.dynamicImports].some((id) =>
+ reactPeer.test(id),
+ ),
+ )
+ ) {
+ throw new Error(`Core export ${name} imported React`)
+ }
+ for (const feature of features) {
+ // Suspense can share the error policy used by the explicit option helper.
+ if (feature === 'throwOnError' && required.includes('suspense')) continue
+ const included = modules.some(([id]) => rendersFeature(id, feature))
+ if (included !== required.includes(feature)) {
+ throw new Error(
+ `Importing ${name} unexpectedly ${included ? 'included' : 'excluded'} ${feature}`,
+ )
+ }
+ }
+ if (resultHelpers.includes(name)) checkResultHelpers(modules, [name], name)
+ if (!coreOnly)
+ checkErrorReset(
+ chunks,
+ required.includes('QueryErrorResetBoundary'),
+ name,
+ )
+ if (!coreOnly || name === 'fetchOptimistic')
+ checkOptimisticFetch(chunks, required.includes('fetchOptimistic'), name)
+ if (
+ ['QueryClient', 'query', 'infiniteQuery', 'setQueryData'].includes(
+ name,
+ ) ||
+ Object.hasOwn(bulkOperations, name) ||
+ Object.hasOwn(cacheHelpers, name)
+ ) {
+ checkClientOperations(
+ modules,
+ name,
+ name === 'QueryClient' ? undefined : name,
+ )
+ }
+ }
+}
+await checkPluggableExports()
+
+const integer = new Intl.NumberFormat('en-US')
+function formatChange(bytes: number, baselineBytes: number) {
+ const difference = bytes - baselineBytes
+ const sign = difference > 0 ? '+' : ''
+ const percent = ((100 * difference) / baselineBytes).toFixed(2)
+ return `${sign}${integer.format(difference)} B (${sign}${percent}%)`
+}
+
+function formatSize(bytes: number, baselineBytes: number, isBaseline: boolean) {
+ const size = `${integer.format(bytes)} B`
+ if (isBaseline) return size
+ return `${size}
${formatChange(bytes, baselineBytes)}`
+}
+
+function revision(directory: string) {
+ return execFileSync('git', ['-C', directory, 'rev-parse', 'HEAD'], {
+ encoding: 'utf8',
+ }).trim()
+}
+
+const head = revision(root)
+const base = baseCheckout ? revision(baseCheckout) : head
+const lines = [
+ '## React Query bundle size',
+ '',
+ '### Gzipped Query runtime',
+ '',
+ 'Each row compares the Query JavaScript used by the same app. The change is measured against v6 for that row. Negative values mean fewer bytes.',
+ '',
+ '| Workload | React Query v6 | React Query Pluggable | Change vs v6 |',
+ '| --- | ---: | ---: | ---: |',
+]
+const results = []
+for (const { screen, title } of workloads) {
+ const stock = await measure(baseline, screen)
+ const experiment = await measure(pluggable, screen)
+ results.push({ screen, title, rows: [stock, experiment] as const })
+ const v6Gzip = stock.library.gzip
+ const pluggableGzip = experiment.library.gzip
+ lines.push(
+ `| ${title} | ${integer.format(v6Gzip)} B | ${integer.format(pluggableGzip)} B | ${formatChange(pluggableGzip, v6Gzip)} |`,
+ )
+}
+lines.push(
+ '',
+ '### What each workload leaves out',
+ '',
+ 'These implementations are present in the v6 Query chunk and absent from the pluggable chunk for the same screen.',
+ '',
+ '| Workload | Code removed compared with v6 |',
+ '| --- | --- |',
+)
+for (const {
+ title,
+ rows: [stock, experiment],
+} of results) {
+ const removed = stock.features.filter(
+ (feature) => !experiment.features.includes(feature),
+ )
+ lines.push(
+ `| ${title} | ${removed.join(' · ') || 'None of the tracked features'} |`,
+ )
+}
+lines.push(
+ '',
+ 'All four screens retain default structural sharing. Both bookmark screens retain mutation support. The selection screen retains invalidation and refetching. The polling screen retains Suspense, pagination and polling.',
+ '',
+ `Baseline adapter and core at \`${base}\` (${baseCheckout ? 'base checkout' : 'current checkout'}). Pluggable adapter, core and fixture at \`${head}\`.`,
+)
+lines.push(
+ '',
+ '',
+ 'Query runtime sizes · minified JS, gzip and Brotli
',
+ '',
+ 'The app entry drives tree-shaking. Each isolated ESM chunk includes the React adapter and its matching core. React and React DOM are external. Sizes are bytes of the Query chunk measured directly, with gzip level 9 and Brotli quality 11.',
+ '',
+ '| Workload | Package | Minified JS | Gzip | Brotli |',
+ '| --- | --- | ---: | ---: | ---: |',
+)
+for (const { title, rows } of results) {
+ const baselineSizes = rows[0].library
+ for (const row of rows) {
+ const cells = (['raw', 'gzip', 'brotli'] as const).map((metric) =>
+ formatSize(
+ row.library[metric],
+ baselineSizes[metric],
+ row.name === baseline,
+ ),
+ )
+ lines.push(`| ${title} | \`${row.name}\` | ${cells.join(' | ')} |`)
+ }
+}
+const comparison = {
+ root,
+ checkout,
+ baseCheckout,
+ baseline,
+ pluggable,
+ runtimeOwners,
+ formatChange,
+} as const
+const readOnly = results.find(({ screen }) => screen === 'query')?.rows[1]
+assert(readOnly, 'Expected a read-only pluggable workload')
+lines.push(
+ '',
+ `Largest modules in the read-only pluggable chunk, by rendered size before minification: ${readOnly.largestModules.map((name) => `\`${name}\``).join(', ')}.`,
+ '',
+ ' ',
+ '',
+ await measureLazyRoutes(comparison),
+ '',
+ await measureMicrofrontends(comparison),
+ '',
+)
+const report = lines.join('\n')
+await writeFile(path.join(root, 'dist/report.md'), report)
+process.stdout.write(report)
diff --git a/integrations/react/bundle-size/microfrontends.ts b/integrations/react/bundle-size/microfrontends.ts
new file mode 100644
index 00000000000..169cfd44b52
--- /dev/null
+++ b/integrations/react/bundle-size/microfrontends.ts
@@ -0,0 +1,249 @@
+import assert from 'node:assert/strict'
+import { cp, mkdir, writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import { gzipSync } from 'node:zlib'
+import { build } from 'vite'
+
+const screens = ['query', 'paginated'] as const
+type Screen = (typeof screens)[number]
+type Adapter = '@tanstack/react-query' | '@tanstack/react-query-pluggable'
+const deployments = ['independent', 'shared'] as const
+type Deployment = (typeof deployments)[number]
+
+// Both remotes use the host's React and React DOM. A shared Query deployment
+// serves one ESM chunk at one URL; each remote still owns its QueryClient.
+async function buildHost(root: string, directory: string) {
+ const peers: Record = {
+ react:
+ "export { default, createContext, use, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'",
+ dom: "export { createRoot } from 'react-dom/client'",
+ jsx: "export { Fragment, jsx, jsxs } from 'react/jsx-runtime'",
+ }
+ const input = {
+ navigation: path.join(root, 'host/navigation.ts'),
+ ...Object.fromEntries(
+ Object.keys(peers).map((name) => [name, 'host:' + name]),
+ ),
+ }
+ await build({
+ root,
+ configFile: false,
+ publicDir: false,
+ logLevel: 'warn',
+ plugins: [
+ {
+ name: 'microfrontend-host-peers',
+ resolveId(id) {
+ return id.startsWith('host:') ? '\0' + id : null
+ },
+ load(id) {
+ if (!id.startsWith('\0host:')) return
+ return peers[id.slice(6)]
+ },
+ },
+ ],
+ build: {
+ outDir: path.join(directory, 'host'),
+ rolldownOptions: {
+ input,
+ preserveEntrySignatures: 'strict',
+ output: { entryFileNames: '[name].js' },
+ },
+ },
+ })
+}
+
+function routeDirectory(deployment: Deployment, screen: Screen) {
+ return deployment === 'shared' ? '.' : './' + screen
+}
+
+function shell(deployment: Deployment) {
+ const catalog = routeDirectory(deployment, 'query') + '/query.js'
+ const bookmarks = routeDirectory(deployment, 'paginated') + '/paginated.js'
+ return `
+Reading list
+
+
+`
+}
+
+async function buildRemotes({
+ root,
+ outDir,
+ included,
+ packageName,
+ owners,
+ packageScope,
+ pluggable,
+}: {
+ root: string
+ outDir: string
+ included: ReadonlyArray
+ packageName: Adapter
+ owners: ReadonlyArray
+ packageScope: string
+ pluggable: Adapter
+}) {
+ const entries = Object.fromEntries(
+ included.map((screen) => [screen, 'remote:' + screen]),
+ )
+ const belongs = (id: string) => owners.some((dir) => id.startsWith(dir))
+ const result = await build({
+ root,
+ configFile: false,
+ publicDir: false,
+ base: './',
+ logLevel: 'warn',
+ resolve: {
+ alias: {
+ '#catalog-hooks': path.join(
+ root,
+ 'src',
+ packageName === pluggable ? 'pluggable-catalog.ts' : 'v6-catalog.ts',
+ ),
+ '#query-hooks': path.join(
+ root,
+ 'src',
+ packageName === pluggable ? 'pluggable-query.ts' : 'v6-query.ts',
+ ),
+ },
+ },
+ plugins: [
+ {
+ name: 'microfrontend-routes',
+ enforce: 'pre',
+ resolveId(id, importer) {
+ if (id.startsWith('remote:'))
+ return path.join(root, 'src', 'remote.tsx') + '?' + id.slice(7)
+ if (id === '#screen') {
+ const screen = screens.find((name) =>
+ importer?.endsWith('?' + name),
+ )
+ assert.ok(screen, 'Missing remote screen in ' + importer)
+ return path.join(root, 'src', screen + '.tsx')
+ }
+ if (id === '#adapter')
+ return this.resolve(packageName, packageScope, { skipSelf: true })
+ return null
+ },
+ },
+ ],
+ build: {
+ outDir,
+ rolldownOptions: {
+ input: entries,
+ preserveEntrySignatures: 'allow-extension',
+ external: /^react(?:-dom)?(?:\/|$)/,
+ checks: { moduleLevelDirective: false },
+ output: {
+ entryFileNames: '[name].js',
+ chunkFileNames: '[name].js',
+ codeSplitting: {
+ groups: [
+ {
+ name: 'query-runtime',
+ test: belongs,
+ includeDependenciesRecursively: false,
+ },
+ ],
+ },
+ },
+ },
+ },
+ })
+ assert.ok('output' in result, 'Expected one build output for ' + packageName)
+ const chunks = result.output.filter((chunk) => chunk.type === 'chunk')
+ const runtime = chunks.find((chunk) => chunk.name === 'query-runtime')
+ assert.ok(runtime, 'Missing Query runtime for ' + packageName)
+ const modules = Object.entries(runtime.modules).filter(
+ ([, mod]) => mod.renderedLength > 0,
+ )
+ assert.ok(modules.every(([id]) => belongs(id)))
+ for (const owner of owners)
+ assert.ok(modules.some(([id]) => id.startsWith(owner)))
+ for (const chunk of chunks.filter((item) => item !== runtime)) {
+ assert.ok(
+ !Object.entries(chunk.modules).some(
+ ([id, mod]) => mod.renderedLength && belongs(id),
+ ),
+ )
+ }
+ return gzipSync(runtime.code, { level: 9 }).length
+}
+
+export async function measureMicrofrontends({
+ root,
+ checkout,
+ baseCheckout,
+ baseline,
+ pluggable,
+ runtimeOwners,
+ formatChange,
+}: {
+ root: string
+ checkout: string
+ baseCheckout?: string
+ baseline: Adapter
+ pluggable: Adapter
+ runtimeOwners: (directory: string, adapter: Adapter) => ReadonlyArray
+ formatChange: (bytes: number, baselineBytes: number) => string
+}) {
+ const directory = path.join(root, 'dist', 'microfrontends')
+ await buildHost(root, directory)
+ const results: Array = []
+ for (const deployment of deployments) {
+ async function measureAdapter(packageName: Adapter) {
+ const source =
+ packageName === baseline && baseCheckout ? baseCheckout : checkout
+ const name = path.basename(packageName)
+ const dir = path.join(directory, name, deployment)
+ const groups =
+ deployment === 'shared'
+ ? [screens]
+ : screens.map((screen) => [screen] as const)
+ let catalog = 0
+ let journey = 0
+ for (const included of groups) {
+ const prefix = routeDirectory(deployment, included[0])
+ const size = await buildRemotes({
+ root,
+ outDir: path.join(dir, prefix),
+ included,
+ packageName,
+ pluggable,
+ packageScope: path.join(source, 'packages', name, 'package.json'),
+ owners: runtimeOwners(source, packageName),
+ })
+ if (included.includes('query')) catalog = size
+ journey += size
+ }
+ await mkdir(dir, { recursive: true })
+ await cp(path.join(root, 'public'), dir, { recursive: true })
+ await writeFile(path.join(dir, 'index.html'), shell(deployment))
+ return { catalog, journey }
+ }
+ const stock = await measureAdapter(baseline)
+ const experimental = await measureAdapter(pluggable)
+ for (const [key, journey] of [
+ ['catalog', 'Catalog only'],
+ ['journey', 'Catalog then bookmarks'],
+ ] as const) {
+ const base = stock[key]
+ const experiment = experimental[key]
+ const label =
+ deployment === 'shared' ? 'Shared Query chunk' : 'Query per remote'
+ results.push(
+ `| ${label} | ${journey} | ${base.toLocaleString('en-US')} B | ${experiment.toLocaleString('en-US')} B | ${formatChange(experiment, base)} |`,
+ )
+ }
+ }
+ return [
+ '### Microfrontend navigation',
+ '',
+ 'Cumulative Query JavaScript (gzip) from a cold catalog visit through the first visit to bookmarks. Both remotes share host React and React DOM. The independent builds serve distinct Query URLs. The shared build serves one Query chunk containing the features used across both routes. Chromium checks the requested Query URLs on each visit and revisit.',
+ '',
+ '| Deployment | Journey | React Query v6 | React Query Pluggable | Change vs v6 |',
+ '| --- | --- | ---: | ---: | ---: |',
+ ...results,
+ ].join('\n')
+}
diff --git a/integrations/react/bundle-size/package.json b/integrations/react/bundle-size/package.json
new file mode 100644
index 00000000000..ce28804e3c9
--- /dev/null
+++ b/integrations/react/bundle-size/package.json
@@ -0,0 +1,30 @@
+{
+ "name": "@tanstack/query-integration-react-bundle-size",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "test:types": "tsc -b && node check-editor.ts",
+ "measure": "node measure.ts",
+ "test:browser": "vitest run --config vitest.browser.config.ts",
+ "test:browser:ui": "vitest --watch --ui --config vitest.browser.config.ts",
+ "browser:install": "playwright install --with-deps --only-shell chromium"
+ },
+ "dependencies": {
+ "@tanstack/react-query": "workspace:*",
+ "@tanstack/react-query-pluggable": "workspace:*",
+ "react": "catalog:",
+ "react-dom": "catalog:"
+ },
+ "devDependencies": {
+ "@types/node": "^24.19.2",
+ "@types/react": "catalog:",
+ "@types/react-dom": "catalog:",
+ "@vitest/browser-playwright": "5.0.5",
+ "@vitest/ui": "5.0.5",
+ "playwright": "1.65.1",
+ "rollup-plugin-visualizer": "7.1.1",
+ "typescript": "catalog:",
+ "vite": "^8.3.8",
+ "vitest": "^5.0.5"
+ }
+}
diff --git a/integrations/react/bundle-size/public/books-1.json b/integrations/react/bundle-size/public/books-1.json
new file mode 100644
index 00000000000..e64ec490101
--- /dev/null
+++ b/integrations/react/bundle-size/public/books-1.json
@@ -0,0 +1 @@
+{ "titles": ["Middlemarch", "Persuasion"], "next": 2 }
diff --git a/integrations/react/bundle-size/public/books-2.json b/integrations/react/bundle-size/public/books-2.json
new file mode 100644
index 00000000000..c58cb48908a
--- /dev/null
+++ b/integrations/react/bundle-size/public/books-2.json
@@ -0,0 +1 @@
+{ "titles": ["Villette", "North and South"], "next": null }
diff --git a/integrations/react/bundle-size/src/books.ts b/integrations/react/bundle-size/src/books.ts
new file mode 100644
index 00000000000..1e40818494a
--- /dev/null
+++ b/integrations/react/bundle-size/src/books.ts
@@ -0,0 +1,35 @@
+import type {
+ InfiniteData,
+ QueryKey,
+ UseInfiniteQueryOptions,
+ UseSuspenseInfiniteQueryOptions,
+} from '#adapter'
+
+export interface BookPage {
+ titles: string[]
+ next: number | null
+}
+
+export async function fetchBooks(
+ page: number,
+ signal: AbortSignal,
+): Promise {
+ const response = await fetch(`./books-${page}.json`, { signal })
+ if (!response.ok) throw new Error(`Could not load page ${page}`)
+ return response.json() as Promise
+}
+
+export type BookPagesOptions = UseInfiniteQueryOptions<
+ BookPage,
+ Error,
+ InfiniteData,
+ QueryKey,
+ number
+>
+export type SuspenseBookPagesOptions = UseSuspenseInfiniteQueryOptions<
+ BookPage,
+ Error,
+ InfiniteData,
+ QueryKey,
+ number
+>
diff --git a/integrations/react/bundle-size/src/lazy/index.html b/integrations/react/bundle-size/src/lazy/index.html
new file mode 100644
index 00000000000..3a83fc0e498
--- /dev/null
+++ b/integrations/react/bundle-size/src/lazy/index.html
@@ -0,0 +1,12 @@
+
+
+
+
+
+ Reading list
+
+
+
+
+
+
diff --git a/integrations/react/bundle-size/src/lazy/main.tsx b/integrations/react/bundle-size/src/lazy/main.tsx
new file mode 100644
index 00000000000..d62386360e1
--- /dev/null
+++ b/integrations/react/bundle-size/src/lazy/main.tsx
@@ -0,0 +1,80 @@
+import * as React from 'react'
+import { createRoot } from 'react-dom/client'
+import { QueryClient, QueryClientProvider } from '#adapter'
+import { ReadingList as Catalog } from '../query.tsx'
+
+const LazyBookmarks = React.lazy(() =>
+ import('../paginated.tsx').then(({ ReadingList }) => ({
+ default: ReadingList,
+ })),
+)
+const client = new QueryClient({
+ defaultOptions: { queries: { staleTime: Infinity } },
+})
+
+function Bookmarks() {
+ return (
+ Loading bookmarks…
}>
+
+
+ )
+}
+
+function Library() {
+ const [route, setRoute] = React.useState<'catalog' | 'bookmarks'>('catalog')
+ return (
+ <>
+
+ {route === 'catalog' ? 'Catalog' : 'Bookmarks'}
+ {route === 'catalog' ? : }
+ >
+ )
+}
+
+function ScrollingLibrary() {
+ const shelf = React.useRef(null)
+ const [showBookmarks, setShowBookmarks] = React.useState(false)
+ React.useEffect(() => {
+ const observer = new IntersectionObserver(([entry]) => {
+ if (entry.isIntersecting) {
+ setShowBookmarks(true)
+ observer.disconnect()
+ }
+ })
+ observer.observe(shelf.current!)
+ return () => observer.disconnect()
+ }, [])
+
+ return (
+ <>
+
+
+ Bookmarks
+ {showBookmarks && }
+
+ >
+ )
+}
+
+const scrollLayout =
+ new URLSearchParams(location.search).get('layout') === 'scroll'
+
+createRoot(document.getElementById('root')!).render(
+
+ {scrollLayout ? : }
+ ,
+)
diff --git a/integrations/react/bundle-size/src/main.tsx b/integrations/react/bundle-size/src/main.tsx
new file mode 100644
index 00000000000..9fa26663307
--- /dev/null
+++ b/integrations/react/bundle-size/src/main.tsx
@@ -0,0 +1,13 @@
+import * as React from 'react'
+import { createRoot } from 'react-dom/client'
+import { QueryClient, QueryClientProvider } from '#adapter'
+import { ReadingList } from '#screen'
+
+const client = new QueryClient()
+
+createRoot(document.getElementById('root')!).render(
+
+ Reading list
+
+ ,
+)
diff --git a/integrations/react/bundle-size/src/numeric-interval.ts b/integrations/react/bundle-size/src/numeric-interval.ts
new file mode 100644
index 00000000000..b22ad6afd12
--- /dev/null
+++ b/integrations/react/bundle-size/src/numeric-interval.ts
@@ -0,0 +1 @@
+export const interval = 250
diff --git a/integrations/react/bundle-size/src/options.tsx b/integrations/react/bundle-size/src/options.tsx
new file mode 100644
index 00000000000..2f275d731d9
--- /dev/null
+++ b/integrations/react/bundle-size/src/options.tsx
@@ -0,0 +1,68 @@
+import * as React from 'react'
+import { useMutation, useQueryClient } from '#adapter'
+import {
+ bookmarkScope,
+ previousPage,
+ refreshBookmarks,
+ selectTitles,
+} from '#feature-options'
+import { isError, isPending, useBookQuery } from '#query-hooks'
+import { fetchBooks } from './books.ts'
+
+function savedBooks(): string[] {
+ return JSON.parse(localStorage.getItem('bookmarks') ?? '[]') as string[]
+}
+
+export function ReadingList() {
+ const client = useQueryClient()
+ const [page, setPage] = React.useState(1)
+ const [events, setEvents] = React.useState([])
+ const books = useBookQuery({
+ queryKey: ['books', page],
+ queryFn: ({ signal }) => fetchBooks(page, signal),
+ select: selectTitles,
+ placeholderData: previousPage,
+ })
+ const saved = useBookQuery({ queryKey: ['bookmarks'], queryFn: savedBooks })
+ const bookmark = useMutation({
+ scope: bookmarkScope,
+ mutationFn: async (title: string) => {
+ setEvents((items) => [...items, `Saving ${title}`])
+ await Promise.resolve()
+ localStorage.setItem(
+ 'bookmarks',
+ JSON.stringify([...savedBooks(), title]),
+ )
+ setEvents((items) => [...items, `Saved ${title}`])
+ },
+ onSuccess: () => refreshBookmarks(client),
+ })
+ if (isPending(books)) return Loading books…
+ if (isError(books)) return {books.error.message}
+ return (
+ <>
+
+ {books.data.map((title) => (
+ - {title}
+ ))}
+
+ {books.isPlaceholderData && (
+ Showing the previous page
+ )}
+
+
+ Bookmarks: {saved.data?.join(', ')}
+
+ {events.map((event, index) => (
+ - {event}
+ ))}
+
+ >
+ )
+}
diff --git a/integrations/react/bundle-size/src/paginated.tsx b/integrations/react/bundle-size/src/paginated.tsx
new file mode 100644
index 00000000000..aeec60de82d
--- /dev/null
+++ b/integrations/react/bundle-size/src/paginated.tsx
@@ -0,0 +1,52 @@
+import * as React from 'react'
+import { queryOptions, mutationOptions, useMutation, useQuery } from '#adapter'
+import { isError, isFetching, isPending, useBookPages } from '#query-hooks'
+import { fetchBooks } from './books.ts'
+
+export function ReadingList() {
+ const books = useBookPages({
+ queryKey: ['books'],
+ queryFn: ({ pageParam, signal }) => fetchBooks(pageParam, signal),
+ initialPageParam: 1,
+ getNextPageParam: (lastPage) => lastPage.next,
+ })
+ const bookmark = useQuery(
+ queryOptions({
+ queryKey: ['bookmark'],
+ queryFn: () => localStorage.getItem('bookmark'),
+ }),
+ )
+ const save = useMutation(
+ mutationOptions({
+ mutationFn: async (title: string) =>
+ localStorage.setItem('bookmark', title),
+ onSuccess: () => bookmark.refetch(),
+ }),
+ )
+ if (isPending(books)) return Loading books…
+ if (isError(books)) return {books.error.message}
+ return (
+ <>
+ {bookmark.data && Bookmarked: {bookmark.data}
}
+
+ {books.data.pages
+ .flatMap((page) => page.titles)
+ .map((title) => (
+ -
+ {title}{' '}
+
+
+ ))}
+
+ {books.hasNextPage && (
+
+ )}
+ {save.isError && {save.error.message}
}
+ >
+ )
+}
diff --git a/integrations/react/bundle-size/src/pluggable-catalog.ts b/integrations/react/bundle-size/src/pluggable-catalog.ts
new file mode 100644
index 00000000000..6a31eb565d1
--- /dev/null
+++ b/integrations/react/bundle-size/src/pluggable-catalog.ts
@@ -0,0 +1,10 @@
+import { queryOptions, useQuery } from '#adapter'
+import type { UndefinedInitialDataOptions } from '#adapter'
+
+export function useBookQuery(
+ options: UndefinedInitialDataOptions,
+) {
+ return useQuery(queryOptions(options))
+}
+
+export { isError, isPending } from '#adapter'
diff --git a/integrations/react/bundle-size/src/pluggable-interval.ts b/integrations/react/bundle-size/src/pluggable-interval.ts
new file mode 100644
index 00000000000..ca450d5790b
--- /dev/null
+++ b/integrations/react/bundle-size/src/pluggable-interval.ts
@@ -0,0 +1,3 @@
+import { refetchInterval } from '#adapter'
+
+export const interval = refetchInterval(250)
diff --git a/integrations/react/bundle-size/src/pluggable-options.ts b/integrations/react/bundle-size/src/pluggable-options.ts
new file mode 100644
index 00000000000..803a35d3f9d
--- /dev/null
+++ b/integrations/react/bundle-size/src/pluggable-options.ts
@@ -0,0 +1,16 @@
+import {
+ invalidateQueries,
+ placeholderData,
+ select,
+ serialScope,
+} from '#adapter'
+import type { QueryClient } from '#adapter'
+import type { BookPage } from './books.ts'
+
+export const selectTitles = select((page: BookPage) => page.titles)
+export const previousPage = placeholderData(
+ (previous: BookPage | undefined) => previous,
+)
+export const bookmarkScope = serialScope('bookmarks')
+export const refreshBookmarks = (client: QueryClient) =>
+ invalidateQueries(client, { queryKey: ['bookmarks'] })
diff --git a/integrations/react/bundle-size/src/pluggable-query.ts b/integrations/react/bundle-size/src/pluggable-query.ts
new file mode 100644
index 00000000000..bf60d7a878f
--- /dev/null
+++ b/integrations/react/bundle-size/src/pluggable-query.ts
@@ -0,0 +1,29 @@
+import {
+ infiniteQueryOptions,
+ suspenseQueryOptions,
+ suspenseInfiniteQueryOptions,
+ useQuery,
+} from '#adapter'
+import type { UseSuspenseQueryOptions } from '#adapter'
+import type {
+ BookPage,
+ BookPagesOptions,
+ SuspenseBookPagesOptions,
+} from './books.ts'
+
+export function useSuspenseBookQuery(
+ options: UseSuspenseQueryOptions,
+) {
+ return useQuery(suspenseQueryOptions(options))
+}
+
+export function useBookPages(options: BookPagesOptions) {
+ return useQuery(infiniteQueryOptions(options))
+}
+
+export function useSuspenseBookPages(options: SuspenseBookPagesOptions) {
+ return useQuery(suspenseInfiniteQueryOptions(options))
+}
+
+export { isError, isPending, useBookQuery } from './pluggable-catalog.ts'
+export { isFetching } from '#adapter'
diff --git a/integrations/react/bundle-size/src/polling.tsx b/integrations/react/bundle-size/src/polling.tsx
new file mode 100644
index 00000000000..c3183c8839f
--- /dev/null
+++ b/integrations/react/bundle-size/src/polling.tsx
@@ -0,0 +1,92 @@
+import * as React from 'react'
+import { interval } from '#polling-option'
+import {
+ useBookPages,
+ useBookQuery,
+ useSuspenseBookPages,
+ useSuspenseBookQuery,
+} from '#query-hooks'
+import { fetchBooks } from './books.ts'
+import type { UseQueryResult } from '#adapter'
+import type { BookPage } from './books.ts'
+
+function options(name: string) {
+ return {
+ queryKey: ['books', name],
+ queryFn: ({
+ pageParam,
+ signal,
+ }: {
+ pageParam?: unknown
+ signal: AbortSignal
+ }) => fetchBooks(typeof pageParam === 'number' ? pageParam : 1, signal),
+ refetchInterval: interval,
+ refetchIntervalInBackground: true,
+ }
+}
+
+const pagination = {
+ initialPageParam: 1,
+ getNextPageParam: (page: BookPage) => page.next,
+}
+
+function BookRow({
+ label,
+ result,
+ page,
+}: {
+ label: string
+ result: Pick
+ page: BookPage | undefined
+}) {
+ return (
+
+ {label}: {page?.titles.join(', ')}{' '}
+ {result.dataUpdatedAt > 0 && (
+
+ )}
+
+ )
+}
+
+function SuspenseBook() {
+ const result = useSuspenseBookQuery(options('suspense'))
+ return
+}
+
+function SuspensePages() {
+ const result = useSuspenseBookPages({
+ ...options('suspense-infinite'),
+ ...pagination,
+ })
+ return (
+
+ )
+}
+
+export function ReadingList() {
+ const query = useBookQuery(options('query'))
+ const infinite = useBookPages({ ...options('infinite'), ...pagination })
+ return (
+
+
+
+ Loading suspense query…}>
+
+
+ Loading suspense pages…}>
+
+
+
+ )
+}
diff --git a/integrations/react/bundle-size/src/query.tsx b/integrations/react/bundle-size/src/query.tsx
new file mode 100644
index 00000000000..24899d1022d
--- /dev/null
+++ b/integrations/react/bundle-size/src/query.tsx
@@ -0,0 +1,19 @@
+import * as React from 'react'
+import { isError, isPending, useBookQuery } from '#catalog-hooks'
+import { fetchBooks } from './books.ts'
+
+export function ReadingList() {
+ const books = useBookQuery({
+ queryKey: ['books', 1],
+ queryFn: ({ signal }) => fetchBooks(1, signal),
+ })
+ if (isPending(books)) return Loading books…
+ if (isError(books)) return {books.error.message}
+ return (
+
+ {books.data.titles.map((title) => (
+ - {title}
+ ))}
+
+ )
+}
diff --git a/integrations/react/bundle-size/src/remote.tsx b/integrations/react/bundle-size/src/remote.tsx
new file mode 100644
index 00000000000..11308766250
--- /dev/null
+++ b/integrations/react/bundle-size/src/remote.tsx
@@ -0,0 +1,16 @@
+import * as React from 'react'
+import { createRoot } from 'react-dom/client'
+import { QueryClient, QueryClientProvider } from '#adapter'
+import { ReadingList } from '#screen'
+import type { MountRemote } from '../host/navigation.ts'
+
+export const mount: MountRemote = (container) => {
+ const root = createRoot(container)
+ const client = new QueryClient()
+ root.render(
+
+
+ ,
+ )
+ return () => root.unmount()
+}
diff --git a/integrations/react/bundle-size/src/screen-types.ts b/integrations/react/bundle-size/src/screen-types.ts
new file mode 100644
index 00000000000..af6ab547c21
--- /dev/null
+++ b/integrations/react/bundle-size/src/screen-types.ts
@@ -0,0 +1,6 @@
+// Vite resolves #screen to one of these modules for each browser build.
+export declare const ReadingList:
+ | typeof import('./query.tsx').ReadingList
+ | typeof import('./paginated.tsx').ReadingList
+ | typeof import('./polling.tsx').ReadingList
+ | typeof import('./options.tsx').ReadingList
diff --git a/integrations/react/bundle-size/src/v6-catalog.ts b/integrations/react/bundle-size/src/v6-catalog.ts
new file mode 100644
index 00000000000..b51fe308726
--- /dev/null
+++ b/integrations/react/bundle-size/src/v6-catalog.ts
@@ -0,0 +1,8 @@
+export { useQuery as useBookQuery } from '#adapter'
+
+export const isPending = (
+ result: T,
+): result is T & { isPending: true } => result.isPending
+export const isError = (
+ result: T,
+): result is T & { isError: true } => result.isError
diff --git a/integrations/react/bundle-size/src/v6-options.ts b/integrations/react/bundle-size/src/v6-options.ts
new file mode 100644
index 00000000000..a390f6d0c03
--- /dev/null
+++ b/integrations/react/bundle-size/src/v6-options.ts
@@ -0,0 +1,8 @@
+import type { QueryClient } from '#adapter'
+import type { BookPage } from './books.ts'
+
+export const selectTitles = (page: BookPage) => page.titles
+export const previousPage = (previous: BookPage | undefined) => previous
+export const bookmarkScope = { id: 'bookmarks' }
+export const refreshBookmarks = (client: QueryClient) =>
+ client.invalidateQueries({ queryKey: ['bookmarks'] })
diff --git a/integrations/react/bundle-size/src/v6-query.ts b/integrations/react/bundle-size/src/v6-query.ts
new file mode 100644
index 00000000000..f3c7f31f019
--- /dev/null
+++ b/integrations/react/bundle-size/src/v6-query.ts
@@ -0,0 +1,14 @@
+import { infiniteQueryOptions, useInfiniteQuery } from '#adapter'
+import type { BookPagesOptions } from './books.ts'
+
+export {
+ useSuspenseInfiniteQuery as useSuspenseBookPages,
+ useSuspenseQuery as useSuspenseBookQuery,
+} from '#adapter'
+
+export function useBookPages(options: BookPagesOptions) {
+ return useInfiniteQuery(infiniteQueryOptions(options))
+}
+
+export { isError, isPending, useBookQuery } from './v6-catalog.ts'
+export const isFetching = (result: { isFetching: boolean }) => result.isFetching
diff --git a/integrations/react/bundle-size/tsconfig.json b/integrations/react/bundle-size/tsconfig.json
new file mode 100644
index 00000000000..8c02fcb4c64
--- /dev/null
+++ b/integrations/react/bundle-size/tsconfig.json
@@ -0,0 +1,22 @@
+{
+ "compilerOptions": {
+ "target": "ES2024",
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "lib": ["ES2024", "DOM", "DOM.Iterable"],
+ "jsx": "react-jsx",
+ "strict": true,
+ "noEmit": true,
+ "outDir": "./.cache/test-types",
+ "skipLibCheck": true,
+ "allowImportingTsExtensions": true,
+ "erasableSyntaxOnly": true,
+ "verbatimModuleSyntax": true
+ },
+ "files": [],
+ "references": [
+ { "path": "./tsconfig.v6.json" },
+ { "path": "./tsconfig.pluggable.json" },
+ { "path": "./tsconfig.tools.json" }
+ ]
+}
diff --git a/integrations/react/bundle-size/tsconfig.pluggable.json b/integrations/react/bundle-size/tsconfig.pluggable.json
new file mode 100644
index 00000000000..debd6b78436
--- /dev/null
+++ b/integrations/react/bundle-size/tsconfig.pluggable.json
@@ -0,0 +1,15 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "paths": {
+ "#adapter": ["./node_modules/@tanstack/react-query-pluggable"],
+ "#catalog-hooks": ["./src/pluggable-catalog.ts"],
+ "#query-hooks": ["./src/pluggable-query.ts"],
+ "#feature-options": ["./src/pluggable-options.ts"],
+ "#polling-option": ["./src/pluggable-interval.ts"],
+ "#screen": ["./src/screen-types.ts"]
+ }
+ },
+ "include": ["src/**/*.ts", "src/**/*.tsx"],
+ "exclude": ["src/v6-*.ts", "src/numeric-interval.ts"]
+}
diff --git a/integrations/react/bundle-size/tsconfig.tools.json b/integrations/react/bundle-size/tsconfig.tools.json
new file mode 100644
index 00000000000..891fb8b62d9
--- /dev/null
+++ b/integrations/react/bundle-size/tsconfig.tools.json
@@ -0,0 +1,4 @@
+{
+ "extends": "./tsconfig.json",
+ "include": ["*.ts", "browser/**/*.ts", "host/**/*.ts"]
+}
diff --git a/integrations/react/bundle-size/tsconfig.v6.json b/integrations/react/bundle-size/tsconfig.v6.json
new file mode 100644
index 00000000000..a905219718e
--- /dev/null
+++ b/integrations/react/bundle-size/tsconfig.v6.json
@@ -0,0 +1,15 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "paths": {
+ "#adapter": ["./node_modules/@tanstack/react-query"],
+ "#catalog-hooks": ["./src/v6-catalog.ts"],
+ "#query-hooks": ["./src/v6-query.ts"],
+ "#feature-options": ["./src/v6-options.ts"],
+ "#polling-option": ["./src/numeric-interval.ts"],
+ "#screen": ["./src/screen-types.ts"]
+ }
+ },
+ "include": ["src/**/*.ts", "src/**/*.tsx"],
+ "exclude": ["src/pluggable-*.ts"]
+}
diff --git a/integrations/react/bundle-size/vitest.browser.config.ts b/integrations/react/bundle-size/vitest.browser.config.ts
new file mode 100644
index 00000000000..b200c327367
--- /dev/null
+++ b/integrations/react/bundle-size/vitest.browser.config.ts
@@ -0,0 +1,68 @@
+import assert from 'node:assert/strict'
+import { playwright } from '@vitest/browser-playwright'
+import { defineConfig } from 'vitest/config'
+
+interface PollingGate {
+ requested: PromiseWithResolvers
+ response: PromiseWithResolvers
+}
+
+declare module 'vitest/browser' {
+ interface BrowserCommands {
+ holdPollingBooks: (adapter: string) => Promise
+ waitForPollingRequest: (adapter: string) => Promise
+ releasePollingBooks: (adapter: string) => Promise
+ }
+}
+
+const pendingBooks = new Map()
+const booksUrl = (adapter: string) => `/polling/${adapter}/books-1.json`
+
+export default defineConfig({
+ root: import.meta.dirname,
+ // Serve the measured apps from disk, including their production JS chunks.
+ publicDir: 'dist',
+ plugins: [
+ {
+ name: 'hold-polling-fixtures',
+ configureServer(server) {
+ server.middlewares.use((request, response, next) => {
+ const gate = request.url && pendingBooks.get(request.url)
+ if (gate) {
+ gate.requested.resolve()
+ gate.response.promise.then(() => next(), next)
+ } else next()
+ })
+ },
+ },
+ ],
+ test: {
+ include: ['browser/*.test.ts'],
+ browser: {
+ enabled: true,
+ headless: true,
+ provider: playwright(),
+ instances: [{ browser: 'chromium' }],
+ commands: {
+ holdPollingBooks(_, adapter: string) {
+ pendingBooks.set(booksUrl(adapter), {
+ requested: Promise.withResolvers(),
+ response: Promise.withResolvers(),
+ })
+ },
+ waitForPollingRequest(_, adapter: string) {
+ const gate = pendingBooks.get(booksUrl(adapter))
+ assert(gate, 'Missing polling gate for ' + adapter)
+ return gate.requested.promise
+ },
+ releasePollingBooks(_, adapter: string) {
+ const url = booksUrl(adapter)
+ const gate = pendingBooks.get(url)
+ assert(gate, 'Missing polling gate for ' + adapter)
+ gate.response.resolve()
+ pendingBooks.delete(url)
+ },
+ },
+ },
+ },
+})
diff --git a/integrations/react/nodenext/README.md b/integrations/react/nodenext/README.md
index 0cbec8b73d7..f724b66634e 100644
--- a/integrations/react/nodenext/README.md
+++ b/integrations/react/nodenext/README.md
@@ -6,6 +6,8 @@ Checks that `@tanstack/react-query` resolves and emits declarations under `modul
- `src/hooks.ts` (ESM, since `package.json` sets `"type": "module"`) exports a hook that calls `useQuery`.
- `tsconfig.json` sets `module` and `moduleResolution` to `nodenext` with `declaration` and `emitDeclarationOnly`, so TypeScript writes declarations to `dist/`.
+- `src/sharedTypes.ts` augments each core’s `Register` independently, reads tagged keys through the matching client, and exports prepared query options through the published ESM entry points.
+- The emitted declarations for regular and conditionally skipped queries must refer to public package names so another project can resolve them after installation.
- The check runs with TypeScript 6, TypeScript 7.0, and TypeScript 7.1 (dev build) from the root `node_modules`.
- CI runs the `test:types` script, which runs `test:types:ts6`, `test:types:ts7`, and `test:types:ts71`.
diff --git a/integrations/react/nodenext/check-declarations.mjs b/integrations/react/nodenext/check-declarations.mjs
new file mode 100644
index 00000000000..b8196fc1566
--- /dev/null
+++ b/integrations/react/nodenext/check-declarations.mjs
@@ -0,0 +1,19 @@
+import assert from 'node:assert/strict'
+import { readFileSync } from 'node:fs'
+
+const types = readFileSync(
+ new URL('./dist/sharedTypes.d.ts', import.meta.url),
+ 'utf8',
+)
+const publicPackages = new Set([
+ '@tanstack/query-core',
+ '@tanstack/query-core-pluggable',
+ '@tanstack/react-query',
+ '@tanstack/react-query-pluggable',
+])
+for (const [, specifier] of types.matchAll(/import\(["']([^"']+)["']\)/g)) {
+ assert.ok(
+ publicPackages.has(specifier),
+ 'Private declaration import: ' + specifier,
+ )
+}
diff --git a/integrations/react/nodenext/package.json b/integrations/react/nodenext/package.json
index c587035a285..11983a461bb 100644
--- a/integrations/react/nodenext/package.json
+++ b/integrations/react/nodenext/package.json
@@ -4,12 +4,15 @@
"type": "module",
"scripts": {
"test:types": "pnpm run test:types:ts6 && pnpm run test:types:ts7 && pnpm run test:types:ts71",
- "test:types:ts6": "node ../../../node_modules/typescript/lib/tsc.js --pretty false --project tsconfig.json",
- "test:types:ts7": "node ../../../node_modules/typescript70/lib/tsc.js --pretty false --project tsconfig.json",
- "test:types:ts71": "node ../../../node_modules/typescript71/lib/tsc.js --pretty false --project tsconfig.json"
+ "test:types:ts6": "node ../../../node_modules/typescript/lib/tsc.js --pretty false --project tsconfig.json && node check-declarations.mjs",
+ "test:types:ts7": "node ../../../node_modules/typescript70/lib/tsc.js --pretty false --project tsconfig.json && node check-declarations.mjs",
+ "test:types:ts71": "node ../../../node_modules/typescript71/lib/tsc.js --pretty false --project tsconfig.json && node check-declarations.mjs"
},
"dependencies": {
- "@tanstack/react-query": "workspace:*"
+ "@tanstack/query-core": "workspace:*",
+ "@tanstack/query-core-pluggable": "workspace:*",
+ "@tanstack/react-query": "workspace:*",
+ "@tanstack/react-query-pluggable": "workspace:*"
},
"devDependencies": {
"@types/react": "^19.3.0"
diff --git a/integrations/react/nodenext/src/sharedTypes.ts b/integrations/react/nodenext/src/sharedTypes.ts
new file mode 100644
index 00000000000..0d82bc8ed74
--- /dev/null
+++ b/integrations/react/nodenext/src/sharedTypes.ts
@@ -0,0 +1,90 @@
+import { QueryClient as StockClient } from '@tanstack/query-core'
+import {
+ QueryClient,
+ getQueryData,
+ query,
+} from '@tanstack/query-core-pluggable'
+import { queryOptions as stockOptions } from '@tanstack/react-query'
+import {
+ infiniteQuery,
+ infiniteQueryOptions,
+ isSuccess,
+ queryOptions,
+ skipToken,
+ suspenseInfiniteQueryOptions,
+ suspenseQueryOptions,
+ useQuery,
+} from '@tanstack/react-query-pluggable'
+import type { QueryMeta as StockMeta } from '@tanstack/react-query'
+import type { QueryMeta as PluggableMeta } from '@tanstack/react-query-pluggable'
+
+declare module '@tanstack/query-core' {
+ interface Register {
+ queryMeta: { shelf: 'stock' }
+ }
+}
+declare module '@tanstack/query-core-pluggable' {
+ interface Register {
+ queryMeta: { shelf: 'pluggable' }
+ }
+}
+
+type Assert = Matches
+type Same = [A, B] extends [B, A] ? true : false
+
+export type AdapterMetadata = [
+ Assert>,
+ Assert>,
+]
+
+const options = { queryKey: ['book'], queryFn: () => 'Dune' }
+export const book = queryOptions(options)
+export const cachedBook: typeof book = { ...book, staleTime: 30_000 }
+const pageOptions = {
+ queryKey: ['books', 'pages'],
+ initialPageParam: 1,
+ queryFn: ({ pageParam }: { pageParam: number }) => ({
+ page: pageParam,
+ title: 'Dune',
+ }),
+ getNextPageParam: (lastPage: { page: number }) => lastPage.page + 1,
+}
+export const paged = infiniteQueryOptions(pageOptions)
+export const suspendedBook = suspenseQueryOptions(options)
+export const suspendedPages = suspenseInfiniteQueryOptions(pageOptions)
+export function optionalBook(enabled: boolean) {
+ return suspenseQueryOptions({
+ ...options,
+ queryFn: enabled ? options.queryFn : skipToken,
+ })
+}
+export function optionalPages(enabled: boolean) {
+ return suspenseInfiniteQueryOptions({
+ ...pageOptions,
+ queryFn: enabled ? pageOptions.queryFn : skipToken,
+ })
+}
+export const fromStock: string | undefined = new StockClient().getQueryData(
+ stockOptions(options).queryKey,
+)
+export const fromPluggable: string | undefined = getQueryData(
+ new QueryClient(),
+ book.queryKey,
+)
+
+export function useFirstBookPage() {
+ const feed = useQuery(paged)
+ if (isSuccess(feed)) {
+ const cursor: number | undefined = feed.data.pageParams[0]
+ return { cursor, first: feed.data.pages[0] }
+ }
+}
+
+export function readBook(client: QueryClient): Promise {
+ return query(client, book)
+}
+
+export async function readPageCursors(client: QueryClient): Promise {
+ const data = await infiniteQuery(client, paged)
+ return data.pageParams
+}
diff --git a/knip.config.ts b/knip.config.ts
index 802c9b9a485..79f6b779d35 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -1,6 +1,7 @@
import reactQueryDevtools from './packages/react-query-devtools/package.json'
import reactQueryNextExperimental from './packages/react-query-next-experimental/package.json'
import reactQueryPersistClient from './packages/react-query-persist-client/package.json'
+import reactQueryPluggable from './packages/react-query-pluggable/package.json'
import reactQuery from './packages/react-query/package.json'
import type { KnipConfig } from 'knip'
@@ -38,9 +39,24 @@ export default {
entry: ['src/v4/**/*.cjs', 'src/v5/**/*.cjs'],
ignore: ['**/__testfixtures__/**'],
},
+ 'packages/query-core-pluggable': {
+ // Copied v6 compatibility suites import helpers and types directly from these modules.
+ entry: [
+ 'src/infiniteQueryBehavior.ts',
+ 'src/notifyManager.ts',
+ 'src/query.ts',
+ 'src/timeoutManager.ts',
+ 'src/utils.ts',
+ ],
+ },
'packages/react-query': {
ignoreDependencies: optionalPeerDependencies(reactQuery),
},
+ 'packages/react-query-pluggable': {
+ // These internal imports are exercised by the upstream compatibility suites.
+ entry: ['src/suspense.ts', 'tests/compat-*.ts'],
+ ignoreDependencies: optionalPeerDependencies(reactQueryPluggable),
+ },
'packages/react-query-devtools': {
ignoreDependencies: optionalPeerDependencies(reactQueryDevtools),
},
diff --git a/nx.json b/nx.json
index 84ef0aa852b..741140b3dd6 100644
--- a/nx.json
+++ b/nx.json
@@ -24,6 +24,21 @@
"!{projectRoot}/tests/**/*",
"!{projectRoot}/eslint.config.js",
"!{projectRoot}/oxlint.config.ts"
+ ],
+ "reactQueryCompatibility": [
+ "{workspaceRoot}/scripts/test-react-query-compat.mjs",
+ "{workspaceRoot}/scripts/port-query-client-tests.mjs",
+ "{workspaceRoot}/scripts/port-query-projection-tests.mjs",
+ "{workspaceRoot}/scripts/port-query-result-tests.mjs",
+ "{workspaceRoot}/scripts/react-query-compat.config.ts",
+ "{workspaceRoot}/packages/query-core/src/__tests__/**/*",
+ "{workspaceRoot}/packages/query-core/vite.config.ts",
+ "{workspaceRoot}/packages/query-core-pluggable/tests/compat/*.patch",
+ "{workspaceRoot}/packages/react-query/src/__tests__/**/*",
+ "{workspaceRoot}/packages/react-query/test-setup.ts",
+ "{workspaceRoot}/packages/react-query/vite.config.ts",
+ "{workspaceRoot}/packages/query-persist-client-core/src/**/*",
+ "{workspaceRoot}/packages/query-test-utils/src/**/*"
]
},
"targetDefaults": {
diff --git a/packages/query-core-pluggable/README.md b/packages/query-core-pluggable/README.md
new file mode 100644
index 00000000000..115bfae6356
--- /dev/null
+++ b/packages/query-core-pluggable/README.md
@@ -0,0 +1,55 @@
+# @tanstack/query-core-pluggable
+
+An experimental ESM query and mutation cache for JavaScript and TypeScript. It provides the runtime for `@tanstack/react-query-pluggable` and can also be used directly.
+
+Create a `QueryClient` and pass it as the first argument to each operation. This example fetches a list of titles, then marks the matching cached queries stale.
+
+```ts
+import {
+ QueryClient,
+ query,
+ invalidateQueries,
+} from '@tanstack/query-core-pluggable'
+
+const client = new QueryClient()
+
+const titles = await query(client, {
+ queryKey: ['books', 'featured'],
+ queryFn: async (): Promise => {
+ const response = await fetch('/api/featured-titles')
+ if (!response.ok) throw new Error('Could not load featured titles')
+ return response.json()
+ },
+})
+
+await invalidateQueries(client, { queryKey: ['books'] })
+```
+
+Import `infiniteQuery` for pagination, `refetchInterval` for observer polling, or `getMutationCache` to access the client's mutation cache. Pass the same client to the React adapter's `QueryClientProvider` to share cached data between direct calls and components.
+
+Use `findCachedQuery(cache, filters)` to look up a key, `findCachedQueries(cache, filters)` to filter a cache, and `clearQueryCache(cache)` to remove its queries. The predicates `isQueryActive(query)`, `isQueryDisabled(query)`, `isQueryStatic(query)`, and `isQueryStale(query)` inspect individual queries. Import `fetchOptimistic(client, observer, options)` when an observer needs a result as soon as data becomes available during a fetch.
+
+For code that already holds a cache entry, import the operation that takes that entry directly.
+
+| v6 method | Pluggable import | Effect |
+| --------------------------- | ------------------------------ | ----------------------------------------------------------------------------- |
+| `entry.invalidate()` | `invalidateCachedQuery(entry)` | Marks the entry invalidated and notifies its observers. |
+| `entry.reset()` | `resetCachedQuery(entry)` | Cancels any active fetch and restores the entry's initial state. |
+| `entry.getObserversCount()` | `getQueryObserverCount(entry)` | Counts subscribed observers, including disabled observers. |
+| `entry.isFetched()` | `isQueryFetched(entry)` | Checks for a data or error update. Manual cache writes count as data updates. |
+
+The filtered client operations `invalidateQueries(client, filters)` and `resetQueries(client, filters)` also refetch eligible active matches by default.
+
+## Register application types
+
+Augment `Register` on `@tanstack/query-core-pluggable` to configure default errors, query and mutation keys, or metadata across the pluggable package pair.
+
+```ts
+import '@tanstack/query-core-pluggable'
+
+declare module '@tanstack/query-core-pluggable' {
+ interface Register {
+ queryMeta: { requestId?: string }
+ }
+}
+```
diff --git a/packages/query-core-pluggable/oxlint.config.ts b/packages/query-core-pluggable/oxlint.config.ts
new file mode 100644
index 00000000000..396987b4462
--- /dev/null
+++ b/packages/query-core-pluggable/oxlint.config.ts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'oxlint'
+import rootConfig from './root.oxlint.config.ts'
+
+export default defineConfig({
+ extends: [rootConfig],
+ settings: rootConfig.settings,
+})
diff --git a/packages/query-core-pluggable/package.json b/packages/query-core-pluggable/package.json
new file mode 100644
index 00000000000..4943f5c50a1
--- /dev/null
+++ b/packages/query-core-pluggable/package.json
@@ -0,0 +1,54 @@
+{
+ "name": "@tanstack/query-core-pluggable",
+ "version": "5.108.4",
+ "description": "Framework-agnostic query and mutation runtime with independently imported features",
+ "author": "tannerlinsley",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/TanStack/query.git",
+ "directory": "packages/query-core-pluggable"
+ },
+ "homepage": "https://tanstack.com/query",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/tannerlinsley"
+ },
+ "scripts": {
+ "clean": "premove ./build ./coverage ./dist-ts ./.cache/test-types",
+ "compile": "tsc --project tsconfig.json",
+ "test:oxlint": "oxlint ./src",
+ "test:types": "npm-run-all --serial test:types:*",
+ "test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts57 --tsBuildInfoFile .cache/test-types/ts57.tsbuildinfo",
+ "test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts58 --tsBuildInfoFile .cache/test-types/ts58.tsbuildinfo",
+ "test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts59 --tsBuildInfoFile .cache/test-types/ts59.tsbuildinfo",
+ "test:types:tscurrent": "tsc --project tsconfig.json --outDir .cache/test-types/tscurrent --tsBuildInfoFile .cache/test-types/tscurrent.tsbuildinfo",
+ "test:types:ts70": "node ../../node_modules/typescript70/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts70 --tsBuildInfoFile .cache/test-types/ts70.tsbuildinfo",
+ "test:types:ts71": "node ../../node_modules/typescript71/lib/tsc.js --project tsconfig.legacy.json --outDir .cache/test-types/ts71 --tsBuildInfoFile .cache/test-types/ts71.tsbuildinfo",
+ "test:lib": "vitest",
+ "test:lib:dev": "pnpm run test:lib --watch",
+ "test:build": "publint --strict && attw --pack --profile esm-only",
+ "build": "tsdown --tsconfig tsconfig.prod.json"
+ },
+ "type": "module",
+ "types": "./build/index.d.ts",
+ "main": "./build/index.js",
+ "react-native": "src/index.ts",
+ "exports": {
+ ".": {
+ "@tanstack/custom-condition": "./src/index.ts",
+ "types": "./build/index.d.ts",
+ "default": "./build/index.js"
+ },
+ "./package.json": "./package.json"
+ },
+ "sideEffects": false,
+ "files": [
+ "build",
+ "src",
+ "!src/__tests__"
+ ],
+ "devDependencies": {
+ "typescript": "catalog:"
+ }
+}
diff --git a/packages/query-core-pluggable/root.oxlint.config.ts b/packages/query-core-pluggable/root.oxlint.config.ts
new file mode 120000
index 00000000000..56565c65534
--- /dev/null
+++ b/packages/query-core-pluggable/root.oxlint.config.ts
@@ -0,0 +1 @@
+../../oxlint.config.ts
\ No newline at end of file
diff --git a/packages/query-core-pluggable/root.tsdown.config.js b/packages/query-core-pluggable/root.tsdown.config.js
new file mode 120000
index 00000000000..a997d5d337c
--- /dev/null
+++ b/packages/query-core-pluggable/root.tsdown.config.js
@@ -0,0 +1 @@
+../../scripts/getTsdownConfig.js
\ No newline at end of file
diff --git a/packages/query-core-pluggable/src/__tests__/cacheOperations.test.ts b/packages/query-core-pluggable/src/__tests__/cacheOperations.test.ts
new file mode 100644
index 00000000000..7a050069bb5
--- /dev/null
+++ b/packages/query-core-pluggable/src/__tests__/cacheOperations.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it, vi } from 'vitest'
+import {
+ QueryClient,
+ QueryObserver,
+ clearQueryClient,
+ getQueriesData,
+ getQueryCache,
+ getQueryObserverCount,
+ invalidateCachedQuery,
+ invalidateQueries,
+ isQueryFetched,
+ removeQueries,
+ resetCachedQuery,
+ setQueriesData,
+} from '..'
+import { getQueryData, getQueryState, setQueryData } from '../queryClient'
+
+describe('cache operations', () => {
+ it('applies imported cache operations to the supplied client', async () => {
+ const client = new QueryClient()
+ const otherClient = new QueryClient()
+ const filters = { queryKey: ['posts'] }
+ setQueryData(client, ['posts', 1], 2)
+ setQueryData(client, ['posts', 2], 3)
+ setQueryData(otherClient, ['posts', 1], 10)
+
+ setQueriesData(client, filters, (count = 0) => count * 2)
+ expect(getQueriesData(client, filters)).toStrictEqual([
+ [['posts', 1], 4],
+ [['posts', 2], 6],
+ ])
+ await invalidateQueries(client, { ...filters, refetchType: 'none' })
+ expect(getQueryState(client, ['posts', 1])?.isInvalidated).toBe(true)
+ removeQueries(client, filters)
+ expect(getQueriesData(client, filters)).toStrictEqual([])
+ expect(getQueryData(otherClient, ['posts', 1])).toBe(10)
+ })
+})
+
+describe('cached query operations', () => {
+ it('invalidates an observed query once without starting a fetch', () => {
+ const client = new QueryClient()
+ const queryFn = vi.fn<() => string>(() => 'fetched')
+ const options = {
+ queryKey: ['book'],
+ initialData: 'seed',
+ staleTime: Infinity,
+ queryFn,
+ }
+ const first = new QueryObserver(client, options)
+ const second = new QueryObserver(client, { ...options, enabled: false })
+ const entry = first.getCurrentQuery()
+
+ expect(getQueryObserverCount(entry)).toBe(0)
+ const unsubscribeFirst = first.subscribe(() => {})
+ const unsubscribeSecond = second.subscribe(() => {})
+ expect(getQueryObserverCount(entry)).toBe(2)
+
+ const actions: Array = []
+ const unsubscribeCache = getQueryCache(client).subscribe((event) => {
+ if (event.type === 'updated' && event.query === entry) {
+ actions.push(event.action.type)
+ }
+ })
+ invalidateCachedQuery(entry)
+ invalidateCachedQuery(entry)
+
+ expect(actions).toStrictEqual(['invalidate'])
+ expect(first.getCurrentResult().isStale).toBe(true)
+ expect(queryFn).not.toHaveBeenCalled()
+ expect(isQueryFetched(entry)).toBe(false)
+
+ unsubscribeCache()
+ unsubscribeSecond()
+ expect(getQueryObserverCount(entry)).toBe(1)
+ unsubscribeFirst()
+ expect(getQueryObserverCount(entry)).toBe(0)
+ clearQueryClient(client)
+ })
+
+ it('restores initial data and clears recorded fetches after success or failure', async () => {
+ const client = new QueryClient()
+ const queryFn = vi.fn<() => Promise>()
+ const entry = new QueryObserver(client, {
+ queryKey: ['book'],
+ initialData: 'seed',
+ initialDataUpdatedAt: 123,
+ retry: false,
+ queryFn,
+ }).getCurrentQuery()
+ const initialState = entry.state
+ expect(isQueryFetched(entry)).toBe(false)
+
+ queryFn.mockResolvedValueOnce('fresh')
+ await expect(entry.fetch()).resolves.toBe('fresh')
+ expect(isQueryFetched(entry)).toBe(true)
+ resetCachedQuery(entry)
+ expect(entry.state).toStrictEqual(initialState)
+ expect(isQueryFetched(entry)).toBe(false)
+
+ queryFn.mockRejectedValueOnce(new Error('offline'))
+ await expect(entry.fetch()).rejects.toThrow('offline')
+ expect(isQueryFetched(entry)).toBe(true)
+ resetCachedQuery(entry)
+ expect(entry.state).toStrictEqual(initialState)
+ expect(isQueryFetched(entry)).toBe(false)
+ expect(queryFn).toHaveBeenCalledTimes(2)
+ clearQueryClient(client)
+ })
+})
diff --git a/packages/query-core-pluggable/src/__tests__/getMutationCache.test.ts b/packages/query-core-pluggable/src/__tests__/getMutationCache.test.ts
new file mode 100644
index 00000000000..9796992740e
--- /dev/null
+++ b/packages/query-core-pluggable/src/__tests__/getMutationCache.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it, vi } from 'vitest'
+import {
+ MutationCache,
+ MutationObserver,
+ QueryClient,
+ dehydrate,
+ getMutationCache,
+ hydrate,
+} from '..'
+import {
+ clearQueryClient,
+ getQueryData,
+ isMutating,
+ mutationCacheKey,
+ resumePausedMutations,
+ setQueryData,
+} from '../queryClient'
+
+describe('getMutationCache', () => {
+ it('keeps query-only hydration, resume and clear free of mutation caches', async () => {
+ const server = new QueryClient()
+ const client = new QueryClient()
+ setQueryData(server, ['books'], ['Dune'])
+ hydrate(client, dehydrate(server))
+
+ expect(getQueryData(client, ['books'])).toStrictEqual(['Dune'])
+ expect(isMutating(client)).toBe(0)
+ await expect(resumePausedMutations(client)).resolves.toStrictEqual([])
+ clearQueryClient(client)
+ expect(getQueryData(client, ['books'])).toBeUndefined()
+ expect(server[mutationCacheKey]).toBeUndefined()
+ expect(client[mutationCacheKey]).toBeUndefined()
+ })
+
+ it('creates a stable cache per client and reuses it across mutations and clear', async () => {
+ const first = new QueryClient()
+ const second = new QueryClient()
+ const cache = getMutationCache(first)
+ const otherCache = getMutationCache(second)
+ expect(cache).not.toBe(otherCache)
+ const mutation = new MutationObserver(first, {
+ mutationFn: (title: string) => Promise.resolve(title),
+ })
+
+ await mutation.mutate('Dune')
+ expect(cache.getAll().map((entry) => entry.state.data)).toStrictEqual([
+ 'Dune',
+ ])
+ expect(otherCache.getAll()).toStrictEqual([])
+ clearQueryClient(first)
+ expect(cache.getAll()).toStrictEqual([])
+ expect(getMutationCache(first)).toBe(cache)
+ })
+
+ it('uses an injected cache for the first mutation and its callbacks', async () => {
+ const onSuccess = vi.fn<() => void>()
+ const cache = new MutationCache({ onSuccess })
+ const client = new QueryClient({ mutationCache: cache })
+ const mutation = new MutationObserver(client, {
+ mutationKey: ['save'],
+ mutationFn: () => Promise.resolve('saved'),
+ })
+
+ await mutation.mutate()
+ expect(onSuccess).toHaveBeenCalledTimes(1)
+ expect(getMutationCache(client)).toBe(cache)
+ expect(cache.find({ mutationKey: ['save'] })?.state.data).toBe('saved')
+ clearQueryClient(client)
+ expect(cache.getAll()).toStrictEqual([])
+ })
+})
diff --git a/packages/query-core-pluggable/src/__tests__/infiniteQuery.test.ts b/packages/query-core-pluggable/src/__tests__/infiniteQuery.test.ts
new file mode 100644
index 00000000000..e41f9b079ca
--- /dev/null
+++ b/packages/query-core-pluggable/src/__tests__/infiniteQuery.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, expectTypeOf, it, vi } from 'vitest'
+import {
+ QueryClient,
+ dehydrate,
+ getQueryCache,
+ hydrate,
+ infiniteQuery,
+ query,
+ refetchQueries,
+} from '..'
+import {
+ clearQueryClient,
+ getQueryData,
+ setQueryDefaults,
+} from '../queryClient'
+import type { InfiniteData } from '..'
+
+describe('infiniteQuery', () => {
+ it('retains the page fetcher if a cache listener replaces the query options', async () => {
+ const client = new QueryClient()
+ getQueryCache(client).subscribe((event) => {
+ if (event.type === 'updated' && event.action.type === 'fetch') {
+ event.query.setOptions({
+ ...event.query.options,
+ queryFn: () => 'replacement',
+ })
+ }
+ })
+ const pages = await infiniteQuery(client, {
+ queryKey: ['infinite'],
+ queryFn: ({ pageParam }) => pageParam,
+ initialPageParam: 0,
+ getNextPageParam: (lastPage) => lastPage + 1,
+ pages: 2,
+ })
+ expect(pages).toStrictEqual({ pages: [0, 1], pageParams: [0, 1] })
+
+ // An ordinary fetch looks up its query function when the retryer starts.
+ await expect(
+ query(client, { queryKey: ['ordinary'], queryFn: () => 'original' }),
+ ).resolves.toBe('replacement')
+ clearQueryClient(client)
+ })
+
+ it('refetches hydrated pages before any observer subscribes', async () => {
+ const server = new QueryClient()
+ const client = new QueryClient()
+ const queryKey = ['pages']
+ const fetchPage = vi.fn<(context: { pageParam?: unknown }) => number>(
+ ({ pageParam }) => (typeof pageParam === 'number' ? pageParam : -1),
+ )
+ const options = {
+ queryKey,
+ queryFn: fetchPage,
+ initialPageParam: 0,
+ getNextPageParam: (lastPage: number) => lastPage + 1,
+ pages: 2,
+ }
+
+ const promise = infiniteQuery(server, options)
+ expectTypeOf(promise).toEqualTypeOf>>()
+ expect(
+ fetchPage.mock.calls.map(([context]) => context.pageParam),
+ ).toStrictEqual([0])
+ await promise
+
+ setQueryDefaults(client, queryKey, options)
+ hydrate(client, dehydrate(server))
+ fetchPage.mockClear()
+ await refetchQueries(client, { queryKey })
+ expect(
+ fetchPage.mock.calls.map(([context]) => context.pageParam),
+ ).toStrictEqual([0, 1])
+ expect(getQueryData(client, queryKey)).toStrictEqual({
+ pages: [0, 1],
+ pageParams: [0, 1],
+ })
+ clearQueryClient(client)
+ clearQueryClient(server)
+ })
+})
diff --git a/packages/query-core-pluggable/src/__tests__/projection.test.ts b/packages/query-core-pluggable/src/__tests__/projection.test.ts
new file mode 100644
index 00000000000..d6c189617fa
--- /dev/null
+++ b/packages/query-core-pluggable/src/__tests__/projection.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it, vi } from 'vitest'
+import { QueryClient, QueryObserver, placeholderData, select } from '..'
+import { getQueryData, setQueryData, setQueryDefaults } from '../queryClient'
+
+describe('projection options', () => {
+ it('reuses a stable selector and placeholder factory when option pairs are recreated', () => {
+ const client = new QueryClient()
+ const placeholder = vi.fn<() => { count: number }>(() => ({ count: 1 }))
+ const count = vi.fn<(value: { count: number }) => number>(
+ (value) => value.count,
+ )
+ const options = () => ({
+ queryKey: ['count'],
+ queryFn: () => Promise.resolve({ count: 2 }),
+ placeholderData: placeholderData(placeholder),
+ select: select(count),
+ })
+ const observer = new QueryObserver(client, options())
+ expect(observer.getCurrentResult()).toMatchObject({
+ data: 1,
+ isPlaceholderData: true,
+ })
+ observer.setOptions(options())
+ expect(placeholder).toHaveBeenCalledTimes(1)
+ expect(count).toHaveBeenCalledTimes(1)
+ setQueryData(client, ['count'], { count: 2 })
+ observer.setOptions(options())
+ expect(observer.getCurrentResult()).toMatchObject({
+ data: 2,
+ isPlaceholderData: false,
+ })
+ })
+
+ it('keeps selection state and errors separate for observers sharing a default', () => {
+ const client = new QueryClient()
+ const transform = (value: unknown) => {
+ if (typeof value !== 'number') throw new TypeError('Expected a number')
+ return value * 2
+ }
+ setQueryDefaults(client, ['entry'], { select: select(transform) })
+ const a = new QueryObserver(client, {
+ queryKey: ['entry', 'a'],
+ queryFn: () => 2,
+ initialData: 2,
+ })
+ const b = new QueryObserver(client, {
+ queryKey: ['entry', 'b'],
+ queryFn: () => 'invalid',
+ initialData: 'invalid',
+ })
+ expect(a.getCurrentResult()).toMatchObject({ status: 'success', data: 4 })
+ expect(b.getCurrentResult()).toMatchObject({
+ status: 'error',
+ data: undefined,
+ error: expect.any(TypeError),
+ })
+ expect(getQueryData(client, ['entry', 'b'])).toBe('invalid')
+ })
+})
diff --git a/packages/query-core-pluggable/src/__tests__/queryResult.test-d.tsx b/packages/query-core-pluggable/src/__tests__/queryResult.test-d.tsx
new file mode 100644
index 00000000000..3dcff595f50
--- /dev/null
+++ b/packages/query-core-pluggable/src/__tests__/queryResult.test-d.tsx
@@ -0,0 +1,60 @@
+import { describe, expectTypeOf, it } from 'vitest'
+import {
+ isError,
+ isFetchPreviousPageError,
+ isFetchingNextPage,
+ isLoading,
+ isLoadingError,
+ isPending,
+ isRefetchError,
+ isSuccess,
+} from '../queryResult'
+import type {
+ DefinedQueryObserverResult,
+ InfiniteData,
+ InfiniteQueryObserverResult,
+ QueryObserverResult,
+} from '../types'
+
+describe('query result type guards', () => {
+ it('narrows regular, nullable, defined and infinite results without losing their types', () => {
+ const regular = {} as QueryObserverResult
+ if (isPending(regular)) {
+ expectTypeOf(regular.data).toEqualTypeOf()
+ expectTypeOf(regular.error).toEqualTypeOf()
+ }
+ if (isLoading(regular))
+ expectTypeOf(regular.fetchStatus).toEqualTypeOf<'fetching'>()
+ if (isError(regular))
+ expectTypeOf(regular.error).toEqualTypeOf()
+ if (isLoadingError(regular))
+ expectTypeOf(regular.data).toEqualTypeOf()
+ if (isRefetchError(regular))
+ expectTypeOf(regular.data).toEqualTypeOf()
+ if (!isPending(regular) && !isError(regular))
+ expectTypeOf(regular.data).toEqualTypeOf()
+ const selected = {} as DefinedQueryObserverResult<
+ string | undefined,
+ RangeError
+ >
+ if (isSuccess(selected))
+ expectTypeOf(selected.data).toEqualTypeOf()
+ const pages = {} as InfiniteQueryObserverResult<
+ InfiniteData,
+ RangeError
+ >
+ if (isSuccess(pages)) {
+ expectTypeOf(pages.data.pages).toEqualTypeOf>()
+ expectTypeOf(pages.data.pageParams).toEqualTypeOf>()
+ expectTypeOf(pages.fetchNextPage).toEqualTypeOf<
+ typeof pages.fetchPreviousPage
+ >()
+ }
+ if (isFetchPreviousPageError(pages)) {
+ expectTypeOf(pages.error).toEqualTypeOf()
+ expectTypeOf(pages.fetchDirection).toEqualTypeOf<'backward'>()
+ }
+ if (isFetchingNextPage(pages))
+ expectTypeOf(pages.fetchDirection).toEqualTypeOf<'forward'>()
+ })
+})
diff --git a/packages/query-core-pluggable/src/__tests__/queryResult.test.ts b/packages/query-core-pluggable/src/__tests__/queryResult.test.ts
new file mode 100644
index 00000000000..839906dfb8e
--- /dev/null
+++ b/packages/query-core-pluggable/src/__tests__/queryResult.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it, vi } from 'vitest'
+import {
+ InfiniteQueryObserver,
+ QueryClient,
+ QueryObserver,
+ setQueryData,
+} from '..'
+import {
+ isError,
+ isFetchNextPageError,
+ isFetchPreviousPageError,
+ isFetched,
+ isFetching,
+ isFetchingNextPage,
+ isFetchingPreviousPage,
+ isLoading,
+ isLoadingError,
+ isPaused,
+ isPending,
+ isRefetchError,
+ isRefetching,
+ isSuccess,
+} from '../queryResult'
+
+describe('query result helpers', () => {
+ it('subscribes to status when a consumer only reads isPending', () => {
+ const client = new QueryClient()
+ const queryKey = ['tracked']
+ const observer = new QueryObserver(client, {
+ queryKey,
+ queryFn: () => 'unused',
+ enabled: false,
+ })
+ const tracked = vi.fn<(key: string) => void>()
+ const initial = observer.trackResult(observer.getCurrentResult(), tracked)
+ expect(isPending(initial)).toBe(true)
+ expect(tracked.mock.calls).toStrictEqual([['status']])
+ const notify = vi.fn<() => void>()
+ const unsubscribe = observer.subscribe(notify)
+ try {
+ setQueryData(client, queryKey, 'first')
+ setQueryData(client, queryKey, 'second')
+ expect(notify).toHaveBeenCalledTimes(1)
+ const result = observer.getCurrentResult()
+ expect(isSuccess(result)).toBe(true)
+ expect(isFetched(result)).toBe(true)
+ expect(result.dataUpdateCount).toBe(2)
+ for (const field of [
+ 'isPending',
+ 'isSuccess',
+ 'isError',
+ 'isFetched',
+ 'isFetching',
+ 'isRefetching',
+ ])
+ expect(result).not.toHaveProperty(field)
+ } finally {
+ unsubscribe()
+ }
+ })
+
+ it('distinguishes a directional page request and error from a background refetch', async () => {
+ const request = Promise.withResolvers()
+ const observer = new InfiniteQueryObserver(new QueryClient(), {
+ queryKey: ['pages'],
+ initialPageParam: 1,
+ initialData: { pages: [1], pageParams: [1] },
+ staleTime: Infinity,
+ retry: false,
+ queryFn: () => request.promise,
+ getNextPageParam: (page) => page + 1,
+ })
+ const unsubscribe = observer.subscribe(() => {})
+ try {
+ const next = observer.fetchNextPage()
+ const fetching = observer.getCurrentResult()
+ expect(isFetching(fetching)).toBe(true)
+ expect(isFetchingNextPage(fetching)).toBe(true)
+ expect(isFetchingPreviousPage(fetching)).toBe(false)
+ expect(isRefetching(fetching)).toBe(false)
+ request.reject(new Error('page unavailable'))
+ const failed = await next
+ expect(failed.fetchDirection).toBe('forward')
+ expect(isError(failed)).toBe(true)
+ expect(isFetchNextPageError(failed)).toBe(true)
+ expect(isFetchPreviousPageError(failed)).toBe(false)
+ expect(isLoadingError(failed)).toBe(false)
+ expect(isRefetchError(failed)).toBe(false)
+ expect(isLoading(failed)).toBe(false)
+ expect(isPaused(failed)).toBe(false)
+ } finally {
+ unsubscribe()
+ }
+ })
+
+ it('keeps the direction of a failed first page when there is no data', async () => {
+ const observer = new InfiniteQueryObserver(new QueryClient(), {
+ queryKey: ['empty-pages'],
+ enabled: false,
+ initialPageParam: 0,
+ retry: false,
+ queryFn: () => Promise.reject(new Error('first request failed')),
+ getNextPageParam: () => undefined,
+ })
+ const unsubscribe = observer.subscribe(() => {})
+ try {
+ const failed = await observer.fetchPreviousPage()
+ expect(failed.data).toBeUndefined()
+ expect(isLoadingError(failed)).toBe(true)
+ expect(isRefetchError(failed)).toBe(false)
+ expect(isFetchPreviousPageError(failed)).toBe(true)
+ expect(isFetchNextPageError(failed)).toBe(false)
+ } finally {
+ unsubscribe()
+ }
+ })
+})
diff --git a/packages/query-core-pluggable/src/__tests__/refetchInterval.test.ts b/packages/query-core-pluggable/src/__tests__/refetchInterval.test.ts
new file mode 100644
index 00000000000..b9a89dc2a6c
--- /dev/null
+++ b/packages/query-core-pluggable/src/__tests__/refetchInterval.test.ts
@@ -0,0 +1,152 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ MutationObserver,
+ QueryClient,
+ QueryObserver,
+ environmentManager,
+ focusManager,
+ infiniteQuery,
+ refetchInterval,
+} from '..'
+
+const wasServer = environmentManager.isServer()
+
+describe('refetchInterval', () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ environmentManager.setIsServer(() => false)
+ focusManager.setFocused(true)
+ })
+
+ afterEach(() => {
+ focusManager.setFocused(undefined)
+ environmentManager.setIsServer(() => wasServer)
+ vi.useRealTimers()
+ })
+
+ it('keeps the timer cadence on rerender and stops on option removal or unsubscribe', async () => {
+ const queryFn = vi.fn<() => number>(() => 1)
+ const options = {
+ queryKey: ['orders'],
+ queryFn,
+ initialData: 1,
+ staleTime: Infinity,
+ }
+ const observer = new QueryObserver(new QueryClient(), {
+ ...options,
+ refetchInterval: refetchInterval(100),
+ })
+ const unsubscribe = observer.subscribe(() => {})
+ await vi.advanceTimersByTimeAsync(90)
+ observer.setOptions({ ...options, refetchInterval: refetchInterval(100) })
+ await vi.advanceTimersByTimeAsync(10)
+ expect(queryFn).toHaveBeenCalledTimes(1)
+
+ observer.setOptions({ ...options, refetchInterval: refetchInterval(50) })
+ await vi.advanceTimersByTimeAsync(50)
+ expect(queryFn).toHaveBeenCalledTimes(2)
+ observer.setOptions(options)
+ await vi.advanceTimersByTimeAsync(100)
+ expect(queryFn).toHaveBeenCalledTimes(2)
+
+ observer.setOptions({ ...options, refetchInterval: refetchInterval(50) })
+ unsubscribe()
+ await vi.advanceTimersByTimeAsync(100)
+ expect(queryFn).toHaveBeenCalledTimes(2)
+ })
+
+ it('respects data-dependent intervals, background changes and disabled observers', async () => {
+ const queryFn = vi.fn<() => number>(() => 2)
+ const options = {
+ queryKey: ['orders'],
+ queryFn,
+ initialData: 1,
+ staleTime: Infinity,
+ }
+ const client = new QueryClient()
+ const observer = new QueryObserver(client, {
+ ...options,
+ refetchInterval: (query) =>
+ refetchInterval(query.state.data === 1 ? 100 : false),
+ })
+ const unsubscribe = observer.subscribe(() => {})
+ focusManager.setFocused(false)
+ await vi.advanceTimersByTimeAsync(100)
+ expect(queryFn).not.toHaveBeenCalled()
+ observer.setOptions({
+ ...observer.options,
+ refetchIntervalInBackground: true,
+ })
+ await vi.advanceTimersByTimeAsync(300)
+ expect(queryFn).toHaveBeenCalledTimes(1)
+ observer.setOptions({
+ ...observer.options,
+ enabled: false,
+ refetchInterval: refetchInterval(100),
+ })
+ await vi.advanceTimersByTimeAsync(100)
+ expect(queryFn).toHaveBeenCalledTimes(1)
+ unsubscribe()
+ })
+
+ it('shares a default polling option without sharing its timers', async () => {
+ const client = new QueryClient({
+ defaultOptions: {
+ queries: { refetchInterval: refetchInterval(60), staleTime: Infinity },
+ },
+ })
+ const first = vi.fn<() => number>(() => 1)
+ const second = vi.fn<() => number>(() => 2)
+ const a = new QueryObserver(client, {
+ queryKey: ['a'],
+ queryFn: first,
+ initialData: 1,
+ })
+ const b = new QueryObserver(client, {
+ queryKey: ['b'],
+ queryFn: second,
+ initialData: 2,
+ })
+ const unsubscribeA = a.subscribe(() => {})
+ const unsubscribeB = b.subscribe(() => {})
+ await vi.advanceTimersByTimeAsync(60)
+ unsubscribeA()
+ await vi.advanceTimersByTimeAsync(60)
+ expect(first).toHaveBeenCalledTimes(1)
+ expect(second).toHaveBeenCalledTimes(2)
+ unsubscribeB()
+ })
+
+ it('keeps server rendering free of polling timers', async () => {
+ environmentManager.setIsServer(() => true)
+ const queryFn = vi.fn<() => number>(() => 1)
+ const observer = new QueryObserver(new QueryClient(), {
+ queryKey: ['orders'],
+ queryFn,
+ initialData: 1,
+ staleTime: Infinity,
+ refetchInterval: refetchInterval(100),
+ })
+ const unsubscribe = observer.subscribe(() => {})
+ await vi.advanceTimersByTimeAsync(500)
+ expect(queryFn).not.toHaveBeenCalled()
+ unsubscribe()
+ })
+
+ it('supports mutations and infinite queries on a default client', async () => {
+ const client = new QueryClient()
+ const mutation = new MutationObserver(client, {
+ mutationFn: () => Promise.resolve(42),
+ })
+ await expect(mutation.mutate()).resolves.toBe(42)
+ await expect(
+ infiniteQuery(client, {
+ queryKey: ['pages'],
+ initialPageParam: 1,
+ pages: 2,
+ queryFn: ({ pageParam }) => pageParam,
+ getNextPageParam: (page) => page + 1,
+ }),
+ ).resolves.toStrictEqual({ pages: [1, 2], pageParams: [1, 2] })
+ })
+})
diff --git a/packages/query-core-pluggable/src/__tests__/serialScope.test.ts b/packages/query-core-pluggable/src/__tests__/serialScope.test.ts
new file mode 100644
index 00000000000..d4b6889db23
--- /dev/null
+++ b/packages/query-core-pluggable/src/__tests__/serialScope.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest'
+import {
+ MutationObserver,
+ QueryClient,
+ dehydrate,
+ hydrate,
+ onlineManager,
+ serialScope,
+} from '..'
+import { clearQueryClient, resumePausedMutations } from '../queryClient'
+
+describe('serialScope', () => {
+ it('restores the queue from JSON and resumes its mutations in order', async () => {
+ const source = new QueryClient()
+ const started = Promise.withResolvers()
+ const release = Promise.withResolvers()
+ const events: Array = []
+ const target = new QueryClient({
+ defaultOptions: {
+ mutations: {
+ mutationFn: async (value) => {
+ events.push(`start ${value}`)
+ if (value === 1) {
+ started.resolve()
+ await release.promise
+ }
+ events.push(`finish ${value}`)
+ },
+ },
+ },
+ })
+ const wasOnline = onlineManager.isOnline()
+ try {
+ onlineManager.setOnline(false)
+ const observer = new MutationObserver(source, {
+ scope: serialScope('orders'),
+ mutationFn: (value: number) => Promise.resolve(value),
+ })
+ const first = observer.mutate(1)
+ const second = observer.mutate(2)
+ const snapshot = JSON.parse(JSON.stringify(dehydrate(source)))
+ expect(
+ snapshot.mutations.map((m: { scope: unknown }) => m.scope),
+ ).toStrictEqual([{ id: 'orders' }, { id: 'orders' }])
+
+ hydrate(target, snapshot)
+ onlineManager.setOnline(true)
+ const resumed = resumePausedMutations(target)
+ await started.promise
+ expect(events).toStrictEqual(['start 1'])
+ release.resolve()
+ await resumed
+ expect(events).toStrictEqual([
+ 'start 1',
+ 'finish 1',
+ 'start 2',
+ 'finish 2',
+ ])
+ await resumePausedMutations(source)
+ await Promise.all([first, second])
+ } finally {
+ release.resolve()
+ onlineManager.setOnline(wasOnline)
+ clearQueryClient(source)
+ clearQueryClient(target)
+ }
+ })
+})
diff --git a/packages/query-core-pluggable/src/cacheOperations.ts b/packages/query-core-pluggable/src/cacheOperations.ts
new file mode 100644
index 00000000000..2e3f39f87ac
--- /dev/null
+++ b/packages/query-core-pluggable/src/cacheOperations.ts
@@ -0,0 +1,280 @@
+import { notifyManager } from './notifyManager'
+import { invalidateCachedQuery, resetCachedQuery } from './query'
+import { findCachedQueries } from './queryCacheOperations'
+import { getQueryCache, setQueryData } from './queryClient'
+import { isQueryDisabled, isQueryStatic } from './queryPredicates'
+import { noop } from './utils'
+import type { QueryClient } from './queryClient'
+import type {
+ CancelOptions,
+ InvalidateOptions,
+ InvalidateQueryFilters,
+ QueryKey,
+ RefetchOptions,
+ RefetchQueryFilters,
+ ResetOptions,
+ SetDataOptions,
+} from './types'
+import type { QueryFilters, Updater } from './utils'
+
+/**
+ * Imperative (non-reactive) way to retrieve the cached data of multiple queries at once.
+ * Only queries matching the given filters are returned; if none match, an empty array is
+ * returned.
+ *
+ * Because the matched queries can hold data of different shapes (e.g. a broad filter can match
+ * queries with unrelated data types), the `TQueryFnData` generic defaults to `unknown` rather
+ * than being inferred. Passing a more specific type is a convenience for call sites that know
+ * every matched query holds the same shape — it is not checked against the actual cache
+ * contents.
+ * @param client - The client that owns the query cache.
+ * @param filters - The filters that select which queries to read.
+ * @returns An array of query key and data pairs. The data is `undefined` for a query with no cached data.
+ * @see {@link getQueryData}
+ * @example
+ * ```ts
+ * const data = getQueriesData(queryClient, { queryKey: ['posts'] })
+ * ```
+ */
+export function getQueriesData<
+ TQueryFnData = unknown,
+ TQueryFilters extends QueryFilters = QueryFilters,
+>(
+ client: QueryClient,
+ filters: TQueryFilters,
+): Array<[QueryKey, TQueryFnData | undefined]> {
+ return findCachedQueries(getQueryCache(client), filters).map(
+ ({ queryKey, state }) => {
+ const data = state.data as TQueryFnData | undefined
+ return [queryKey, data]
+ },
+ )
+}
+
+/**
+ * Synchronous way to immediately update the cached data of multiple queries at once, using
+ * filters or partial query key matching. Only queries that already exist and match the given
+ * filters are updated; no new cache entries are created. Internally this calls
+ * {@link setQueryData} for each matching query.
+ * @param client - The client that owns the query cache.
+ * @param filters - The filters that select which existing queries to update.
+ * @param updater - Either the new data, or a function that receives each matched query's current
+ * data (which may be `undefined`) and returns the new data.
+ * @param options - Set `updatedAt` to override the timestamp the written data is recorded with.
+ * @returns One `[queryKey, data]` tuple per matched query, in the same shape and with the same
+ * `undefined` case as {@link setQueryData}.
+ * @example
+ * ```ts
+ * setQueriesData(queryClient, { queryKey: ['posts'] }, (oldPosts) =>
+ * oldPosts ? oldPosts.filter((post) => post.id !== deletedId) : oldPosts)
+ * ```
+ */
+export function setQueriesData<
+ TQueryFnData,
+ TQueryFilters extends QueryFilters = QueryFilters,
+>(
+ client: QueryClient,
+ filters: TQueryFilters,
+ updater: Updater<
+ NoInfer | undefined,
+ NoInfer | undefined
+ >,
+ options?: SetDataOptions,
+): Array<[QueryKey, TQueryFnData | undefined]> {
+ return notifyManager.batch(() =>
+ findCachedQueries(getQueryCache(client), filters).map(({ queryKey }) => [
+ queryKey,
+ setQueryData(client, queryKey, updater, options),
+ ]),
+ )
+}
+
+/**
+ * Removes queries from the cache that match the given filters. Unlike
+ * {@link invalidateQueries} or {@link refetchQueries}, this removes
+ * matching queries from the cache instead of refetching them. Without filters, every query in
+ * the cache is removed.
+ * @param client - The client that owns the query cache.
+ * @param filters - The filters that select which queries to remove. Without filters, every query
+ * is removed.
+ * @example
+ * ```ts
+ * removeQueries(queryClient, { queryKey: ['posts'], exact: true })
+ * ```
+ */
+export function removeQueries(
+ client: QueryClient,
+ filters?: QueryFilters,
+): void {
+ const queryCache = getQueryCache(client)
+ notifyManager.batch(() => {
+ findCachedQueries(queryCache, filters).forEach((query) => {
+ queryCache.remove(query)
+ })
+ })
+}
+
+/**
+ * Resets queries matching the given filters back to their initial state (e.g. any
+ * `initialData`), notifying subscribers rather than removing them. Active queries among the
+ * matched set are then refetched, and the returned promise resolves once that refetch settles.
+ * @param client - The client that owns the query cache.
+ * @param filters - The filters that select which queries to reset. Without filters, every query
+ * is reset.
+ * @param options - Passed to the refetch of the active matched queries, e.g. `cancelRefetch` and
+ * `throwOnError`.
+ * @returns A promise that resolves once the refetch of the active matched queries settles.
+ * @example
+ * ```ts
+ * await resetQueries(queryClient, { queryKey: ['posts'], exact: true })
+ * ```
+ */
+export function resetQueries(
+ client: QueryClient,
+ filters?: QueryFilters,
+ options?: ResetOptions,
+): Promise {
+ const queryCache = getQueryCache(client)
+
+ return notifyManager.batch(() => {
+ const matched = findCachedQueries(queryCache, filters)
+ const queriesToRefetch = new Set(matched)
+ matched.forEach((query) => {
+ resetCachedQuery(query)
+ })
+ return refetchQueries(
+ client,
+ {
+ type: 'active',
+ predicate: (query) => queriesToRefetch.has(query),
+ },
+ options,
+ )
+ })
+}
+
+/**
+ * Cancels outgoing fetches for queries matching the given filters. Most useful when performing
+ * optimistic updates, since any outgoing refetch that resolves afterwards would otherwise
+ * overwrite the optimistic update. By default (`revert: true`), a cancelled query's data is
+ * reverted to its state before the outgoing fetch started.
+ *
+ * The returned promise never rejects, even if individual cancellations fail.
+ * @param client - The client that owns the query cache.
+ * @param filters - The filters that select which queries to cancel. Without filters, every query
+ * is cancelled.
+ * @param cancelOptions - Passed to each matched query's cancellation. `revert` defaults to
+ * `true`.
+ * @returns A promise that resolves once every cancellation has settled.
+ * @example
+ * ```ts
+ * await cancelQueries(queryClient, { queryKey: ['posts'], exact: true })
+ * ```
+ */
+export function cancelQueries(
+ client: QueryClient,
+ filters?: QueryFilters,
+ cancelOptions: CancelOptions = {},
+): Promise {
+ const defaultedCancelOptions = { revert: true, ...cancelOptions }
+
+ const promises = notifyManager.batch(() =>
+ findCachedQueries(getQueryCache(client), filters).map((query) =>
+ query.cancel(defaultedCancelOptions),
+ ),
+ )
+
+ return Promise.all(promises).then(noop, noop)
+}
+
+/**
+ * Marks queries matching the given filters as invalidated. Unlike
+ * {@link removeQueries}, invalidated queries stay in the cache.
+ *
+ * Unless `filters.refetchType` is `'none'`, matching queries are then refetched via
+ * {@link refetchQueries}, using `filters.refetchType` if set, otherwise
+ * `filters.type`, otherwise `'active'`.
+ * @param client - The client that owns the query cache.
+ * @param filters - The filters that select which queries to invalidate, plus `refetchType` to
+ * control which of them to refetch afterwards. Without filters, every query is invalidated.
+ * @param options - Passed to {@link refetchQueries}, e.g. `cancelRefetch` and
+ * `throwOnError`.
+ * @returns A promise that resolves once the refetch settles, or immediately if `refetchType` is
+ * `'none'`.
+ * @example
+ * ```ts
+ * await invalidateQueries(queryClient, { queryKey: ['posts'], refetchType: 'active' })
+ * ```
+ */
+export function invalidateQueries(
+ client: QueryClient,
+ filters?: InvalidateQueryFilters,
+ options?: InvalidateOptions,
+): Promise {
+ return notifyManager.batch(() => {
+ findCachedQueries(getQueryCache(client), filters).forEach((query) => {
+ invalidateCachedQuery(query)
+ })
+
+ if (filters?.refetchType === 'none') {
+ return Promise.resolve()
+ }
+ return refetchQueries(
+ client,
+ {
+ ...filters,
+ type: filters?.refetchType ?? filters?.type ?? 'active',
+ },
+ options,
+ )
+ })
+}
+
+/**
+ * Refetches queries matching the given filters, regardless of whether they are stale. Without
+ * filters, every query in the cache is refetched. Queries that are disabled, or static (only
+ * have observers with a static `staleTime`), are never refetched.
+ *
+ * By default (`cancelRefetch: true`), a currently running fetch is cancelled before the new
+ * one starts. The returned promise does not reject on individual query failures unless
+ * `throwOnError` is `true`.
+ *
+ * Initially paused fetches do not delay the returned promise. Their later errors are handled
+ * even when `throwOnError` is `true`.
+ * @param client - The client that owns the query cache.
+ * @param filters - The filters that select which queries to refetch. Without filters, every query
+ * in the cache is included.
+ * @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling
+ * it, and `throwOnError` to `true` to reject when a refetch that was not initially paused fails.
+ * @returns A promise that resolves once all matching refetches that were not initially paused
+ * have settled.
+ * @example
+ * ```ts
+ * // refetch all active queries partially matching a query key:
+ * await refetchQueries(queryClient, { queryKey: ['posts'], type: 'active' })
+ * ```
+ */
+export function refetchQueries(
+ client: QueryClient,
+ filters?: RefetchQueryFilters,
+ options?: RefetchOptions,
+): Promise {
+ const fetchOptions = {
+ ...options,
+ cancelRefetch: options?.cancelRefetch ?? true,
+ }
+ const promises = notifyManager.batch(() =>
+ findCachedQueries(getQueryCache(client), filters)
+ .filter((query) => !isQueryDisabled(query) && !isQueryStatic(query))
+ .map((query) => {
+ let promise = query.fetch(undefined, fetchOptions)
+ const isPaused = query.state.fetchStatus === 'paused'
+ if (!fetchOptions.throwOnError || isPaused) {
+ promise = promise.catch(noop)
+ }
+ return isPaused ? Promise.resolve() : promise
+ }),
+ )
+
+ return Promise.all(promises).then(noop)
+}
diff --git a/packages/query-core-pluggable/src/environmentManager.ts b/packages/query-core-pluggable/src/environmentManager.ts
new file mode 100644
index 00000000000..6cdede3a64a
--- /dev/null
+++ b/packages/query-core-pluggable/src/environmentManager.ts
@@ -0,0 +1,42 @@
+/**
+ * A function that returns whether the code is running on the server.
+ */
+export type IsServerValue = () => boolean
+
+const defaultIsServer = typeof window === 'undefined' || 'Deno' in globalThis
+
+let isServerFn: IsServerValue = () => defaultIsServer
+
+/**
+ * Returns whether the current runtime should be treated as a server environment.
+ * @returns `true` if the runtime is treated as a server.
+ */
+export const isServer = (): boolean => isServerFn()
+
+/**
+ * Manages how TanStack Query detects whether the current runtime should be treated as
+ * server-side, which disables scheduling refetch timers and changes the default `retry` count
+ * and `gcTime`. By default, the detection treats a missing `window` (or the presence of a
+ * `Deno` global) as server.
+ *
+ * Override this for runtimes where that default detection would give the wrong answer — for
+ * example, a Service Worker, where `window` is undefined even though the environment should
+ * behave like a client.
+ * @example
+ * ```ts
+ * import { environmentManager } from '@tanstack/query-core-pluggable'
+ *
+ * environmentManager.setIsServer(() => false)
+ * ```
+ */
+export const environmentManager = {
+ isServer,
+ /**
+ * Overrides the server check globally.
+ * @param isServerValue - A function that returns whether the runtime should be treated as a
+ * server.
+ */
+ setIsServer(isServerValue: IsServerValue): void {
+ isServerFn = isServerValue
+ },
+}
diff --git a/packages/query-core-pluggable/src/fetchOptimistic.ts b/packages/query-core-pluggable/src/fetchOptimistic.ts
new file mode 100644
index 00000000000..b8ca97e8793
--- /dev/null
+++ b/packages/query-core-pluggable/src/fetchOptimistic.ts
@@ -0,0 +1,67 @@
+import { defaultQueryOptions, getQueryCache } from './queryClient'
+import type { QueryClient } from './queryClient'
+import type { ObserverOptionsInput, QueryObserver } from './queryObserver'
+import type { QueryKey, QueryObserverResult } from './types'
+
+/**
+ * Fetches a query defined by the given options without affecting this
+ * observer's own tracked query or result, and returns a promise that
+ * resolves with the `QueryObserverResult` for that fetch. This is useful
+ * for prefetching data that another observer (e.g. a query about to be
+ * navigated to) will need, ahead of time.
+ * @param client - The client that owns the observer and its query cache.
+ * @param observer - The observer that computes the result.
+ * @param options - The observer options of the query to fetch.
+ * @returns A promise that resolves with the result for the fetched query.
+ * @example
+ * ```ts
+ * const result = await fetchOptimistic(client, observer, {
+ * queryKey: ['posts', 2],
+ * queryFn: () => fetchPost(2),
+ * })
+ * console.log(result.data)
+ * ```
+ */
+export function fetchOptimistic<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryData,
+ TQueryKey extends QueryKey,
+>(
+ client: QueryClient,
+ observer: QueryObserver,
+ options: NoInfer<
+ ObserverOptionsInput
+ >,
+): Promise> {
+ const defaultedOptions = defaultQueryOptions(client, options)
+
+ const cache = getQueryCache(client)
+ const query = cache.build(client, defaultedOptions)
+
+ const cached = Promise.withResolvers>()
+ const unsubscribe = cache.subscribe((event) => {
+ if (
+ event.type === 'updated' &&
+ event.query.queryHash === query.queryHash &&
+ query.state.data !== undefined
+ ) {
+ unsubscribe()
+ cached.resolve(observer.createResult(query, defaultedOptions))
+ }
+ })
+
+ return Promise.race([
+ query
+ .fetch(defaultedOptions)
+ .then(() => {
+ const result = observer.createResult(query, defaultedOptions)
+ // Resolve the cache wait when the fetch succeeds.
+ cached.resolve(result)
+ return result
+ })
+ .finally(unsubscribe),
+ cached.promise,
+ ])
+}
diff --git a/packages/query-core-pluggable/src/focusManager.ts b/packages/query-core-pluggable/src/focusManager.ts
new file mode 100644
index 00000000000..6a434c80af4
--- /dev/null
+++ b/packages/query-core-pluggable/src/focusManager.ts
@@ -0,0 +1,144 @@
+import { Subscribable } from './subscribable'
+
+type Listener = (focused: boolean) => void
+
+type SetupFn = (
+ setFocused: (focused?: boolean) => void,
+) => (() => void) | undefined
+
+/**
+ * The `FocusManager` manages the focus state within TanStack Query.
+ *
+ * It can be used to change the default event listeners or to manually change the focus state.
+ */
+export class FocusManager extends Subscribable {
+ #focused?: boolean
+ #cleanup?: () => void
+
+ #setup: SetupFn
+
+ constructor() {
+ super()
+ this.#setup = (onFocus) => {
+ // addEventListener does not exist in React Native, but window does
+ // oxlint-disable-next-line typescript/no-unnecessary-condition
+ if (typeof window !== 'undefined' && window.addEventListener) {
+ const listener = () => onFocus()
+ // Listen to visibilitychange
+ window.addEventListener('visibilitychange', listener, false)
+
+ return () => {
+ // Be sure to unsubscribe if a new handler is set
+ window.removeEventListener('visibilitychange', listener)
+ }
+ }
+ return
+ }
+ }
+
+ protected override onSubscribe(): void {
+ if (!this.#cleanup) {
+ this.setEventListener(this.#setup)
+ }
+ }
+
+ protected override onUnsubscribe() {
+ if (!this.hasListeners()) {
+ this.#cleanup?.()
+ this.#cleanup = undefined
+ }
+ }
+
+ /**
+ * `setEventListener` can be used to set a custom event listener that will
+ * be used to determine the focus state. The provided `setup` function
+ * receives a `setFocused` callback: call it with a `boolean` to manually
+ * set the focus state, or with no arguments to re-evaluate the current
+ * focus state and notify subscribers.
+ * @param setup - Receives the `setFocused` callback, registers the event listener, and may return
+ * a cleanup function that is called when the listener is replaced or no longer needed.
+ * @example
+ * ```ts
+ * import { focusManager } from '@tanstack/query-core-pluggable'
+ *
+ * focusManager.setEventListener((handleFocus) => {
+ * const listener = () => handleFocus()
+ * // Listen to visibilitychange
+ * if (typeof window !== 'undefined' && window.addEventListener) {
+ * window.addEventListener('visibilitychange', listener, false)
+ * }
+ *
+ * return () => {
+ * // Be sure to unsubscribe if a new handler is set
+ * window.removeEventListener('visibilitychange', listener)
+ * }
+ * })
+ * ```
+ */
+ setEventListener(setup: SetupFn): void {
+ this.#setup = setup
+ this.#cleanup?.()
+ this.#cleanup = setup((focused) => {
+ if (typeof focused === 'boolean') {
+ this.setFocused(focused)
+ } else {
+ this.onFocus()
+ }
+ })
+ }
+
+ /**
+ * `setFocused` can be used to manually set the focus state. Set `undefined`
+ * to fall back to the default focus check.
+ * @param focused - The focus state, or `undefined` to use the default focus check.
+ * @example
+ * ```ts
+ * import { focusManager } from '@tanstack/query-core-pluggable'
+ *
+ * // Set focused
+ * focusManager.setFocused(true)
+ *
+ * // Set unfocused
+ * focusManager.setFocused(false)
+ *
+ * // Fallback to the default focus check
+ * focusManager.setFocused(undefined)
+ * ```
+ */
+ setFocused(focused?: boolean): void {
+ const changed = this.#focused !== focused
+ if (changed) {
+ this.#focused = focused
+ this.onFocus()
+ }
+ }
+
+ /**
+ * `onFocus` notifies all subscribed listeners with the current focus state.
+ */
+ onFocus(): void {
+ const isFocused = this.isFocused()
+ this.listeners.forEach((listener) => {
+ listener(isFocused)
+ })
+ }
+
+ /**
+ * `isFocused` can be used to get the current focus state.
+ * @returns The focus state set with `setFocused`, or otherwise whether the document is visible.
+ */
+ isFocused(): boolean {
+ if (typeof this.#focused === 'boolean') {
+ return this.#focused
+ }
+
+ // document global can be unavailable in react native
+ // oxlint-disable-next-line typescript/no-unnecessary-condition
+ return globalThis.document?.visibilityState !== 'hidden'
+ }
+}
+
+/**
+ * Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query.
+ */
+export const focusManager = new FocusManager()
diff --git a/packages/query-core-pluggable/src/hydration.ts b/packages/query-core-pluggable/src/hydration.ts
new file mode 100644
index 00000000000..ff543b6bc37
--- /dev/null
+++ b/packages/query-core-pluggable/src/hydration.ts
@@ -0,0 +1,461 @@
+import { createInfiniteFetch } from './infiniteQueryBehavior'
+import { Mutation } from './mutation'
+import {
+ getDefaultOptions,
+ getQueryCache,
+ mutationCacheKey,
+} from './queryClient'
+import { serialScope } from './serialScope'
+import { noop } from './utils'
+import type { MutationState } from './mutation'
+import type { Query, QueryState } from './query'
+import type { QueryClient } from './queryClient'
+import type {
+ DefaultError,
+ MutationKey,
+ MutationMeta,
+ MutationOptions,
+ MutationScope,
+ QueryKey,
+ QueryMeta,
+ QueryOptions,
+} from './types'
+
+interface DehydratedMutation {
+ mutationKey?: MutationKey
+ state: MutationState
+ meta?: MutationMeta
+ scope?: MutationScope
+}
+
+interface DehydratedQuery {
+ queryHash: string
+ queryKey: QueryKey
+ state: QueryState
+ dehydratedAt: number
+ promise?: Promise
+ meta?: QueryMeta
+ queryType?: 'infinite'
+}
+
+// TYPES
+type TransformerFn = (data: any) => any
+
+/**
+ * Options for `dehydrate`, controlling which queries/mutations are included in the resulting `DehydratedState` and
+ * how their data/errors are transformed before being serialized (e.g. for embedding in server-rendered markup).
+ */
+export interface DehydrateOptions {
+ /** Transforms a query's `data` before it is dehydrated. Useful for non-JSON-serializable data. */
+ serializeData?: TransformerFn
+ /** Predicate to decide whether a given `Mutation` should be dehydrated. Defaults to `defaultShouldDehydrateMutation`. */
+ shouldDehydrateMutation?: (mutation: Mutation) => boolean
+ /** Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. */
+ shouldDehydrateQuery?: (query: Query) => boolean
+ /**
+ * Predicate to decide whether a query's error should be redacted before dehydration. Errors are redacted
+ * (replaced with a generic `Error('redacted')`) unless this function is provided and returns `false` for the
+ * given error, in which case the original error is kept.
+ */
+ shouldRedactErrors?: (error: unknown) => boolean
+}
+
+/**
+ * Options for `hydrate`, controlling the default options applied to queries/mutations restored from a
+ * `DehydratedState`, and how to reverse any transformation applied by `DehydrateOptions.serializeData`.
+ */
+export interface HydrateOptions {
+ /** Options applied to the queries and mutations restored from the dehydrated state. */
+ defaultOptions?: {
+ /** Transforms a query's `data` after it is read from the dehydrated state, reversing `serializeData`. */
+ deserializeData?: TransformerFn
+ /** Default options merged into every query restored from the dehydrated state. */
+ queries?: QueryOptions
+ /** Default options merged into every mutation restored from the dehydrated state. */
+ mutations?: MutationOptions
+ }
+}
+
+/**
+ * Reads the value of a promise synchronously if it has already resolved, e.g. a thenable that
+ * resolves within its `then` call.
+ * @param promise - The promise to read.
+ * @returns An object with the resolved `data`, or `undefined` if the promise hasn't resolved
+ * synchronously (or resolved with `undefined`).
+ */
+function tryResolveSync(promise: PromiseLike) {
+ let data: unknown
+
+ const thenResult = promise.then((result) => {
+ data = result
+ return result
+ }, noop) as Partial> | undefined
+
+ // A synchronous thenable may return an object without a catch method.
+ thenResult?.catch?.(noop)
+
+ if (data !== undefined) {
+ return { data }
+ }
+
+ return undefined
+}
+
+// FUNCTIONS
+
+/**
+ * Dehydrates a single `Mutation` into a serializable snapshot of its key, state, scope, and meta.
+ * @param mutation - The mutation to dehydrate.
+ * @returns The dehydrated mutation.
+ */
+function dehydrateMutation(mutation: Mutation): DehydratedMutation {
+ return {
+ mutationKey: mutation.options.mutationKey,
+ state: mutation.state,
+ ...(mutation.options.scope && { scope: { id: mutation.options.scope.id } }),
+ ...(mutation.meta && { meta: mutation.meta }),
+ }
+}
+
+/**
+ * Prepares the in-flight promise of a pending query for dehydration: applies `serializeData` to its
+ * result, and redacts its rejection error unless `shouldRedactErrors` returns `false` for it.
+ * @param query - The pending query whose promise is dehydrated.
+ * @param serializeData - Optional transform applied to the resolved data.
+ * @param shouldRedactErrors - Optional predicate; if it returns `false` for the rejection error,
+ * that
+ * error is kept as-is instead of being redacted.
+ * @returns The transformed promise, or `undefined` if the query has no in-flight promise.
+ */
+function dehydratePromise(
+ query: Query,
+ serializeData?: TransformerFn,
+ shouldRedactErrors?: (error: unknown) => boolean,
+): Promise | undefined {
+ const promise = query.promise?.then(serializeData).catch((error) => {
+ if (shouldRedactErrors?.(error) === false) {
+ // Reject original error if it should not be redacted
+ return Promise.reject(error)
+ }
+ // If not in production, log original error before rejecting redacted error
+ if (process.env.NODE_ENV !== 'production') {
+ console.error(
+ `A query that was dehydrated as pending ended up rejecting. [${query.queryHash}]: ${error}; The error will be redacted in production builds`,
+ )
+ }
+ return Promise.reject(new Error('redacted'))
+ })
+
+ // Avoid unhandled promise rejections
+ // We need the promise we dehydrate to reject to get the correct result into
+ // the query cache, but we also want to avoid unhandled promise rejections
+ // in whatever environment the prefetches are happening in.
+ promise?.catch(noop)
+
+ return promise
+}
+
+/**
+ * Dehydrates a single `Query` into a serializable `DehydratedQuery` snapshot. Note that most query config (e.g.
+ * `queryFn`, `staleTime`) is not dehydrated but instead meant to be configured again when consuming the
+ * de/rehydrated data, typically with `useQuery` on the client. If the query is still `pending`, its in-flight
+ * promise is dehydrated too so it can be resumed on the other side instead of re-fetched.
+ * @param query - The query to dehydrate.
+ * @param serializeData - Optional transform applied to `query.state.data` before it is included in the snapshot.
+ * @param shouldRedactErrors - Optional predicate; if it returns `false` for the promise's rejection error, that
+ * error is kept as-is instead of being redacted.
+ * @returns The dehydrated query.
+ */
+export function dehydrateQuery(
+ query: Query,
+ serializeData?: TransformerFn,
+ shouldRedactErrors?: (error: unknown) => boolean,
+): DehydratedQuery {
+ return {
+ dehydratedAt: Date.now(),
+ state: {
+ ...query.state,
+ ...(query.state.data !== undefined && {
+ data: serializeData
+ ? serializeData(query.state.data)
+ : query.state.data,
+ }),
+ },
+ queryKey: query.queryKey,
+ queryHash: query.queryHash,
+ ...(query.state.status === 'pending' && {
+ promise: dehydratePromise(query, serializeData, shouldRedactErrors),
+ }),
+ ...(query.meta && { meta: query.meta }),
+ ...(query.queryType && { queryType: query.queryType }),
+ }
+}
+
+/**
+ * The default `shouldDehydrateMutation` predicate used by `dehydrate`. Only dehydrates mutations that are
+ * currently paused (e.g. paused by `networkMode` while offline).
+ * @param mutation - The mutation to check.
+ * @returns `true` if the mutation is paused.
+ */
+export function defaultShouldDehydrateMutation(mutation: Mutation) {
+ return mutation.state.isPaused
+}
+
+/**
+ * The default `shouldDehydrateQuery` predicate used by `dehydrate`. Only dehydrates queries whose status is
+ * `'success'`.
+ * @param query - The query to check.
+ * @returns `true` if the query's status is `'success'`.
+ */
+export function defaultShouldDehydrateQuery(query: Query) {
+ return query.state.status === 'success'
+}
+
+/**
+ * Dehydrates a `QueryClient`'s cache (queries and mutations) into a plain, serializable `DehydratedState`,
+ * typically to embed in server-rendered markup and later restore into a client-side `QueryClient` via `hydrate`.
+ * Which queries/mutations are included, and how their data/errors are transformed, is controlled by `options`,
+ * falling back to the client's `dehydrate` default options, and finally to `defaultShouldDehydrateQuery` /
+ * `defaultShouldDehydrateMutation`.
+ * @param client - The client whose cache is dehydrated.
+ * @param options - Controls which queries and mutations are included and how their data and errors
+ * are transformed. Each option falls back to the client's `defaultOptions.dehydrate`.
+ * @returns The dehydrated state, with the included `queries` and `mutations`.
+ * @example
+ * ```ts
+ * const queryClient = new QueryClient()
+ *
+ * await query(queryClient, {
+ * queryKey: ['posts'],
+ * queryFn: getPosts,
+ * })
+ *
+ * const dehydratedState = dehydrate(queryClient)
+ * ```
+ */
+export function dehydrate(
+ client: QueryClient,
+ options: DehydrateOptions = {},
+): DehydratedState {
+ const filterMutation =
+ options.shouldDehydrateMutation ??
+ getDefaultOptions(client).dehydrate?.shouldDehydrateMutation ??
+ defaultShouldDehydrateMutation
+
+ const mutations =
+ client[mutationCacheKey]
+ ?.getAll()
+ .flatMap((mutation) =>
+ filterMutation(mutation) ? [dehydrateMutation(mutation)] : [],
+ ) ?? []
+
+ const filterQuery =
+ options.shouldDehydrateQuery ??
+ getDefaultOptions(client).dehydrate?.shouldDehydrateQuery ??
+ defaultShouldDehydrateQuery
+
+ const shouldRedactErrors =
+ options.shouldRedactErrors ??
+ getDefaultOptions(client).dehydrate?.shouldRedactErrors
+
+ const serializeData =
+ options.serializeData ?? getDefaultOptions(client).dehydrate?.serializeData
+
+ const queries = getQueryCache(client)
+ .getAll()
+ .flatMap((query) =>
+ filterQuery(query)
+ ? [dehydrateQuery(query, serializeData, shouldRedactErrors)]
+ : [],
+ )
+
+ return { mutations, queries }
+}
+
+/**
+ * Restores a `DehydratedState` (as produced by `dehydrate`) into a `QueryClient`'s cache, typically to seed the
+ * client with data already fetched on the server. `mutations` and `queries` are each optional on `dehydratedState`.
+ * Queries not yet in the cache are built from the dehydrated snapshot; queries that already exist are only updated
+ * when the dehydrated data is newer than what's already cached. Newly built queries have their `fetchStatus` reset
+ * to `'idle'` so they don't hydrate stuck in a fetching state. If a dehydrated query still had an in-flight
+ * promise, it is resumed via `query.fetch()` (reusing that promise as `initialPromise`) rather than re-invoking
+ * `queryFn`.
+ * @param client - The client whose cache is restored into.
+ * @param dehydratedState - The dehydrated state, e.g. produced by `dehydrate` on the server.
+ * @param options - `defaultOptions` merged into every restored query and mutation (on top of the
+ * client's `defaultOptions.hydrate`), and `deserializeData` to reverse `serializeData`.
+ * @example
+ * ```ts
+ * // dehydratedState was produced by `dehydrate` on the server
+ * // and sent to the client, e.g. embedded in server-rendered markup.
+ * const queryClient = new QueryClient()
+ *
+ * hydrate(queryClient, dehydratedState)
+ * ```
+ */
+export function hydrate(
+ client: QueryClient,
+ dehydratedState: Partial,
+ options?: HydrateOptions,
+): void {
+ dehydratedState.mutations?.forEach(({ state, scope, ...mutationOptions }) => {
+ Mutation.build(
+ client,
+ {
+ ...getDefaultOptions(client).hydrate?.mutations,
+ ...options?.defaultOptions?.mutations,
+ ...mutationOptions,
+ ...(scope && { scope: serialScope(scope.id) }),
+ },
+ state,
+ )
+ })
+
+ if (dehydratedState.queries)
+ hydrateQueries(client, dehydratedState.queries, options)
+}
+
+/**
+ * Restores just the queries accepted by a React hydration boundary.
+ * @internal
+ * @param client - The client receiving the entries.
+ * @param queries - The serialized query entries.
+ * @param options - Query restoration settings.
+ */
+export function hydrateQueries(
+ client: QueryClient,
+ queries: Array,
+ options?: HydrateOptions,
+): void {
+ const queryCache = getQueryCache(client)
+ const deserializeData =
+ options?.defaultOptions?.deserializeData ??
+ getDefaultOptions(client).hydrate?.deserializeData
+
+ queries.forEach(
+ ({
+ queryKey,
+ state,
+ queryHash,
+ meta,
+ promise,
+ dehydratedAt,
+ queryType,
+ }) => {
+ const syncData = promise ? tryResolveSync(promise) : undefined
+ const rawData = state.data === undefined ? syncData?.data : state.data
+ const data =
+ rawData === undefined
+ ? rawData
+ : deserializeData
+ ? deserializeData(rawData)
+ : rawData
+
+ let query = queryCache.get(queryHash)
+ const existingQueryIsPending = query?.state.status === 'pending'
+ const existingQueryIsFetching = query?.state.fetchStatus === 'fetching'
+
+ // Do not hydrate if an existing query exists with newer data
+ if (query) {
+ const hasNewerSyncData =
+ syncData && dehydratedAt > query.state.dataUpdatedAt
+ if (
+ state.dataUpdatedAt > query.state.dataUpdatedAt ||
+ hasNewerSyncData
+ ) {
+ // Omit fetchStatus from dehydrated state so that query stays in its current fetchStatus
+ const { fetchStatus: _ignored, ...serializedState } = state
+ query.setState({
+ ...serializedState,
+ data,
+ // If the query was pending at the moment of dehydration, but resolved to have data
+ // before hydration, we can assume the query should be hydrated as successful.
+ //
+ // Since you can opt into dehydrating failed queries, and those can have data from
+ // previous successful fetches, we make sure we only do this for pending queries.
+ ...(state.status === 'pending' &&
+ data !== undefined && {
+ status: 'success' as const,
+ dataUpdatedAt: dehydratedAt,
+ // Preserve existing fetchStatus if the existing query is actively fetching.
+ ...(!existingQueryIsFetching && {
+ fetchStatus: 'idle' as const,
+ }),
+ }),
+ })
+ }
+ } else {
+ // Restore query
+ query = queryCache.build(
+ client,
+ {
+ ...getDefaultOptions(client).hydrate?.queries,
+ ...options?.defaultOptions?.queries,
+ queryKey,
+ queryHash,
+ meta,
+ ...(queryType === 'infinite' && {
+ _type: queryType,
+ _prepareInfiniteFetch: createInfiniteFetch,
+ }),
+ },
+ // Reset fetch status to idle to avoid
+ // query being stuck in fetching state upon hydration
+ {
+ ...state,
+ data,
+ fetchStatus: 'idle',
+ // Like above, if the query was pending at the moment of dehydration but has data,
+ // we can assume it should be hydrated as successful.
+ status:
+ state.status === 'pending' && data !== undefined
+ ? 'success'
+ : state.status,
+ ...(state.status === 'pending' &&
+ data !== undefined && {
+ dataUpdatedAt: dehydratedAt,
+ }),
+ },
+ )
+ }
+
+ if (
+ promise &&
+ // If the data was synchronously available, there is no need to set up
+ // a retryer and thus no reason to call fetch
+ !syncData &&
+ !existingQueryIsPending &&
+ !existingQueryIsFetching &&
+ // Only hydrate if dehydration is newer than any existing data,
+ // this is always true for new queries
+ dehydratedAt > query.state.dataUpdatedAt
+ ) {
+ // This doesn't actually fetch - it just creates a retryer
+ // which will re-use the passed `initialPromise`
+ query
+ .fetch(undefined, {
+ // RSC transformed promises are not thenable
+ initialPromise: Promise.resolve(promise).then(deserializeData),
+ })
+ // Avoid unhandled promise rejections
+ .catch(noop)
+ }
+ },
+ )
+}
+
+/**
+ * A serializable snapshot of a `QueryClient`'s cache, as produced by `dehydrate` and consumed by `hydrate`. Typically
+ * transported from server to client (e.g. embedded in server-rendered markup) to seed the client's cache with data
+ * that has already been fetched, avoiding a redundant fetch on the client.
+ */
+export interface DehydratedState {
+ /**
+ * The dehydrated mutations, by default only the paused ones.
+ */
+ mutations: Array
+ /**
+ * The dehydrated queries, by default only the successful ones.
+ */
+ queries: Array
+}
diff --git a/packages/query-core-pluggable/src/index.ts b/packages/query-core-pluggable/src/index.ts
new file mode 100644
index 00000000000..f84e385ca80
--- /dev/null
+++ b/packages/query-core-pluggable/src/index.ts
@@ -0,0 +1,236 @@
+/* istanbul ignore file */
+
+export {
+ getQueriesData,
+ setQueriesData,
+ removeQueries,
+ resetQueries,
+ cancelQueries,
+ invalidateQueries,
+ refetchQueries,
+} from './cacheOperations'
+export { environmentManager } from './environmentManager'
+export { infiniteQuery } from './infiniteQuery'
+export { fetchOptimistic } from './fetchOptimistic'
+export { focusManager } from './focusManager'
+export type { FocusManager } from './focusManager'
+export {
+ hydrateQueries,
+ defaultShouldDehydrateMutation,
+ defaultShouldDehydrateQuery,
+ dehydrate,
+ dehydrateQuery,
+ hydrate,
+} from './hydration'
+export type {
+ DehydratedState,
+ HydrateOptions,
+ DehydrateOptions,
+} from './hydration'
+export { InfiniteQueryObserver } from './infiniteQueryObserver'
+export { Mutation } from './mutation'
+export type { MutationState } from './mutation'
+export { MutationCache, getMutationCache } from './mutationCache'
+export type {
+ MutationCacheNotifyEvent,
+ MutationCacheConfig,
+} from './mutationCache'
+export { MutationObserver } from './mutationObserver'
+export { defaultScheduler, notifyManager } from './notifyManager'
+export { onlineManager } from './onlineManager'
+export type { OnlineManager } from './onlineManager'
+export { placeholderData } from './placeholderData'
+export type { Select, PlaceholderData } from './projectionTypes'
+export { QueriesObserver } from './queriesObserver'
+export type {
+ QueriesObserverOptions,
+ QueriesObserverResultReader,
+} from './queriesObserver'
+export { Query, invalidateCachedQuery, resetCachedQuery } from './query'
+export type { QueryState } from './query'
+export { QueryCache } from './queryCache'
+export {
+ clearQueryCache,
+ findCachedQuery,
+ findCachedQueries,
+} from './queryCacheOperations'
+export {
+ getQueryObserverCount,
+ isQueryFetched,
+ isQueryActive,
+ isQueryDisabled,
+ isQueryStale,
+ isQueryStatic,
+} from './queryPredicates'
+export type { QueryCacheNotifyEvent, QueryCacheConfig } from './queryCache'
+export {
+ getQueryCache,
+ mountQueryClient,
+ unmountQueryClient,
+ QueryClient,
+ countFetchingQueries,
+ isMutating,
+ getQueryData,
+ setQueryData,
+ getQueryState,
+ query,
+ resumePausedMutations,
+ getDefaultOptions,
+ setDefaultOptions,
+ setQueryDefaults,
+ getQueryDefaults,
+ setMutationDefaults,
+ getMutationDefaults,
+ defaultQueryOptions,
+ defaultMutationOptions,
+ clearQueryClient,
+} from './queryClient'
+export { QueryObserver } from './queryObserver'
+export type { QueryObserverResultReader } from './queryObserver'
+export {
+ isPending,
+ isSuccess,
+ isError,
+ isFetching,
+ isPaused,
+ isLoading,
+ isRefetching,
+ isLoadingError,
+ isRefetchError,
+ isFetched,
+ isFetchingNextPage,
+ isFetchingPreviousPage,
+ isFetchNextPageError,
+ isFetchPreviousPageError,
+} from './queryResult'
+export { refetchInterval } from './refetchInterval'
+export type { RefetchInterval } from './refetchInterval'
+export { CancelledError } from './retryer'
+export { select } from './select'
+export { serialScope } from './serialScope'
+export type { SerialScope } from './serialScope'
+export { streamedQuery } from './streamedQuery'
+export { timeoutManager } from './timeoutManager'
+export type {
+ TimeoutManager,
+ ManagedTimerId,
+ TimeoutCallback,
+ TimeoutProvider,
+} from './timeoutManager'
+export { dataTagSymbol, dataTagErrorSymbol, unsetMarker } from './types'
+export type {
+ OmitKeyof,
+ QueryKey,
+ QueryObserverResult,
+ DefaultedQueryObserverOptions,
+ ThrowOnError,
+ QueryErrorBoundaryOption,
+ QueryErrorBoundaryPolicy,
+ QueryFunction,
+ StaleTimeFunction,
+ QueryBooleanOption,
+ QueryPersister,
+ QueryFunctionContext,
+ PlaceholderDataFunction,
+ QueryOptions,
+ QueryObserverOptions,
+ InfiniteQueryObserverOptions,
+ DefaultedInfiniteQueryObserverOptions,
+ QueryExecuteOptions,
+ InfiniteQueryExecuteOptions,
+ InvalidateQueryFilters,
+ RefetchQueryFilters,
+ MutationFunctionContext,
+ MutationFunction,
+ MutationOptions,
+ MutationObserverOptions,
+ MutateOptions,
+ MutateFunctionRest,
+ MutateFunction,
+ MutationObserverBaseResult,
+ MutationObserverIdleResult,
+ MutationObserverLoadingResult,
+ MutationObserverErrorResult,
+ MutationObserverSuccessResult,
+ MutationObserverResult,
+ QueryClientConfig,
+ DefaultOptions,
+ NonUndefinedGuard,
+ DistributiveOmit,
+ Override,
+ Register,
+ DefaultError,
+ UnsetMarker,
+ AnyDataTag,
+ DataTag,
+ QueryKeyWithDataTag,
+ InferDataFromTag,
+ InferErrorFromTag,
+ StaleTime,
+ InitialDataFunction,
+ QueriesPlaceholderDataFunction,
+ EqualityFn,
+ CacheKeyHashFunction,
+ CacheKeyConfig,
+ GetPreviousPageParamFunction,
+ GetNextPageParamFunction,
+ InfiniteData,
+ QueryMeta,
+ NetworkMode,
+ NotifyOnChangeProps,
+ InitialPageParam,
+ InfiniteQueryPageParamsOptions,
+ WithRequired,
+ ResultOptions,
+ RefetchOptions,
+ InvalidateOptions,
+ ResetOptions,
+ FetchNextPageOptions,
+ FetchPreviousPageOptions,
+ QueryStatus,
+ FetchStatus,
+ QueryObserverBaseResult,
+ QueryObserverPendingResult,
+ QueryObserverLoadingResult,
+ QueryObserverLoadingErrorResult,
+ QueryObserverRefetchErrorResult,
+ QueryObserverSuccessResult,
+ QueryObserverPlaceholderResult,
+ DefinedQueryObserverResult,
+ InfiniteQueryObserverBaseResult,
+ InfiniteQueryObserverPendingResult,
+ InfiniteQueryObserverLoadingResult,
+ InfiniteQueryObserverLoadingErrorResult,
+ InfiniteQueryObserverRefetchErrorResult,
+ InfiniteQueryObserverSuccessResult,
+ InfiniteQueryObserverPlaceholderResult,
+ DefinedInfiniteQueryObserverResult,
+ InfiniteQueryObserverResult,
+ MutationKey,
+ MutationStatus,
+ MutationScope,
+ MutationMeta,
+ CancelOptions,
+ SetDataOptions,
+ NotifyEventType,
+ NotifyEvent,
+} from './types'
+export {
+ shouldThrowError,
+ hashKey,
+ noop,
+ partialMatchKey,
+ replaceEqualDeep,
+ defaultQueryFn,
+ skipToken,
+ keepPreviousData,
+ matchMutation,
+ matchQuery,
+} from './utils'
+export type {
+ DefaultQueryFn,
+ SkipToken,
+ Updater,
+ MutationFilters,
+ QueryFilters,
+} from './utils'
diff --git a/packages/query-core-pluggable/src/infiniteQuery.ts b/packages/query-core-pluggable/src/infiniteQuery.ts
new file mode 100644
index 00000000000..a901149cedf
--- /dev/null
+++ b/packages/query-core-pluggable/src/infiniteQuery.ts
@@ -0,0 +1,105 @@
+import { infiniteFetchOptions } from './infiniteQueryBehavior'
+import { query } from './queryClient'
+import type { QueryClient, WithoutSkipToken } from './queryClient'
+import type {
+ DefaultError,
+ InfiniteData,
+ InfiniteQueryExecuteOptions,
+ QueryKey,
+} from './types'
+
+/**
+ * Asynchronous method to fetch and cache an infinite query, resolving with an
+ * {@link InfiniteData} object or throwing with the error.
+ *
+ * Requires `initialPageParam` and `getNextPageParam`. Use `pages` to specify how many
+ * pages to fetch. If you omit `pages`, the client fetches up to the number of cached
+ * pages, or one page if the cache has no pages.
+ * If shared infinite query options contain `skipToken` as their `queryFn`, the call skips fetching
+ * and resolves with existing data or `undefined` on a cache miss. Use {@link getQueryData}
+ * to read the cache directly.
+ * @param client - The client that stores the query.
+ * @param options - The query to fetch and the options that control which pages to fetch.
+ * @returns A promise that resolves to the {@link InfiniteData}, or to the result of `select` if
+ * provided. It rejects with the error from the fetch or from `select`.
+ * @example
+ * ```ts
+ * try {
+ * const data = await infiniteQuery(queryClient, {
+ * queryKey,
+ * queryFn,
+ * initialPageParam: 0,
+ * getNextPageParam: (lastPage) => lastPage.nextCursor,
+ * })
+ * console.log(data.pages)
+ * } catch (error) {
+ * console.log(error)
+ * }
+ * ```
+ */
+export function infiniteQuery<
+ TQueryFnData,
+ TError = DefaultError,
+ TData = InfiniteData,
+ TQueryKey extends QueryKey = QueryKey,
+ TPageParam = unknown,
+>(
+ client: QueryClient,
+ options: WithoutSkipToken<
+ InfiniteQueryExecuteOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >
+ >,
+): Promise<
+ Array extends Array>
+ ? InfiniteData
+ : TData
+>
+export function infiniteQuery<
+ TQueryFnData,
+ TError = DefaultError,
+ TData = InfiniteData,
+ TQueryKey extends QueryKey = QueryKey,
+ TPageParam = unknown,
+>(
+ client: QueryClient,
+ options: InfiniteQueryExecuteOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >,
+): Promise<
+ | undefined
+ | (Array extends Array>
+ ? InfiniteData
+ : TData)
+>
+export function infiniteQuery<
+ TQueryFnData,
+ TError = DefaultError,
+ TData = InfiniteData,
+ TQueryKey extends QueryKey = QueryKey,
+ TPageParam = unknown,
+>(
+ client: QueryClient,
+ options: InfiniteQueryExecuteOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >,
+): Promise<
+ | undefined
+ | (Array extends Array>
+ ? InfiniteData
+ : TData)
+> {
+ return query(client, infiniteFetchOptions(options) as any)
+}
diff --git a/packages/query-core-pluggable/src/infiniteQueryBehavior.ts b/packages/query-core-pluggable/src/infiniteQueryBehavior.ts
new file mode 100644
index 00000000000..94b70bba2ef
--- /dev/null
+++ b/packages/query-core-pluggable/src/infiniteQueryBehavior.ts
@@ -0,0 +1,231 @@
+import {
+ addConsumeAwareSignal,
+ addToArray,
+ ensureQueryFn,
+ fetchSignal,
+} from './utils'
+import type { FetchContext, FetchOptions, Query } from './query'
+import type { QueryClient } from './queryClient'
+import type {
+ DefaultError,
+ InfiniteData,
+ InfiniteQueryPageParamsOptions,
+} from './types'
+import type { FetchSignalContext } from './utils'
+
+/**
+ * Captures the options and cached pages for this fetch before the cache notifies listeners.
+ * @param client - Client that owns the query.
+ * @param query - The cached infinite query.
+ * @param fetchOptions - Options for the fetch in progress.
+ * @param addSignal - Attaches the query's cancellation signal without consuming it.
+ * @returns The fetcher to use for the first attempt and subsequent retries.
+ */
+export function createInfiniteFetch(
+ client: QueryClient,
+ query: Query,
+ fetchOptions: FetchOptions | undefined,
+ addSignal: (context: object) => asserts context is { signal: AbortSignal },
+) {
+ const { queryKey, options, state } = query as Query<
+ unknown,
+ DefaultError,
+ InfiniteData
+ >
+ const context = { client, queryKey, options, state, fetchOptions }
+ addSignal(context)
+ return prepareInfiniteFetch(context, query)
+}
+
+/**
+ * Creates the page fetcher for an infinite query. A retry continues from the
+ * failed page. A new fetch starts with the most recently cached pages.
+ * @param context - The fetch in progress, including its options and cached pages.
+ * @param query - The query supplied to a custom persister.
+ * @returns A fetcher that resumes pagination at the failed page on retry.
+ */
+export function prepareInfiniteFetch(
+ context: Omit<
+ FetchContext>,
+ 'fetchFn'
+ >,
+ query: Query,
+) {
+ const options = context.options as InfiniteQueryPageParamsOptions & {
+ pages?: number
+ }
+ const direction = context.fetchOptions?.meta?.fetchMore?.direction
+ const oldPages = context.state.data?.pages || []
+ const oldPageParams = context.state.data?.pageParams || []
+ let result: InfiniteData = { pages: [], pageParams: [] }
+ let currentPage = 0
+
+ const fetchFn = async () => {
+ let cancelled = false
+ const signalContext: FetchSignalContext = context
+ const queryFn = ensureQueryFn(context.options, context.fetchOptions)
+
+ // Create function to fetch a page
+ const fetchPage = async (
+ data: InfiniteData,
+ param: unknown,
+ previous?: boolean,
+ ): Promise> => {
+ if (cancelled) {
+ return Promise.reject(context.signal.reason)
+ }
+
+ if (param == null && data.pages.length) {
+ return Promise.resolve(data)
+ }
+
+ const queryFnContext = addConsumeAwareSignal(
+ {
+ client: context.client,
+ queryKey: context.queryKey,
+ pageParam: param,
+ meta: context.options.meta,
+ },
+ () => context.signal,
+ () => (cancelled = true),
+ signalContext[fetchSignal],
+ )
+
+ const page = await queryFn(queryFnContext)
+
+ const { maxPages } = context.options
+ return {
+ pages: addToArray(data.pages, page, maxPages, previous),
+ pageParams: addToArray(data.pageParams, param, maxPages, previous),
+ }
+ }
+
+ // fetch next / previous page?
+ if (direction && oldPages.length) {
+ const previous = direction === 'backward'
+ const pageParamFn = previous ? getPreviousPageParam : getNextPageParam
+ const oldData = {
+ pages: oldPages,
+ pageParams: oldPageParams,
+ }
+ const param = pageParamFn(options, oldData)
+
+ result = await fetchPage(oldData, param, previous)
+ } else {
+ const remainingPages = options.pages ?? oldPages.length
+
+ // Fetch all pages
+ do {
+ const param =
+ currentPage === 0
+ ? oldPageParams[0] === undefined
+ ? options.initialPageParam
+ : oldPageParams[0]
+ : getNextPageParam(options, result)
+ if (currentPage > 0 && param == null) {
+ break
+ }
+ result = await fetchPage(result, param)
+ currentPage++
+ } while (currentPage < remainingPages)
+ }
+
+ return result
+ }
+ if (context.options.persister) {
+ return () => {
+ return context.options.persister?.(
+ fetchFn as any,
+ {
+ client: context.client,
+ queryKey: context.queryKey,
+ meta: context.options.meta,
+ signal: context.signal,
+ },
+ query,
+ )
+ }
+ }
+ return fetchFn
+}
+
+/**
+ * Computes the page param of the page after the last one, with the `getNextPageParam` option.
+ * @param options - The infinite query options.
+ * @param data - The current pages and page params.
+ * @returns The next page param, or `undefined` if there are no pages yet.
+ */
+function getNextPageParam(
+ options: InfiniteQueryPageParamsOptions,
+ { pages, pageParams }: InfiniteData,
+): unknown | undefined {
+ return pages.length > 0
+ ? options.getNextPageParam(
+ pages.at(-1),
+ pages,
+ pageParams.at(-1),
+ pageParams,
+ )
+ : undefined
+}
+
+/**
+ * Computes the page param of the page before the first one, with the `getPreviousPageParam`
+ * option.
+ * @param options - The infinite query options.
+ * @param data - The current pages and page params.
+ * @returns The previous page param, or `undefined` if there are no pages yet or no
+ * `getPreviousPageParam` option.
+ */
+function getPreviousPageParam(
+ options: InfiniteQueryPageParamsOptions,
+ { pages, pageParams }: InfiniteData,
+): unknown | undefined {
+ return pages.length > 0
+ ? options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams)
+ : undefined
+}
+
+/**
+ * Checks if there is a next page.
+ * @param options - The infinite query options with `getNextPageParam`.
+ * @param data - The current pages and page params.
+ * @returns `true` if `getNextPageParam` returns a value other than `null` or `undefined`.
+ */
+export function hasNextPage(
+ options: InfiniteQueryPageParamsOptions,
+ data?: InfiniteData,
+): boolean {
+ if (!data) return false
+ return getNextPageParam(options, data) != null
+}
+
+/**
+ * Checks if there is a previous page.
+ * @param options - The infinite query options with `getPreviousPageParam`.
+ * @param data - The current pages and page params.
+ * @returns `true` if `getPreviousPageParam` is set and returns a value other than `null` or
+ * `undefined`.
+ */
+export function hasPreviousPage(
+ options: InfiniteQueryPageParamsOptions,
+ data?: InfiniteData,
+): boolean {
+ if (!data || !options.getPreviousPageParam) return false
+ return getPreviousPageParam(options, data) != null
+}
+
+/**
+ * Attaches paging to the options that create or restore an infinite query.
+ * @param options - Options accepted by an infinite query or observer.
+ * @returns Options that install the page fetcher on the cached query.
+ */
+export function infiniteFetchOptions(
+ options: TOptions,
+) {
+ return {
+ ...options,
+ _type: 'infinite' as const,
+ _prepareInfiniteFetch: createInfiniteFetch,
+ }
+}
diff --git a/packages/query-core-pluggable/src/infiniteQueryObserver.ts b/packages/query-core-pluggable/src/infiniteQueryObserver.ts
new file mode 100644
index 00000000000..e354ec1e9fc
--- /dev/null
+++ b/packages/query-core-pluggable/src/infiniteQueryObserver.ts
@@ -0,0 +1,283 @@
+import {
+ hasNextPage,
+ hasPreviousPage,
+ infiniteFetchOptions,
+} from './infiniteQueryBehavior'
+import { QueryObserver } from './queryObserver'
+import type { Query } from './query'
+import type { QueryClient } from './queryClient'
+import type {
+ QueryObserverResultContext,
+ QueryObserverResultReader,
+} from './queryObserver'
+import type { Subscribable } from './subscribable'
+import type {
+ DefaultError,
+ DefaultedInfiniteQueryObserverOptions,
+ FetchNextPageOptions,
+ FetchPreviousPageOptions,
+ InfiniteData,
+ InfiniteQueryObserverBaseResult,
+ InfiniteQueryObserverOptions,
+ InfiniteQueryObserverResult,
+ QueryKey,
+ QueryObserverResult,
+} from './types'
+
+type InfiniteQueryObserverListener = (
+ result: InfiniteQueryObserverResult,
+) => void
+
+type ReplaceReturnType<
+ TFunction extends (...args: Array) => unknown,
+ TReturn,
+> = (...args: Parameters) => TReturn
+
+type InfiniteObserverOptionsInput<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey extends QueryKey,
+ TPageParam,
+> =
+ | InfiniteQueryObserverOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >
+ | DefaultedInfiniteQueryObserverOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >
+
+/**
+ * An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch
+ * between infinite queries. It augments the base `QueryObserverResult` with
+ * infinite-query-specific fields and methods, such as `hasNextPage` and
+ * `fetchNextPage`. The React adapter uses this observer for
+ * `useQuery(infiniteQueryOptions(options))` and `useQuery(suspenseInfiniteQueryOptions(options))`.
+ * @example
+ * ```ts
+ * const observer = new InfiniteQueryObserver(queryClient, {
+ * queryKey: ['projects'],
+ * queryFn: ({ pageParam }) => fetchProjects(pageParam),
+ * initialPageParam: 0,
+ * getNextPageParam: (lastPage) => lastPage.nextCursor,
+ * })
+ *
+ * const unsubscribe = observer.subscribe((result) => console.log(result))
+ * ```
+ */
+export class InfiniteQueryObserver<
+ TQueryFnData = unknown,
+ TError = DefaultError,
+ TData = InfiniteData,
+ TQueryKey extends QueryKey = QueryKey,
+ TPageParam = unknown,
+> extends QueryObserver<
+ TQueryFnData,
+ TError,
+ TData,
+ InfiniteData,
+ TQueryKey
+> {
+ // Type override
+ override subscribe!: Subscribable<
+ InfiniteQueryObserverListener
+ >['subscribe']
+
+ // Type override
+ override getCurrentResult!: ReplaceReturnType<
+ QueryObserver<
+ TQueryFnData,
+ TError,
+ TData,
+ InfiniteData,
+ TQueryKey
+ >['getCurrentResult'],
+ InfiniteQueryObserverResult
+ >
+
+ // Type override
+ protected override fetch!: ReplaceReturnType<
+ QueryObserver<
+ TQueryFnData,
+ TError,
+ TData,
+ InfiniteData,
+ TQueryKey
+ >['fetch'],
+ Promise>
+ >
+
+ constructor(
+ client: QueryClient,
+ options: InfiniteObserverOptionsInput<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >,
+ ) {
+ super(client, options)
+ }
+
+ protected override bindMethods(): void {
+ super.bindMethods()
+ this.fetchNextPage = this.fetchNextPage.bind(this)
+ this.fetchPreviousPage = this.fetchPreviousPage.bind(this)
+ }
+
+ /**
+ * Updates the observer's options. Behaves the same as
+ * `QueryObserver.setOptions`, additionally marking the options as
+ * belonging to an infinite query before delegating to the base
+ * implementation.
+ * @param options - The new infinite query observer options.
+ */
+ override setOptions(
+ options: InfiniteObserverOptionsInput<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >,
+ ): void {
+ super.setOptions(infiniteFetchOptions(options))
+ }
+
+ /**
+ * Creates a cached snapshot reader for an infinite query.
+ * @param options - The defaulted options used to read and commit the query result.
+ * @returns A reader that keeps its result and computation state until commit.
+ */
+ override createResultReader(
+ options: DefaultedInfiniteQueryObserverOptions<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >,
+ ): QueryObserverResultReader> {
+ return super.createResultReader(
+ infiniteFetchOptions(options),
+ ) as QueryObserverResultReader>
+ }
+
+ /**
+ * Fetches the next page of the infinite query and returns a promise that
+ * resolves with the resulting `InfiniteQueryObserverResult`. The page
+ * param used for the fetch is determined by `getNextPageParam`, which
+ * receives the current pages/page params and whose result also determines
+ * `hasNextPage`.
+ * @param options - Set `cancelRefetch` to `false` to ignore the call while a fetch is running,
+ * and `throwOnError` to `true` to reject when the fetch fails.
+ * @returns A promise that resolves with the result after the next page is fetched. With
+ * `cancelRefetch: false`, a running fetch is reused instead, so the next page may not be fetched.
+ * @see {@link InfiniteQueryObserver#fetchPreviousPage}
+ * @example
+ * ```ts
+ * const { hasNextPage } = observer.getCurrentResult()
+ *
+ * if (hasNextPage) {
+ * await observer.fetchNextPage()
+ * }
+ * ```
+ */
+ fetchNextPage(
+ options?: FetchNextPageOptions,
+ ): Promise> {
+ return this.fetch({
+ ...options,
+ meta: {
+ fetchMore: { direction: 'forward' },
+ },
+ })
+ }
+
+ /**
+ * Fetches the previous page of the infinite query and returns a promise
+ * that resolves with the resulting `InfiniteQueryObserverResult`. The page
+ * param used for the fetch is determined by `getPreviousPageParam`, which
+ * receives the current pages/page params and whose result also determines
+ * `hasPreviousPage`.
+ * @param options - Set `cancelRefetch` to `false` to ignore the call while a fetch is running,
+ * and `throwOnError` to `true` to reject when the fetch fails.
+ * @returns A promise that resolves with the result after the previous page is fetched. With
+ * `cancelRefetch: false`, a running fetch is reused instead, so the previous page may not be fetched.
+ * @see {@link InfiniteQueryObserver#fetchNextPage}
+ * @example
+ * ```ts
+ * const { hasPreviousPage } = observer.getCurrentResult()
+ *
+ * if (hasPreviousPage) {
+ * await observer.fetchPreviousPage()
+ * }
+ * ```
+ */
+ fetchPreviousPage(
+ options?: FetchPreviousPageOptions,
+ ): Promise> {
+ return this.fetch({
+ ...options,
+ meta: {
+ fetchMore: { direction: 'backward' },
+ },
+ })
+ }
+
+ /**
+ * Adds pagination controls and fetch direction to the observer result.
+ * @internal
+ * @param query - The cached infinite query.
+ * @param options - Options used to read the pages.
+ * @param context - Selection and placeholder state for this read.
+ * @param prevResult - The preceding result for structural sharing.
+ * @returns The observer snapshot with page controls and direction-specific status.
+ */
+ override createResult(
+ query: Query<
+ TQueryFnData,
+ TError,
+ InfiniteData,
+ TQueryKey
+ >,
+ options: InfiniteObserverOptionsInput<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryKey,
+ TPageParam
+ >,
+ context?: QueryObserverResultContext<
+ TQueryFnData,
+ TError,
+ TData,
+ InfiniteData,
+ TQueryKey
+ >,
+ prevResult?: QueryObserverResult,
+ ): InfiniteQueryObserverResult {
+ const { state } = query
+ const parentResult = super.createResult(query, options, context, prevResult)
+
+ const result: InfiniteQueryObserverBaseResult = {
+ ...parentResult,
+ fetchNextPage: this.fetchNextPage,
+ fetchPreviousPage: this.fetchPreviousPage,
+ hasNextPage: hasNextPage(options, state.data),
+ hasPreviousPage: hasPreviousPage(options, state.data),
+ fetchDirection: state.fetchMeta?.fetchMore?.direction,
+ }
+
+ return result as InfiniteQueryObserverResult
+ }
+}
diff --git a/packages/query-core-pluggable/src/mutation.ts b/packages/query-core-pluggable/src/mutation.ts
new file mode 100644
index 00000000000..2062c7ffa6f
--- /dev/null
+++ b/packages/query-core-pluggable/src/mutation.ts
@@ -0,0 +1,590 @@
+import { getMutationCache } from './mutationCache'
+import { notifyManager } from './notifyManager'
+import { defaultMutationOptions } from './queryClient'
+import { Removable } from './removable'
+import { createRetryer } from './retryer'
+import type { MutationCache } from './mutationCache'
+import type { MutationObserver } from './mutationObserver'
+import type { QueryClient } from './queryClient'
+import type { Retryer } from './retryer'
+import type {
+ DefaultError,
+ MutationFunctionContext,
+ MutationMeta,
+ MutationOptions,
+ MutationStatus,
+} from './types'
+
+interface MutationConfig {
+ client: QueryClient
+ mutationId: number
+ mutationCache: MutationCache
+ options: MutationOptions
+ state?: MutationState
+}
+
+// CLASS
+
+/**
+ * Represents a single mutation attempt. A `Mutation` holds the mutation's
+ * options, state (data/error/status), and the `MutationObserver`s currently
+ * subscribed to it.
+ *
+ * Instances are created and managed internally by `MutationCache`; application
+ * code typically interacts with mutations indirectly through `QueryClient` or
+ * a framework hook like `useMutation`. Direct access to a `Mutation` instance
+ * is possible via `mutationCache.find()`/`getAll()` for inspecting cache state.
+ * @example
+ * ```ts
+ * const mutationCache = getMutationCache(queryClient)
+ *
+ * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
+ * ```
+ */
+export class Mutation<
+ TData = unknown,
+ TError = DefaultError,
+ TVariables = unknown,
+ TOnMutateResult = unknown,
+> extends Removable {
+ state: MutationState
+ options!: MutationOptions
+ readonly mutationId: number
+
+ #client: QueryClient
+ #observers: Array<
+ MutationObserver
+ >
+ #mutationCache: MutationCache
+ #retryer?: Retryer
+
+ /**
+ * Creates a mutation with the client's defaults and adds it to the cache.
+ * @param client - Supplies defaults and the mutation cache.
+ * @param options - The options for the new mutation.
+ * @param state - The initial state, for example when hydrating a paused mutation.
+ * @returns The registered mutation.
+ */
+ static build(
+ client: QueryClient,
+ options: MutationOptions,
+ state?: MutationState,
+ ): Mutation {
+ const cache = getMutationCache(client)
+ return cache.register(
+ (mutationId) =>
+ new Mutation({
+ client,
+ mutationCache: cache,
+ mutationId,
+ options: defaultMutationOptions(client, options),
+ state,
+ }),
+ )
+ }
+
+ constructor(
+ config: MutationConfig,
+ ) {
+ super()
+
+ this.#client = config.client
+ this.mutationId = config.mutationId
+ this.#mutationCache = config.mutationCache
+ this.#observers = []
+ this.state = config.state || getDefaultState()
+
+ this.options = config.options
+ this.updateGcTime(config.options.gcTime)
+ this.scheduleGc()
+ }
+
+ /**
+ * Replaces the mutation's options and applies their `gcTime`.
+ * @internal
+ * @param options - The new mutation options.
+ */
+ setOptions(
+ options: MutationOptions,
+ ): void {
+ // An observer may change options while its previous mutation is still queued.
+ const scope = this.options.scope
+ this.options = options.scope === scope ? options : { ...options, scope }
+ this.updateGcTime(options.gcTime)
+ }
+
+ /**
+ * The `meta` object passed in the mutation's options, if any.
+ * @returns The mutation's `meta`, or `undefined` if none was set.
+ */
+ get meta(): MutationMeta | undefined {
+ return this.options.meta
+ }
+
+ /**
+ * Subscribes an observer to the mutation and stops its garbage collection.
+ * @internal
+ * @param observer - The observer to add. Adding an observer that is already subscribed does
+ * nothing.
+ */
+ addObserver(observer: MutationObserver): void {
+ if (!this.#observers.includes(observer)) {
+ this.#observers.push(observer)
+
+ // Stop the mutation from being garbage collected
+ this.clearGcTimeout()
+
+ this.#mutationCache.notify({
+ type: 'observerAdded',
+ mutation: this,
+ observer,
+ })
+ }
+ }
+
+ /**
+ * Unsubscribes an observer from the mutation.
+ * @internal
+ * @param observer - The observer to remove. Schedules garbage collection if the mutation
+ * is still in the cache.
+ */
+ removeObserver(observer: MutationObserver): void {
+ this.#observers = this.#observers.filter((x) => x !== observer)
+
+ if (this.#mutationCache.has(this)) {
+ this.scheduleGc()
+ }
+
+ this.#mutationCache.notify({
+ type: 'observerRemoved',
+ mutation: this,
+ observer,
+ })
+ }
+
+ protected override optionalRemove() {
+ if (!this.#observers.length) {
+ if (this.state.status === 'pending') {
+ this.scheduleGc()
+ } else {
+ this.#mutationCache.remove(this)
+ }
+ }
+ }
+
+ /**
+ * Resumes a mutation that is currently paused or was restored from a
+ * dehydrated, still-`pending` state.
+ *
+ * - If this mutation has an active retryer (it paused mid-attempt, e.g. due
+ * to the network mode or scope-based queuing), its retryer is resumed.
+ * - Otherwise, if the mutation's status is still `pending` (e.g. it was
+ * dehydrated while an attempt was in flight and never got a retryer in
+ * this instance), `execute` is called again with the last known variables.
+ * - Otherwise the mutation has already settled and this resolves immediately
+ * without running anything again.
+ * @returns A promise that settles with the resumed mutation: it rejects if the mutation fails.
+ * It resolves immediately if the mutation has already settled.
+ * @see {@link Mutation#execute}
+ * @example
+ * ```ts
+ * // typically driven by reconnect handling, e.g. resumePausedMutations()
+ * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
+ * await mutation?.continue()
+ * ```
+ */
+ continue(): Promise {
+ return (
+ this.#retryer?.continue() ??
+ // continuing a mutation assumes that variables are set, mutation must have been dehydrated before.
+ // a settled mutation has no retryer to continue and must not run again
+ (this.state.status === 'pending'
+ ? this.execute(this.state.variables!)
+ : Promise.resolve())
+ )
+ }
+
+ /**
+ * Runs the mutation function for the given variables through a retryer, and
+ * drives the mutation's state and lifecycle callbacks through to settlement.
+ *
+ * If this mutation's state is already `pending` when `execute` is called
+ * (i.e. it was restored, still in-flight, from a dehydrated state), the
+ * `onMutate` step is skipped and a `continue` action is dispatched to
+ * unpause it; otherwise a `pending` action is dispatched first, then the
+ * mutation cache's `onMutate` and the mutation's own `onMutate` option are
+ * awaited in that order, and the resulting context is stored.
+ *
+ * The mutation function is then run (subject to `retry`/`retryDelay`/
+ * `networkMode`, and to the mutation cache's scope-based serialization).
+ * On success, the cache's `onSuccess`/`onSettled` callbacks run before the
+ * mutation's own `onSuccess`/`onSettled` options, a `success` action is
+ * dispatched, and the resolved data is returned. On failure, the same
+ * cache-then-option ordering is used for `onError`/`onSettled`, but each of
+ * those four callbacks is individually caught so that a throwing callback
+ * cannot mask the original error; an `error` action is then dispatched and
+ * the original error is re-thrown.
+ * @param variables - The variables passed to the `mutationFn`.
+ * @returns A promise that resolves with the mutation's data, or rejects with its error.
+ * @see {@link Mutation#continue}
+ * @example
+ * ```ts
+ * // Called internally by `MutationObserver.mutate` and `Mutation.continue` —
+ * // applications normally trigger mutations through those, not this method.
+ * const data = await mutation.execute(variables)
+ * ```
+ */
+ async execute(variables: TVariables): Promise {
+ const onContinue = () => {
+ this.#dispatch({ type: 'continue' })
+ }
+
+ const mutationFnContext = {
+ client: this.#client,
+ meta: this.options.meta,
+ mutationKey: this.options.mutationKey,
+ } satisfies MutationFunctionContext
+
+ const retryer = (this.#retryer = createRetryer({
+ fn: () => {
+ if (!this.options.mutationFn) {
+ return Promise.reject(new Error('No mutationFn found'))
+ }
+
+ return this.options.mutationFn(variables, mutationFnContext)
+ },
+ onFail: (failureCount, error) => {
+ this.#dispatch({ type: 'failed', failureCount, error })
+ },
+ onPause: () => {
+ this.#dispatch({ type: 'pause' })
+ },
+ onContinue,
+ retry: this.options.retry ?? 0,
+ retryDelay: this.options.retryDelay,
+ networkMode: this.options.networkMode,
+ canRun: () => this.#mutationCache.canRun(this),
+ }))
+
+ const restored = this.state.status === 'pending'
+ const isPaused = !retryer.canStart()
+
+ try {
+ if (restored) {
+ // Dispatch continue action to unpause restored mutation
+ onContinue()
+ } else {
+ this.#dispatch({ type: 'pending', variables, isPaused })
+ // Notify cache callback
+ if (this.#mutationCache.config.onMutate) {
+ await this.#mutationCache.config.onMutate(
+ variables,
+ this as Mutation,
+ mutationFnContext,
+ )
+ }
+ const context = await this.options.onMutate?.(
+ variables,
+ mutationFnContext,
+ )
+ if (context !== this.state.context) {
+ this.#dispatch({
+ type: 'pending',
+ context,
+ variables,
+ isPaused,
+ })
+ }
+ }
+ // Unpause a mutation that became able to start while onMutate was running
+ if (this.state.isPaused && retryer.canStart()) {
+ onContinue()
+ }
+ const data = await retryer.start()
+
+ // Notify cache callback
+ await this.#mutationCache.config.onSuccess?.(
+ data,
+ variables,
+ this.state.context,
+ this as Mutation,
+ mutationFnContext,
+ )
+
+ await this.options.onSuccess?.(
+ data,
+ variables,
+ this.state.context!,
+ mutationFnContext,
+ )
+
+ // Notify cache callback
+ await this.#mutationCache.config.onSettled?.(
+ data,
+ null,
+ this.state.variables,
+ this.state.context,
+ this as Mutation,
+ mutationFnContext,
+ )
+
+ await this.options.onSettled?.(
+ data,
+ null,
+ variables,
+ this.state.context,
+ mutationFnContext,
+ )
+
+ this.#dispatch({ type: 'success', data })
+ return data
+ } catch (error) {
+ try {
+ // Notify cache callback
+ await this.#mutationCache.config.onError?.(
+ error as any,
+ variables,
+ this.state.context,
+ this as Mutation,
+ mutationFnContext,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+
+ try {
+ await this.options.onError?.(
+ error as TError,
+ variables,
+ this.state.context,
+ mutationFnContext,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+
+ try {
+ // Notify cache callback
+ await this.#mutationCache.config.onSettled?.(
+ undefined,
+ error as any,
+ this.state.variables,
+ this.state.context,
+ this as Mutation,
+ mutationFnContext,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+
+ try {
+ await this.options.onSettled?.(
+ undefined,
+ error as TError,
+ variables,
+ this.state.context,
+ mutationFnContext,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+
+ this.#dispatch({ type: 'error', error: error as TError })
+ throw error
+ } finally {
+ // The settled retryer's promise would otherwise pin this mutation's
+ // result, variables and context for as long as the cache keeps it
+ if (this.#retryer === retryer) {
+ this.#retryer = undefined
+ }
+ this.#mutationCache.runNext(this)
+ }
+ }
+
+ #dispatch(action: Action): void {
+ const reducer = (
+ state: MutationState,
+ ): MutationState => {
+ switch (action.type) {
+ case 'failed':
+ return {
+ ...state,
+ failureCount: action.failureCount,
+ failureReason: action.error,
+ }
+ case 'pause':
+ return {
+ ...state,
+ isPaused: true,
+ }
+ case 'continue':
+ return {
+ ...state,
+ isPaused: false,
+ }
+ case 'pending':
+ return {
+ ...state,
+ context: action.context,
+ data: undefined,
+ failureCount: 0,
+ failureReason: null,
+ error: null,
+ isPaused: action.isPaused,
+ status: 'pending',
+ variables: action.variables,
+ submittedAt: Date.now(),
+ }
+ case 'success':
+ return {
+ ...state,
+ data: action.data,
+ failureCount: 0,
+ failureReason: null,
+ error: null,
+ status: 'success',
+ isPaused: false,
+ }
+ case 'error':
+ return {
+ ...state,
+ data: undefined,
+ error: action.error,
+ failureCount: state.failureCount + 1,
+ failureReason: action.error,
+ isPaused: false,
+ status: 'error',
+ }
+ }
+ }
+ this.state = reducer(this.state)
+
+ notifyManager.batch(() => {
+ this.#observers.forEach((observer) => {
+ observer.onMutationUpdate(action)
+ })
+ this.#mutationCache.notify({
+ mutation: this,
+ type: 'updated',
+ action,
+ })
+ })
+ }
+}
+
+/**
+ * Returns the initial state of a mutation: `'idle'`, with no data, error, or variables.
+ * @returns The initial mutation state.
+ */
+export function getDefaultState<
+ TData,
+ TError,
+ TVariables,
+ TOnMutateResult,
+>(): MutationState {
+ return {
+ context: undefined,
+ data: undefined,
+ error: null,
+ failureCount: 0,
+ failureReason: null,
+ isPaused: false,
+ status: 'idle',
+ variables: undefined,
+ submittedAt: 0,
+ }
+}
+
+/**
+ * The raw state stored on a `Mutation` instance. This is the underlying state
+ * that observer results (e.g. `MutationObserverResult`) are derived from.
+ */
+export interface MutationState<
+ TData = unknown,
+ TError = DefaultError,
+ TVariables = unknown,
+ TOnMutateResult = unknown,
+> {
+ /**
+ * The value returned by `onMutate`, if defined. Passed to `onSuccess`,
+ * `onError` and `onSettled` as the mutation's context.
+ */
+ context: TOnMutateResult | undefined
+ /**
+ * The last successfully resolved data for the mutation.
+ */
+ data: TData | undefined
+ /**
+ * The error object for the mutation, if the last attempt resulted in an error.
+ * - Defaults to `null`.
+ */
+ error: TError | null
+ /**
+ * The number of times the mutation function has failed for the current attempt.
+ */
+ failureCount: number
+ /**
+ * The reason the current attempt failed, as reported by the retryer.
+ */
+ failureReason: TError | null
+ /**
+ * Whether the mutation is currently paused (see network mode), or is
+ * waiting for another mutation with the same `scope` to finish.
+ */
+ isPaused: boolean
+ /**
+ * The status of the mutation.
+ */
+ status: MutationStatus
+ /**
+ * The variables the mutation was last called with.
+ */
+ variables: TVariables | undefined
+ /**
+ * The timestamp for when the mutation was submitted.
+ */
+ submittedAt: number
+}
+
+interface FailedAction {
+ type: 'failed'
+ failureCount: number
+ error: TError | null
+}
+
+interface PendingAction {
+ type: 'pending'
+ isPaused: boolean
+ variables?: TVariables
+ context?: TOnMutateResult
+}
+
+interface SuccessAction {
+ type: 'success'
+ data: TData
+}
+
+interface ErrorAction {
+ type: 'error'
+ error: TError
+}
+
+interface PauseAction {
+ type: 'pause'
+}
+
+interface ContinueAction {
+ type: 'continue'
+}
+
+/**
+ * The actions a mutation dispatches to update its state, e.g. when it starts, fails, pauses, or
+ * succeeds.
+ */
+export type Action =
+ | ContinueAction
+ | ErrorAction
+ | FailedAction
+ | PendingAction
+ | PauseAction
+ | SuccessAction
diff --git a/packages/query-core-pluggable/src/mutationCache.ts b/packages/query-core-pluggable/src/mutationCache.ts
new file mode 100644
index 00000000000..eeff7fef932
--- /dev/null
+++ b/packages/query-core-pluggable/src/mutationCache.ts
@@ -0,0 +1,345 @@
+import { notifyManager } from './notifyManager'
+import { mutationCacheKey } from './queryClient'
+import { Subscribable } from './subscribable'
+import { matchMutation, noop } from './utils'
+import type { Mutation, Action as MutationAction } from './mutation'
+import type { MutationObserver } from './mutationObserver'
+import type { QueryClient } from './queryClient'
+import type {
+ CacheKeyConfig,
+ DefaultError,
+ MutationFunctionContext,
+ MutationKey,
+ NotifyEvent,
+} from './types'
+import type { MutationFilters } from './utils'
+
+/**
+ * Global callbacks that fire for every mutation handled by a `MutationCache`, regardless of which
+ * component or observer triggered it. They differ from the `defaultOptions` provided to a
+ * `QueryClient` in two ways: `defaultOptions` can be overridden by each mutation, while these
+ * callbacks are always called, and `onMutate` here does not allow returning a result.
+ *
+ * If a callback returns a promise, it will be awaited before the mutation continues.
+ */
+export interface MutationCacheConfig {
+ /**
+ * Configures mutation key comparison and hashing globally.
+ * `equalityFn` compares individual values during partial matching and defaults to strict equality.
+ * `hashFn` hashes mutation keys for exact matching and mutation defaults.
+ */
+ mutationKey?: CacheKeyConfig
+ /** Called when any mutation in the cache encounters an error. */
+ onError?: (
+ error: DefaultError,
+ variables: unknown,
+ onMutateResult: unknown,
+ mutation: Mutation,
+ context: MutationFunctionContext,
+ ) => Promise | unknown
+ /** Called when any mutation in the cache is successful. */
+ onSuccess?: (
+ data: unknown,
+ variables: unknown,
+ onMutateResult: unknown,
+ mutation: Mutation,
+ context: MutationFunctionContext,
+ ) => Promise | unknown
+ /** Called before any mutation in the cache executes. */
+ onMutate?: (
+ variables: unknown,
+ mutation: Mutation,
+ context: MutationFunctionContext,
+ ) => Promise | unknown
+ /** Called when any mutation in the cache is settled, either successfully or with an error. */
+ onSettled?: (
+ data: unknown | undefined,
+ error: DefaultError | null,
+ variables: unknown,
+ onMutateResult: unknown,
+ mutation: Mutation,
+ context: MutationFunctionContext,
+ ) => Promise | unknown
+}
+
+/**
+ * The event passed to a `MutationCache` subscriber. Fired whenever a mutation is added or removed
+ * from the cache, its state is updated, or one of its observers is added, removed, or has its
+ * options updated.
+ */
+export type MutationCacheNotifyEvent =
+ | NotifyEventMutationAdded
+ | NotifyEventMutationRemoved
+ | NotifyEventMutationObserverAdded
+ | NotifyEventMutationObserverRemoved
+ | NotifyEventMutationObserverOptionsUpdated
+ | NotifyEventMutationUpdated
+
+type MutationCacheListener = (event: MutationCacheNotifyEvent) => void
+
+interface NotifyEventMutationAdded extends NotifyEvent {
+ type: 'added'
+ mutation: Mutation
+}
+
+interface NotifyEventMutationRemoved extends NotifyEvent {
+ type: 'removed'
+ mutation: Mutation
+}
+
+interface NotifyEventMutationObserverAdded extends NotifyEvent {
+ type: 'observerAdded'
+ mutation: Mutation
+ observer: MutationObserver
+}
+
+interface NotifyEventMutationObserverRemoved extends NotifyEvent {
+ type: 'observerRemoved'
+ mutation: Mutation
+ observer: MutationObserver
+}
+
+interface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent {
+ type: 'observerOptionsUpdated'
+ mutation?: Mutation
+ observer: MutationObserver
+}
+
+interface NotifyEventMutationUpdated extends NotifyEvent {
+ type: 'updated'
+ mutation: Mutation
+ action: MutationAction
+}
+
+/**
+ * Returns the client's configured mutation cache, creating a default cache on
+ * first use. Mutation hooks and hydration share this cache.
+ * @param client - The client whose mutations you want to access.
+ * @returns The same mutation cache on every call for this client.
+ * @example
+ * ```ts
+ * import { getMutationCache } from '@tanstack/query-core-pluggable'
+ *
+ * const pending = getMutationCache(queryClient).findAll({ status: 'pending' })
+ * ```
+ */
+export function getMutationCache(client: QueryClient): MutationCache {
+ return (client[mutationCacheKey] ??= new MutationCache())
+}
+
+/**
+ * Stores the mutations executed through a client. Use {@link getMutationCache} to
+ * access the cache that mutation hooks use. Subscribe to it to receive updates
+ * when a mutation is added, removed, or changes state.
+ * @example
+ * ```ts
+ * const unsubscribe = mutationCache.subscribe((event) => {
+ * console.log(event.type, event.mutation)
+ * })
+ * ```
+ */
+export class MutationCache extends Subscribable {
+ #mutations: Set>
+ #mutationId: number
+
+ constructor(public config: MutationCacheConfig = {}) {
+ super()
+ this.#mutations = new Set()
+ this.#mutationId = 0
+ }
+
+ /**
+ * Assigns the next cache-local ID and registers the mutation.
+ * @internal
+ * @param create - Constructs the mutation with the assigned ID.
+ * @returns The mutation added to this cache.
+ */
+ register>(
+ create: (id: number) => T,
+ ): T {
+ const mutation = create(++this.#mutationId)
+ this.add(mutation)
+ return mutation
+ }
+
+ /**
+ * Adds a mutation to the cache.
+ * @internal
+ * @param mutation - The mutation to add. If it has a `scope`, it is queued in that scope.
+ */
+ add(mutation: Mutation): void {
+ this.#mutations.add(mutation)
+ mutation.options.scope?.add(this, mutation)
+ this.notify({ type: 'added', mutation })
+ }
+
+ /**
+ * Removes a mutation from the cache and clears its garbage collection timer.
+ * @internal
+ * @param mutation - The mutation to remove, also from its scope's queue.
+ */
+ remove(mutation: Mutation): void {
+ if (this.#mutations.delete(mutation)) {
+ mutation.destroy()
+ mutation.options.scope?.remove(this, mutation)
+ }
+
+ // Currently we notify the removal even if the mutation was already removed.
+ // Consider making this an error or not notifying of the removal depending on the desired semantics.
+ this.notify({ type: 'removed', mutation })
+ }
+
+ /**
+ * Checks whether this cache still holds the given mutation.
+ * @internal
+ * @param mutation - The mutation to check.
+ * @returns Whether the mutation is in the cache.
+ */
+ has(mutation: Mutation): boolean {
+ return this.#mutations.has(mutation)
+ }
+
+ /**
+ * Checks whether a mutation can run now, given the other mutations in its `scope`.
+ * @internal
+ * @param mutation - The mutation to check.
+ * @returns `true` if the mutation has no `scope`, or no other mutation in its scope is pending
+ * ahead of it.
+ */
+ canRun(mutation: Mutation): boolean {
+ return mutation.options.scope?.canRun(this, mutation) ?? true
+ }
+
+ /**
+ * Continues the next paused mutation in the same `scope` after a mutation finishes.
+ * @internal
+ * @param mutation - The mutation that finished.
+ * @returns A promise that resolves once the next paused mutation in the same scope has continued,
+ * or immediately if there is none.
+ */
+ runNext(mutation: Mutation): Promise {
+ return mutation.options.scope?.runNext(this, mutation) ?? Promise.resolve()
+ }
+
+ /**
+ * Removes all mutations and clears their garbage collection timers.
+ * Mutations that are already running continue to execute.
+ * @example
+ * ```ts
+ * const mutationCache = getMutationCache(queryClient)
+ *
+ * mutationCache.clear()
+ * ```
+ */
+ clear(): void {
+ notifyManager.batch(() => {
+ const mutations = this.getAll()
+ this.#mutations.clear()
+ mutations.forEach((mutation) => {
+ mutation.options.scope?.remove(this, mutation)
+ mutation.destroy()
+ })
+ mutations.forEach((mutation) => {
+ this.notify({ type: 'removed', mutation })
+ })
+ })
+ }
+
+ /**
+ * Returns all mutations within the cache.
+ *
+ * This is not typically needed for most applications, but can come in handy when needing more
+ * information about a mutation in rare scenarios.
+ * @returns Every mutation in the cache.
+ * @example
+ * ```ts
+ * const mutationCache = getMutationCache(queryClient)
+ *
+ * const mutations = mutationCache.getAll()
+ * ```
+ */
+ getAll(): Array {
+ return Array.from(this.#mutations)
+ }
+
+ /**
+ * A slightly more advanced method that can be used to get an existing mutation instance from
+ * the cache. If the mutation does not exist, `undefined` is returned.
+ *
+ * This is not typically needed for most applications, but can come in handy when needing more
+ * information about a mutation in rare scenarios.
+ * @param filters - The filters to match. `exact` defaults to `true`.
+ * @returns The first matching mutation, or `undefined`.
+ * @see {@link MutationCache#findAll}
+ * @example
+ * ```ts
+ * const mutationCache = getMutationCache(queryClient)
+ *
+ * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
+ * ```
+ */
+ find<
+ TData = unknown,
+ TError = DefaultError,
+ TVariables = any,
+ TOnMutateResult = unknown,
+ >(
+ filters: MutationFilters,
+ ): Mutation | undefined {
+ const defaultedFilters = { exact: true, ...filters }
+
+ return this.getAll().find((mutation) =>
+ matchMutation(defaultedFilters, mutation, this.config.mutationKey),
+ ) as Mutation | undefined
+ }
+
+ /**
+ * An even more advanced method that can be used to get existing mutation instances from the
+ * cache that match the given filters. If no mutations match, an empty array is returned.
+ *
+ * This is not typically needed for most applications, but can come in handy when needing more
+ * information about mutations in rare scenarios.
+ * @param filters - The filters to match. Without filters, every mutation is returned.
+ * @returns The matching mutations.
+ * @see {@link MutationCache#find}
+ * @example
+ * ```ts
+ * const mutationCache = getMutationCache(queryClient)
+ *
+ * const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })
+ * ```
+ */
+ findAll(filters: MutationFilters = {}): Array {
+ return this.getAll().filter((mutation) =>
+ matchMutation(filters, mutation, this.config.mutationKey),
+ )
+ }
+
+ /**
+ * Notifies every cache listener of an event, in one batch.
+ * @internal
+ * @param event - The event passed to every listener.
+ */
+ notify(event: MutationCacheNotifyEvent) {
+ notifyManager.batch(() => {
+ this.listeners.forEach((listener) => {
+ listener(event)
+ })
+ })
+ }
+
+ /**
+ * Continues every paused mutation, e.g. when the app comes back online.
+ * @internal
+ * @returns A promise that resolves once every paused mutation has continued and settled.
+ */
+ resumePausedMutations(): Promise {
+ const pausedMutations = this.getAll().filter((x) => x.state.isPaused)
+
+ return notifyManager.batch(() =>
+ Promise.all(
+ pausedMutations.map((mutation) => mutation.continue().catch(noop)),
+ ),
+ )
+ }
+}
diff --git a/packages/query-core-pluggable/src/mutationObserver.ts b/packages/query-core-pluggable/src/mutationObserver.ts
new file mode 100644
index 00000000000..3f888fe228d
--- /dev/null
+++ b/packages/query-core-pluggable/src/mutationObserver.ts
@@ -0,0 +1,327 @@
+import { Mutation, getDefaultState } from './mutation'
+import { getMutationCache } from './mutationCache'
+import { notifyManager } from './notifyManager'
+import { defaultMutationOptions } from './queryClient'
+import { Subscribable } from './subscribable'
+import { hashKeyByOptions, shallowEqualObjects } from './utils'
+import type { Action } from './mutation'
+import type { QueryClient } from './queryClient'
+import type {
+ DefaultError,
+ MutateOptions,
+ MutationFunctionContext,
+ MutationObserverOptions,
+ MutationObserverResult,
+} from './types'
+
+type MutationObserverListener = (
+ result: MutationObserverResult,
+) => void
+
+// CLASS
+
+/**
+ * Observes a single mutation and derives a `MutationObserverResult` from it.
+ * A framework hook like `useMutation` creates one `MutationObserver` per hook
+ * call, keeps it stable across re-renders, calls `setOptions` when the options
+ * passed to the hook change, subscribes to it to re-render on updates, and
+ * reads `getCurrentResult()` for the value to return. Calling `mutate()`
+ * builds a new underlying `Mutation` in the `MutationCache` and executes it.
+ * @example
+ * ```ts
+ * const observer = new MutationObserver(queryClient, {
+ * mutationFn: (variables: { title: string }) => addPost(variables),
+ * })
+ * ```
+ */
+export class MutationObserver<
+ TData = unknown,
+ TError = DefaultError,
+ TVariables = void,
+ TOnMutateResult = unknown,
+> extends Subscribable<
+ MutationObserverListener
+> {
+ options!: MutationObserverOptions
+
+ #client: QueryClient
+ #currentResult: MutationObserverResult<
+ TData,
+ TError,
+ TVariables,
+ TOnMutateResult
+ > = undefined!
+ #currentMutation?: Mutation
+ #mutateOptions?: MutateOptions
+
+ constructor(
+ client: QueryClient,
+ options: MutationObserverOptions<
+ TData,
+ TError,
+ TVariables,
+ TOnMutateResult
+ >,
+ ) {
+ super()
+
+ this.#client = client
+ this.setOptions(options)
+ this.bindMethods()
+ this.#updateResult()
+ }
+
+ /**
+ * Binds the methods of the result (`mutate` and `reset`) to the observer, so they keep working when
+ * destructured from it.
+ */
+ protected bindMethods(): void {
+ this.mutate = this.mutate.bind(this)
+ this.reset = this.reset.bind(this)
+ }
+
+ /**
+ * Updates the observer's options.
+ *
+ * If the new `mutationKey` differs from the previous one (and both were
+ * defined), the observer is reset, detaching it from the mutation it was
+ * observing. Otherwise, if the currently observed mutation is still
+ * `pending`, its options are updated in place as well.
+ * @param options - The new mutation observer options. They are defaulted with {@link
+ * defaultMutationOptions} before being applied.
+ * @example
+ * ```ts
+ * observer.setOptions({
+ * mutationFn: (variables: { title: string }) => addPost(variables),
+ * onSuccess: (data) => console.log(data),
+ * })
+ * ```
+ */
+ setOptions(
+ options: MutationObserverOptions<
+ TData,
+ TError,
+ TVariables,
+ TOnMutateResult
+ >,
+ ) {
+ const prevOptions = this.options as
+ | MutationObserverOptions
+ | undefined
+ this.options = defaultMutationOptions(this.#client, options)
+ const mutationCache = getMutationCache(this.#client)
+ if (!shallowEqualObjects(this.options, prevOptions)) {
+ mutationCache.notify({
+ type: 'observerOptionsUpdated',
+ mutation: this.#currentMutation,
+ observer: this,
+ })
+ }
+
+ if (
+ prevOptions?.mutationKey &&
+ this.options.mutationKey &&
+ hashKeyByOptions(
+ prevOptions.mutationKey,
+ mutationCache.config.mutationKey,
+ ) !==
+ hashKeyByOptions(
+ this.options.mutationKey,
+ mutationCache.config.mutationKey,
+ )
+ ) {
+ this.reset()
+ } else if (this.#currentMutation?.state.status === 'pending') {
+ this.#currentMutation.setOptions(this.options)
+ }
+ }
+
+ protected override onSubscribe(): void {
+ if (this.listeners.size === 1 && this.#currentMutation) {
+ this.#currentMutation.addObserver(this)
+
+ this.#updateResult()
+ }
+ }
+
+ protected override onUnsubscribe(): void {
+ if (!this.hasListeners()) {
+ this.#currentMutation?.removeObserver(this)
+ }
+ }
+
+ /**
+ * Updates the observer's result when the observed mutation changes, and notifies its listeners.
+ * @internal
+ * @param action - The action that updated the observed mutation, passed on to the observer's
+ * callbacks.
+ */
+ onMutationUpdate(
+ action: Action,
+ ): void {
+ this.#updateResult()
+
+ this.#notify(action)
+ }
+
+ /**
+ * Returns the observer's current result, derived from the observed
+ * mutation's state (or the default, `idle` state if no mutation has been
+ * built yet, e.g. before the first `mutate()` call or after `reset()`).
+ * @returns The observer's latest result.
+ */
+ getCurrentResult(): MutationObserverResult<
+ TData,
+ TError,
+ TVariables,
+ TOnMutateResult
+ > {
+ return this.#currentResult
+ }
+
+ /**
+ * Detaches the observer from the mutation it is currently observing (if
+ * any) and resets the observed result back to its default, `idle` state.
+ *
+ * This does not cancel an in-flight mutation; the mutation itself keeps
+ * running to completion and its own callbacks still fire, but this
+ * observer stops reflecting its state and a subsequent `mutate()` call
+ * will build a brand new mutation.
+ * @see {@link MutationObserver#mutate}
+ * @example
+ * ```ts
+ * observer.reset()
+ * ```
+ */
+ reset(): void {
+ // reset needs to remove the observer from the mutation because there is no way to "get it back"
+ // another mutate call will yield a new mutation!
+ this.#currentMutation?.removeObserver(this)
+ this.#currentMutation = undefined
+ this.#updateResult()
+ this.#notify()
+ }
+
+ /**
+ * Builds a new `Mutation` in the `MutationCache` using the observer's
+ * current options, detaches this observer from any previously observed
+ * mutation, attaches it to the new one, and executes it with the given
+ * variables.
+ *
+ * The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are
+ * invoked once the mutation settles, in addition to any callbacks defined
+ * on the observer's own options.
+ * @param variables - The variables passed to the `mutationFn`.
+ * @param options - Per-call `onSuccess`, `onError`, and `onSettled` callbacks.
+ * @returns A promise that resolves with the mutation's data, or rejects with its error.
+ * @example
+ * ```ts
+ * await observer.mutate(
+ * { title: 'New post' },
+ * { onSuccess: (data) => console.log(data) },
+ * )
+ * ```
+ */
+ mutate(
+ variables: TVariables,
+ options?: MutateOptions,
+ ): Promise {
+ this.#mutateOptions = options
+
+ this.#currentMutation?.removeObserver(this)
+
+ this.#currentMutation = Mutation.build(this.#client, this.options)
+
+ this.#currentMutation.addObserver(this)
+
+ return this.#currentMutation.execute(variables)
+ }
+
+ #updateResult(): void {
+ const state =
+ this.#currentMutation?.state ??
+ getDefaultState()
+
+ this.#currentResult = {
+ ...state,
+ isPending: state.status === 'pending',
+ isSuccess: state.status === 'success',
+ isError: state.status === 'error',
+ isIdle: state.status === 'idle',
+ mutate: this.mutate,
+ reset: this.reset,
+ } as MutationObserverResult
+ }
+
+ #notify(action?: Action): void {
+ notifyManager.batch(() => {
+ // First trigger the mutate callbacks
+ // Snapshot mutateOptions before dispatching — a callback (e.g. onSuccess)
+ // may call mutate() again, which overwrites this.#mutateOptions in place.
+ // Without the snapshot, onSettled would fire with the *next* mutation's
+ // options but the *current* mutation's data/variables.
+ const mutateOptions = this.#mutateOptions
+ if (mutateOptions && this.hasListeners()) {
+ const variables = this.#currentResult.variables!
+ const onMutateResult = this.#currentResult.context
+
+ const context = {
+ client: this.#client,
+ meta: this.options.meta,
+ mutationKey: this.options.mutationKey,
+ } satisfies MutationFunctionContext
+
+ if (action?.type === 'success') {
+ try {
+ mutateOptions.onSuccess?.(
+ action.data,
+ variables,
+ onMutateResult,
+ context,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+ try {
+ mutateOptions.onSettled?.(
+ action.data,
+ null,
+ variables,
+ onMutateResult,
+ context,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+ } else if (action?.type === 'error') {
+ try {
+ mutateOptions.onError?.(
+ action.error,
+ variables,
+ onMutateResult,
+ context,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+ try {
+ mutateOptions.onSettled?.(
+ undefined,
+ action.error,
+ variables,
+ onMutateResult,
+ context,
+ )
+ } catch (e) {
+ void Promise.reject(e)
+ }
+ }
+ }
+
+ // Then trigger the listeners
+ this.listeners.forEach((listener) => {
+ listener(this.#currentResult)
+ })
+ })
+ }
+}
diff --git a/packages/query-core-pluggable/src/notifyManager.ts b/packages/query-core-pluggable/src/notifyManager.ts
new file mode 100644
index 00000000000..983e8d03539
--- /dev/null
+++ b/packages/query-core-pluggable/src/notifyManager.ts
@@ -0,0 +1,127 @@
+type BatchCallsCallback> = (...args: T) => void
+
+type NotifyCallback = () => void
+
+type NotifyFunction = (callback: () => void) => void
+
+type ScheduleFunction = (callback: () => void) => void
+
+/**
+ * Default scheduling function used by the notify manager.
+ * Schedules the callback in a microtask with `queueMicrotask`.
+ */
+export const defaultScheduler: ScheduleFunction = queueMicrotask
+
+/**
+ * Creates a notify manager, which schedules and batches notifications to subscribers. Query uses a
+ * single instance of it, exported as {@link notifyManager}.
+ * @returns A new notify manager.
+ */
+export function createNotifyManager() {
+ let queue: Array = []
+ let transactions = 0
+ let notifyFn: NotifyFunction = (callback) => {
+ callback()
+ }
+ let scheduleFn = defaultScheduler
+
+ const schedule = (callback: NotifyCallback): void => {
+ if (transactions) {
+ queue.push(callback)
+ } else {
+ scheduleFn(() => {
+ notifyFn(callback)
+ })
+ }
+ }
+ const flush = (): void => {
+ const originalQueue = queue
+ queue = []
+ if (originalQueue.length) {
+ scheduleFn(() => {
+ originalQueue.forEach((callback) => {
+ notifyFn(callback)
+ })
+ })
+ }
+ }
+
+ return {
+ /**
+ * Batches all updates scheduled inside the passed callback.
+ * This is mainly used internally to optimize query client updating.
+ * Batches can be nested; the queue is only flushed once the outermost `batch` call finishes.
+ * The return value of `callback` is passed through.
+ * @param callback - The function to run in the batch.
+ * @returns The return value of `callback`.
+ */
+ batch: (callback: () => T): T => {
+ let result
+ transactions++
+ try {
+ result = callback()
+ } finally {
+ transactions--
+ if (!transactions) {
+ flush()
+ }
+ }
+ return result
+ },
+ /**
+ * All calls to the wrapped function will be batched.
+ * @param callback - The function to wrap.
+ * @returns A function that schedules a call to `callback` with the given arguments.
+ */
+ batchCalls: >(
+ callback: BatchCallsCallback,
+ ): BatchCallsCallback => {
+ return (...args) => {
+ schedule(() => {
+ callback(...args)
+ })
+ }
+ },
+ /**
+ * Schedules a function to be run on the next batch.
+ * By default, the batch runs in a microtask. Use `setScheduler` to change when it runs.
+ */
+ schedule,
+ /**
+ * Use this method to set a custom notify function.
+ * This can be used to for example wrap notifications with `React.act` while running tests.
+ * @param fn - Receives each notification callback and must call it.
+ */
+ setNotifyFunction: (fn: NotifyFunction) => {
+ notifyFn = fn
+ },
+ /**
+ * Configures a custom callback that schedules when the next batch runs.
+ * The default behavior is `queueMicrotask(callback)`.
+ * @param fn - Receives a callback that runs the next batch, and schedules it.
+ * @example
+ * ```ts
+ * import { notifyManager } from '@tanstack/query-core-pluggable'
+ *
+ * // Use the v5 timer-based scheduler
+ * notifyManager.setScheduler((cb) => setTimeout(cb, 0))
+ *
+ * // Schedule batches before the next frame is rendered
+ * notifyManager.setScheduler(requestAnimationFrame)
+ *
+ * // Schedule batches some time in the future
+ * notifyManager.setScheduler((cb) => setTimeout(cb, 10))
+ * ```
+ */
+ setScheduler: (fn: ScheduleFunction) => {
+ scheduleFn = fn
+ },
+ } as const
+}
+
+// SINGLETON
+
+/**
+ * Handles scheduling and batching callbacks in TanStack Query.
+ */
+export const notifyManager = createNotifyManager()
diff --git a/packages/query-core-pluggable/src/onlineManager.ts b/packages/query-core-pluggable/src/onlineManager.ts
new file mode 100644
index 00000000000..8a7bc30aebc
--- /dev/null
+++ b/packages/query-core-pluggable/src/onlineManager.ts
@@ -0,0 +1,119 @@
+import { Subscribable } from './subscribable'
+
+type Listener = (online: boolean) => void
+type SetupFn = (setOnline: Listener) => (() => void) | undefined
+
+/**
+ * The `OnlineManager` manages the online state within TanStack Query. It can
+ * be used to change the default event listeners or to manually change the
+ * online state.
+ *
+ * By default, the `onlineManager` assumes an active network connection, and
+ * listens to the `online` and `offline` events on the `window` object to
+ * detect changes.
+ */
+export class OnlineManager extends Subscribable {
+ #online = true
+ #cleanup?: () => void
+
+ #setup: SetupFn
+
+ constructor() {
+ super()
+ this.#setup = (onOnline) => {
+ // addEventListener does not exist in React Native, but window does
+ // oxlint-disable-next-line typescript/no-unnecessary-condition
+ if (typeof window !== 'undefined' && window.addEventListener) {
+ const onlineListener = () => onOnline(true)
+ const offlineListener = () => onOnline(false)
+ // Listen to online
+ window.addEventListener('online', onlineListener, false)
+ window.addEventListener('offline', offlineListener, false)
+
+ return () => {
+ // Be sure to unsubscribe if a new handler is set
+ window.removeEventListener('online', onlineListener)
+ window.removeEventListener('offline', offlineListener)
+ }
+ }
+
+ return
+ }
+ }
+
+ protected override onSubscribe(): void {
+ if (!this.#cleanup) {
+ this.setEventListener(this.#setup)
+ }
+ }
+
+ protected override onUnsubscribe() {
+ if (!this.hasListeners()) {
+ this.#cleanup?.()
+ this.#cleanup = undefined
+ }
+ }
+
+ /**
+ * `setEventListener` can be used to set a custom event listener that will
+ * be used to determine the online state. The provided `setup` function
+ * receives a `setOnline` callback that should be called with a `boolean`
+ * whenever the online state changes.
+ * @param setup - Receives the `setOnline` callback, registers the event listener, and may return
+ * a cleanup function that is called when the listener is replaced or no longer needed.
+ * @example
+ * ```ts
+ * import NetInfo from '@react-native-community/netinfo'
+ * import { onlineManager } from '@tanstack/query-core-pluggable'
+ *
+ * onlineManager.setEventListener((setOnline) => {
+ * return NetInfo.addEventListener((state) => {
+ * setOnline(!!state.isConnected)
+ * })
+ * })
+ * ```
+ */
+ setEventListener(setup: SetupFn): void {
+ this.#setup = setup
+ this.#cleanup?.()
+ this.#cleanup = setup(this.setOnline.bind(this))
+ }
+
+ /**
+ * `setOnline` can be used to manually set the online state.
+ * @param online - The online state.
+ * @example
+ * ```ts
+ * import { onlineManager } from '@tanstack/query-core-pluggable'
+ *
+ * // Set to online
+ * onlineManager.setOnline(true)
+ *
+ * // Set to offline
+ * onlineManager.setOnline(false)
+ * ```
+ */
+ setOnline(online: boolean): void {
+ const changed = this.#online !== online
+
+ if (changed) {
+ this.#online = online
+ this.listeners.forEach((listener) => {
+ listener(online)
+ })
+ }
+ }
+
+ /**
+ * `isOnline` can be used to get the current online state.
+ * @returns `true` if online.
+ */
+ isOnline(): boolean {
+ return this.#online
+ }
+}
+
+/**
+ * Singleton instance of {@link OnlineManager}, used to manage and observe the online state within TanStack Query.
+ */
+export const onlineManager = new OnlineManager()
diff --git a/packages/query-core-pluggable/src/placeholderData.ts b/packages/query-core-pluggable/src/placeholderData.ts
new file mode 100644
index 00000000000..b1113e8a099
--- /dev/null
+++ b/packages/query-core-pluggable/src/placeholderData.ts
@@ -0,0 +1,98 @@
+import { projectResult } from './projectResult'
+import { replaceData, shallowEqualObjects } from './utils'
+import type { Query } from './query'
+import type {
+ ProjectionFailure,
+ QueryObserverResultContext,
+} from './queryObserver'
+import type { QueryKey, QueryObserverOptionsBase } from './types'
+
+/* #__NO_SIDE_EFFECTS__ */
+/**
+ * Supplies temporary data while an observed query has no cached result.
+ * @param value - A placeholder value or a factory receiving the previous query and its data.
+ * @returns A query placeholder option.
+ */
+export function placeholderData(
+ value: TValue,
+): readonly [typeof placeholderData, TValue] {
+ return [placeholderData, value]
+}
+
+placeholderData.project = projectResult
+placeholderData.resolve = resolvePlaceholder
+
+/**
+ * Reuses a pending query's placeholder until its factory, source query or sharing policy changes.
+ * @param options - Options that supply the placeholder.
+ * @param context - This observer or reader's cached placeholder.
+ * @param previousData - The previous data for structural sharing.
+ * @param previousQuery - The last observed query with defined data.
+ * @returns Placeholder data or the error thrown by its factory.
+ */
+function resolvePlaceholder<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryData,
+ TQueryKey extends QueryKey,
+>(
+ options: QueryObserverOptionsBase<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryData,
+ TQueryKey
+ >,
+ context: QueryObserverResultContext<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryData,
+ TQueryKey
+ >,
+ previousData: TData | undefined,
+ previousQuery: Query | undefined,
+): QueryObserverResultContext<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryData,
+ TQueryKey
+>['placeholder'] {
+ const value = options.placeholderData![1]
+ const previousState = previousQuery?.state
+ const key: NonNullable['key'] = {
+ placeholderData: value,
+ structuralSharing: options.structuralSharing,
+ previousQuery,
+ previousState,
+ previousOptions: previousQuery?.options,
+ }
+ const memo = context.placeholder
+ if (shallowEqualObjects(key, memo?.key)) return memo
+
+ let input: TQueryData | undefined
+ let sourceQuery: typeof previousQuery
+ let failure: ProjectionFailure | undefined
+ if (typeof value === 'function') {
+ try {
+ input = (
+ value as unknown as (
+ previous: TQueryData | undefined,
+ query: typeof previousQuery,
+ ) => TQueryData | undefined
+ )(previousState?.data, previousQuery)
+ } catch (error) {
+ failure = { error: error as TError, errorUpdatedAt: Date.now() }
+ }
+ if (previousState?.data !== undefined) sourceQuery = previousQuery
+ } else {
+ input = value
+ }
+ if (input !== undefined)
+ input = replaceData(previousData, input as unknown, options) as TQueryData
+ return input !== undefined || failure
+ ? { key, input, sourceQuery, failure }
+ : undefined
+}
diff --git a/packages/query-core-pluggable/src/projectResult.ts b/packages/query-core-pluggable/src/projectResult.ts
new file mode 100644
index 00000000000..ecdf5182269
--- /dev/null
+++ b/packages/query-core-pluggable/src/projectResult.ts
@@ -0,0 +1,89 @@
+import type { Query, QueryState } from './query'
+import type { QueryObserverResultContext } from './queryObserver'
+import type { QueryKey, QueryObserverOptionsBase } from './types'
+
+/**
+ * Computes the data, status and error visible to one observer.
+ * @param query - The query whose cached data is being read.
+ * @param state - The query state for this read, including optimistic fetch state.
+ * @param options - The selection, placeholder and structural sharing options.
+ * @param context - Memoized results for this observer or uncommitted result reader.
+ * @param previousData - The preceding observer result for structural sharing.
+ * @param previousQuery - The preceding query with defined cached data.
+ * @returns The projected fields, including whether the result contains placeholder data.
+ */
+export function projectResult<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryData,
+ TQueryKey extends QueryKey,
+>(
+ query: Query,
+ state: QueryState,
+ options: QueryObserverOptionsBase<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryData,
+ TQueryKey
+ >,
+ context: QueryObserverResultContext<
+ TQueryFnData,
+ TError,
+ TData,
+ TQueryData,
+ TQueryKey
+ >,
+ previousData: TData | undefined,
+ previousQuery: Query | undefined,
+): Pick<
+ QueryState,
+ 'data' | 'status' | 'error' | 'errorUpdatedAt'
+> & { isPlaceholderData: boolean } {
+ context.project = projectResult
+ const { select, placeholderData } = options
+ context.placeholder =
+ state.data === undefined && state.status === 'pending' && placeholderData
+ ? placeholderData[0].resolve(
+ options,
+ context,
+ previousData,
+ previousQuery,
+ )
+ : undefined
+ const placeholder = context.placeholder
+ const input = placeholder ? placeholder.input : state.data
+ // A previously selected query may have lost its data even if this render has no selector.
+ if (
+ context.selected?.query &&
+ context.selected.query.state.data === undefined
+ ) {
+ context.selected = undefined
+ if (!context.selection?.failure) context.selection = undefined
+ }
+ if (select && input !== undefined) {
+ select[0].resolve(
+ options,
+ select[1],
+ context,
+ previousData,
+ input,
+ placeholder ? placeholder.sourceQuery : query,
+ )
+ } else {
+ context.selection = undefined
+ }
+ const failure = placeholder?.failure ?? context.selection?.failure
+ const isPlaceholderData = !!placeholder && input !== undefined && !failure
+ const { error, errorUpdatedAt } = failure ?? state
+ return {
+ data: context.selection
+ ? context.selected?.data
+ : (input as unknown as TData | undefined),
+ error,
+ errorUpdatedAt,
+ status: failure ? 'error' : isPlaceholderData ? 'success' : state.status,
+ isPlaceholderData,
+ }
+}
diff --git a/packages/query-core-pluggable/src/projectionTypes.ts b/packages/query-core-pluggable/src/projectionTypes.ts
new file mode 100644
index 00000000000..856fb0dfc7f
--- /dev/null
+++ b/packages/query-core-pluggable/src/projectionTypes.ts
@@ -0,0 +1,20 @@
+import type { placeholderData } from './placeholderData'
+import type { select } from './select'
+
+/** A selector and its opt-in observer implementation. */
+export type Select = readonly [
+ feature: typeof select,
+ value: (data: TInput) => TData,
+]
+
+/** Placeholder data (or a factory) paired with its observer implementation. */
+export type PlaceholderData = readonly [
+ feature: typeof placeholderData,
+ value:
+ // oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes all callable and constructable values
+ | (TData extends Function ? never : TData)
+ | ((
+ previousData: TData | undefined,
+ previousQuery: TQuery | undefined,
+ ) => TData | undefined),
+]
diff --git a/packages/query-core-pluggable/src/queriesObserver.ts b/packages/query-core-pluggable/src/queriesObserver.ts
new file mode 100644
index 00000000000..cdeead23d2e
--- /dev/null
+++ b/packages/query-core-pluggable/src/queriesObserver.ts
@@ -0,0 +1,495 @@
+import { notifyManager } from './notifyManager'
+import { defaultQueryOptions } from './queryClient'
+import { QueryObserver } from './queryObserver'
+import { Subscribable } from './subscribable'
+import {
+ replaceEqualDeep,
+ shallowEqualObjects,
+ shouldThrowError,
+} from './utils'
+import type { QueryClient } from './queryClient'
+import type {
+ ObserverOptionsInput,
+ QueryObserverResultReader,
+} from './queryObserver'
+import type {
+ DefaultedQueryObserverOptions,
+ QueryObserverResult,
+} from './types'
+
+type CombineContext = {
+ result?: Array
+ combine?: CombineFn
+ value?: TCombinedResult
+ queryHashes?: Array
+}
+
+type CombineFn = (
+ result: Array,
+) => TCombinedResult
+
+type QueriesObserverListener = (result: Array) => void
+
+type QueryObserverMatch = {
+ defaultedQueryOptions: DefaultedQueryObserverOptions
+ observer: QueryObserver
+ reader?: QueryObserverResultReader
+}
+
+/**
+ * Returns the items of `array1` that are not in `array2`.
+ * @param array1 - The items to filter.
+ * @param array2 - The items to exclude.
+ * @returns A new array with the items of `array1` that are not in `array2`.
+ */
+function difference(array1: Array, array2: Array): Array {
+ const excludeSet = new Set(array2)
+ return array1.filter((x) => !excludeSet.has(x))
+}
+
+/**
+ * Compares two arrays of results by position and field value.
+ * @param result - The new results.
+ * @param previous - The previous results, if available.
+ * @returns Whether the results match.
+ */
+function equalResults(
+ result: Array,
+ previous: Array | undefined,
+): boolean {
+ return (
+ !!previous &&
+ result.length === previous.length &&
+ result.every((value, index) => shallowEqualObjects(value, previous[index]))
+ )
+}
+
+/**
+ * A `QueriesObserver` watches an array of queries at once, exposing them as
+ * a single array of `QueryObserverResult`s (or, when a `combine` option is
+ * given, as a combined value derived from that array). It manages one
+ * internal `QueryObserver` per query, and is the primitive that framework
+ * adapters (e.g. `useQueries`) build their hooks on top of.
+ * @example
+ * ```ts
+ * const observer = new QueriesObserver(queryClient, [
+ * { queryKey: ['post', 1], queryFn: fetchPost },
+ * { queryKey: ['post', 2], queryFn: fetchPost },
+ * ])
+ *
+ * const unsubscribe = observer.subscribe((result) => {
+ * console.log(result)
+ * })
+ * ```
+ */
+export class QueriesObserver<
+ TCombinedResult = Array,
+> extends Subscribable {
+ #client: QueryClient
+ #result: Array
+ #options?: QueriesObserverOptions
+ #observers: Array
+ #combinedResult?: TCombinedResult
+ #combineContext: CombineContext = {}
+ #observerMatches: Array = []
+ #updatingQueries = false
+
+ constructor(
+ client: QueryClient,
+ queries: Array>,
+ options?: QueriesObserverOptions,
+ ) {
+ super()
+
+ this.#client = client
+ this.#options = options
+ this.#observers = []
+ this.#result = []
+
+ this.setQueries(queries)
+ }
+
+ protected override onSubscribe(): void {
+ if (this.listeners.size === 1) {
+ this.#observers.forEach((observer) => this.#subscribeTo(observer))
+ }
+ }
+
+ protected override onUnsubscribe(): void {
+ if (!this.listeners.size) {
+ this.destroy()
+ }
+ }
+
+ /**
+ * Stops observing all queries: clears all listeners and destroys every
+ * underlying `QueryObserver` this observer manages.
+ */
+ destroy(): void {
+ this.listeners = new Set()
+ this.#observers.forEach((observer) => {
+ observer.destroy()
+ })
+ }
+
+ /**
+ * Replaces the set of queries being observed. Existing `QueryObserver`s
+ * are reused for queries that match an already-observed query hash;
+ * observers for queries that are no longer present are destroyed, and new
+ * observers are created and subscribed to for newly added queries.
+ * @param queries - The options of the queries to observe.
+ * @param options - Replaces the observer's options, e.g. its `combine` function.
+ * @example
+ * ```ts
+ * observer.setQueries([
+ * { queryKey: ['post', 1], queryFn: fetchPost },
+ * { queryKey: ['post', 3], queryFn: fetchPost },
+ * ])
+ * ```
+ */
+ setQueries(
+ queries: Array,
+ options?: QueriesObserverOptions,
+ ): void {
+ this.#setQueries(this.#findMatchingObservers(queries), options)
+ }
+
+ #setQueries(
+ newObserverMatches: Array,
+ options?: QueriesObserverOptions,
+ ): void {
+ this.#options = options
+
+ if (process.env.NODE_ENV !== 'production') {
+ const queryHashes = newObserverMatches.map(
+ (match) => match.defaultedQueryOptions.queryHash,
+ )
+ if (new Set(queryHashes).size !== queryHashes.length) {
+ console.warn(
+ '[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.',
+ )
+ }
+ }
+
+ notifyManager.batch(() => {
+ const prevObservers = this.#observers
+
+ // Apply all options before combining or notifying with the new results.
+ this.#updatingQueries = true
+ try {
+ newObserverMatches.forEach((match) => {
+ if (match.reader) {
+ match.reader.commit()
+ } else {
+ match.observer.setOptions(match.defaultedQueryOptions)
+ }
+ })
+ } finally {
+ this.#updatingQueries = false
+ }
+
+ const newObservers = newObserverMatches.map((match) => match.observer)
+ const newResult = newObservers.map((observer) =>
+ observer.getCurrentResult(),
+ )
+
+ const hasStructuralChange =
+ prevObservers.length !== newObservers.length ||
+ newObservers.some(
+ (observer, index) => observer !== prevObservers[index],
+ )
+
+ if (!hasStructuralChange && equalResults(newResult, this.#result)) return
+
+ if (hasStructuralChange) {
+ this.#observerMatches = newObserverMatches.map(
+ ({ defaultedQueryOptions, observer }) => ({
+ defaultedQueryOptions,
+ observer,
+ }),
+ )
+ this.#observers = newObservers
+ }
+
+ this.#result = newResult
+
+ if (!this.hasListeners()) return
+
+ if (hasStructuralChange) {
+ difference(prevObservers, newObservers).forEach((observer) => {
+ observer.destroy()
+ })
+ difference(newObservers, prevObservers).forEach((observer) =>
+ this.#subscribeTo(observer),
+ )
+ }
+
+ this.#notify()
+ })
+ }
+
+ /**
+ * Returns the most recently computed array of `QueryObserverResult`s, one
+ * per observed query, in the same order as the queries passed to the
+ * constructor or `setQueries`.
+ * @returns The current results.
+ * @example
+ * ```ts
+ * const results = observer.getCurrentResult()
+ * const data = results.map((result) => result.data)
+ * ```
+ */
+ getCurrentResult(): Array {
+ return this.#result
+ }
+
+ /**
+ * Returns the underlying `QueryObserver` instances this observer manages,
+ * in the same order as the queries passed to the constructor or
+ * `setQueries`.
+ * @returns The managed query observers.
+ */
+ getObservers() {
+ return this.#observers
+ }
+
+ /**
+ * Creates a reader for the supplied queries and combine function. Reads keep
+ * result and combine caches local until commit applies the queries and reuses
+ * their computation state. Abandoned readers do not change active observers.
+ * @param queries - The options of the queries to read and commit.
+ * @param options - The combine function used for this reader.
+ * @returns A reader with local snapshot and combine caches.
+ */
+ createResultReader(
+ queries: Array>,
+ options?: QueriesObserverOptions