From ace4b63d0003c7c1e5c5f1e6e3b5ceeb4925ff66 Mon Sep 17 00:00:00 2001 From: Jonghyeon Ko Date: Fri, 27 Nov 2026 19:30:01 +0900 Subject: [PATCH 01/11] feat(react-query): experiment with standalone and pluggable ESM runtimes --- .changeset/react-query-standalone-adapters.md | 8 + .github/workflows/react-query-bundle-size.yml | 73 + integrations/react/bundle-size/README.md | 12 + integrations/react/bundle-size/index.html | 12 + integrations/react/bundle-size/measure.mjs | 114 + integrations/react/bundle-size/package.json | 18 + .../react/bundle-size/public/books-1.json | 1 + .../react/bundle-size/public/books-2.json | 1 + integrations/react/bundle-size/src/books.js | 5 + integrations/react/bundle-size/src/client.js | 3 + integrations/react/bundle-size/src/main.jsx | 12 + .../react/bundle-size/src/paginated.jsx | 46 + .../react/bundle-size/src/plugin-client.js | 5 + integrations/react/bundle-size/src/query.jsx | 19 + integrations/react/nodenext/package.json | 6 +- .../react/nodenext/src/sharedTypes.ts | 38 + knip.config.ts | 17 + nx.json | 11 + packages/query-core/package.json | 3 + .../query-core/src/__tests__/clientOptions.ts | 2 + .../src/__tests__/queryClient.test-d.tsx | 5 +- packages/query-core/src/environmentManager.ts | 7 +- packages/query-core/src/focusManager.ts | 10 +- packages/query-core/src/hydration.ts | 94 +- .../query-core/src/infiniteQueryObserver.ts | 39 +- packages/query-core/src/mutation.ts | 123 +- packages/query-core/src/mutationCache.ts | 110 +- packages/query-core/src/mutationObserver.ts | 15 +- packages/query-core/src/notifyManager.ts | 16 +- packages/query-core/src/onlineManager.ts | 7 +- packages/query-core/src/queriesObserver.ts | 68 +- packages/query-core/src/query.ts | 239 +- packages/query-core/src/queryCache.ts | 118 +- packages/query-core/src/queryClient.ts | 20 +- packages/query-core/src/queryObserver.ts | 119 +- packages/query-core/src/retryer.ts | 86 +- packages/query-core/src/runtimeBinding.ts | 49 + packages/query-core/src/streamedQuery.ts | 49 +- packages/query-core/src/timeoutManager.ts | 61 +- packages/query-core/src/types.ts | 2468 ++-------------- packages/query-core/src/utils.ts | 148 +- packages/query-core/tsconfig.json | 7 +- packages/query-core/tsconfig.legacy.json | 7 +- packages/query-types/oxlint.config.ts | 7 + packages/query-types/package.json | 57 + packages/query-types/root.oxlint.config.ts | 1 + packages/query-types/root.tsdown.config.js | 1 + packages/query-types/src/binding.ts | 61 + packages/query-types/src/bindings.ts | 235 ++ packages/query-types/src/contracts.ts | 541 ++++ .../query-types/src/environmentManager.ts | 4 + packages/query-types/src/focusManager.ts | 5 + packages/query-types/src/hydration.ts | 89 + packages/query-types/src/index.ts | 555 ++++ .../query-types/src/infiniteQueryObserver.ts | 41 + packages/query-types/src/mutation.ts | 110 + packages/query-types/src/mutationCache.ts | 120 + packages/query-types/src/mutationObserver.ts | 18 + packages/query-types/src/notifyManager.ts | 9 + packages/query-types/src/onlineManager.ts | 5 + packages/query-types/src/queriesObserver.ts | 52 + packages/query-types/src/query.ts | 246 ++ packages/query-types/src/queryCache.ts | 136 + packages/query-types/src/queryClient.ts | 26 + packages/query-types/src/queryObserver.ts | 124 + packages/query-types/src/retryer.ts | 74 + packages/query-types/src/streamedQuery.ts | 55 + packages/query-types/src/symbols.ts | 26 + packages/query-types/src/timeoutManager.ts | 49 + packages/query-types/src/types.ts | 2552 +++++++++++++++++ packages/query-types/src/utils.ts | 117 + packages/query-types/tsconfig.json | 8 + packages/query-types/tsconfig.legacy.json | 8 + packages/query-types/tsconfig.prod.json | 10 + packages/query-types/tsdown.config.ts | 6 + .../react-query-no-core-pluggable/README.md | 46 + .../oxlint.config.ts | 51 + .../package.json | 85 + .../root.oxlint.config.ts | 1 + .../root.tsdown.config.js | 1 + .../src/HydrationBoundary.tsx | 140 + .../src/IsRestoringProvider.ts | 18 + .../src/QueryClientProvider.tsx | 84 + .../src/QueryErrorResetBoundary.tsx | 169 ++ .../src/__tests__/plugins.test.ts | 80 + .../src/errorBoundaryUtils.ts | 103 + .../src/index.ts | 83 + .../src/infiniteQueryOptions.ts | 302 ++ .../src/mutationOptions.ts | 92 + .../src/queryOptions.ts | 242 ++ .../src/runtime/clientFeatures.ts | 40 + .../src/runtime/environmentManager.ts | 41 + .../src/runtime/focusManager.ts | 142 + .../src/runtime/hydration.ts | 368 +++ .../src/runtime/index.ts | 169 ++ .../src/runtime/infiniteQueryBehavior.ts | 187 ++ .../src/runtime/infiniteQueryObserver.ts | 277 ++ .../src/runtime/mutation.ts | 503 ++++ .../src/runtime/mutationCache.ts | 270 ++ .../src/runtime/mutationObserver.ts | 335 +++ .../src/runtime/notifyManager.ts | 148 + .../src/runtime/onlineManager.ts | 120 + .../src/runtime/plugins.ts | 24 + .../src/runtime/queriesObserver.ts | 468 +++ .../src/runtime/query.ts | 878 ++++++ .../src/runtime/queryCache.ts | 298 ++ .../src/runtime/queryClient.ts | 1088 +++++++ .../src/runtime/queryObserver.ts | 1034 +++++++ .../src/runtime/removable.ts | 65 + .../src/runtime/retryer.ts | 241 ++ .../src/runtime/runtimeBinding.ts | 49 + .../src/runtime/streamedQuery.ts | 112 + .../src/runtime/subscribable.ts | 65 + .../src/runtime/timeoutManager.ts | 223 ++ .../src/runtime/types.ts | 459 +++ .../src/runtime/utils.ts | 748 +++++ .../src/suspense.ts | 214 ++ .../src/types.ts | 471 +++ .../src/useBaseQuery.ts | 155 + .../src/useInfiniteQuery.ts | 364 +++ .../src/useIsFetching.ts | 56 + .../src/useMutation.ts | 241 ++ .../src/useMutationState.ts | 205 ++ .../src/usePrefetchInfiniteQuery.tsx | 72 + .../src/usePrefetchQuery.tsx | 59 + .../src/useQueries.ts | 487 ++++ .../src/useQuery.ts | 297 ++ .../src/useSuspenseInfiniteQuery.ts | 184 ++ .../src/useSuspenseQueries.ts | 548 ++++ .../src/useSuspenseQuery.ts | 150 + .../test-setup.ts | 16 + .../tests/compat-client.ts | 15 + .../tsconfig.json | 16 + .../tsconfig.legacy.json | 9 + .../tsconfig.prod.json | 10 + .../tsdown.config.ts | 8 + .../vite.config.ts | 33 + packages/react-query-no-core/README.md | 31 + packages/react-query-no-core/oxlint.config.ts | 51 + packages/react-query-no-core/package.json | 80 + .../react-query-no-core/root.oxlint.config.ts | 1 + .../react-query-no-core/root.tsdown.config.js | 1 + .../src/HydrationBoundary.tsx | 140 + .../src/IsRestoringProvider.ts | 18 + .../src/QueryClientProvider.tsx | 84 + .../src/QueryErrorResetBoundary.tsx | 169 ++ .../src/errorBoundaryUtils.ts | 103 + packages/react-query-no-core/src/index.ts | 83 + .../src/infiniteQueryOptions.ts | 302 ++ .../src/mutationOptions.ts | 92 + .../react-query-no-core/src/queryOptions.ts | 242 ++ .../src/runtime/environmentManager.ts | 41 + .../src/runtime/focusManager.ts | 142 + .../src/runtime/hydration.ts | 368 +++ .../react-query-no-core/src/runtime/index.ts | 167 ++ .../src/runtime/infiniteQueryBehavior.ts | 187 ++ .../src/runtime/infiniteQueryObserver.ts | 277 ++ .../src/runtime/mutation.ts | 503 ++++ .../src/runtime/mutationCache.ts | 270 ++ .../src/runtime/mutationObserver.ts | 331 +++ .../src/runtime/notifyManager.ts | 148 + .../src/runtime/onlineManager.ts | 120 + .../src/runtime/queriesObserver.ts | 468 +++ .../react-query-no-core/src/runtime/query.ts | 872 ++++++ .../src/runtime/queryCache.ts | 298 ++ .../src/runtime/queryClient.ts | 1077 +++++++ .../src/runtime/queryObserver.ts | 1034 +++++++ .../src/runtime/removable.ts | 65 + .../src/runtime/retryer.ts | 241 ++ .../src/runtime/runtimeBinding.ts | 49 + .../src/runtime/streamedQuery.ts | 112 + .../src/runtime/subscribable.ts | 65 + .../src/runtime/timeoutManager.ts | 223 ++ .../react-query-no-core/src/runtime/types.ts | 456 +++ .../react-query-no-core/src/runtime/utils.ts | 748 +++++ packages/react-query-no-core/src/suspense.ts | 214 ++ packages/react-query-no-core/src/types.ts | 471 +++ .../react-query-no-core/src/useBaseQuery.ts | 146 + .../src/useInfiniteQuery.ts | 364 +++ .../react-query-no-core/src/useIsFetching.ts | 56 + .../react-query-no-core/src/useMutation.ts | 241 ++ .../src/useMutationState.ts | 205 ++ .../src/useObserverSnapshot.ts | 43 + .../src/usePrefetchInfiniteQuery.tsx | 72 + .../src/usePrefetchQuery.tsx | 59 + .../react-query-no-core/src/useQueries.ts | 480 ++++ packages/react-query-no-core/src/useQuery.ts | 297 ++ .../src/useSuspenseInfiniteQuery.ts | 184 ++ .../src/useSuspenseQueries.ts | 548 ++++ .../src/useSuspenseQuery.ts | 145 + packages/react-query-no-core/tsconfig.json | 15 + .../react-query-no-core/tsconfig.legacy.json | 9 + .../react-query-no-core/tsconfig.prod.json | 10 + packages/react-query-no-core/tsdown.config.ts | 8 + .../src/__tests__/mutationOptions.test.tsx | 3 +- pnpm-lock.yaml | 100 + scripts/react-query-compat.config.ts | 34 + scripts/test-react-query-compat.mjs | 91 + 198 files changed, 33215 insertions(+), 3317 deletions(-) create mode 100644 .changeset/react-query-standalone-adapters.md create mode 100644 .github/workflows/react-query-bundle-size.yml create mode 100644 integrations/react/bundle-size/README.md create mode 100644 integrations/react/bundle-size/index.html create mode 100644 integrations/react/bundle-size/measure.mjs create mode 100644 integrations/react/bundle-size/package.json create mode 100644 integrations/react/bundle-size/public/books-1.json create mode 100644 integrations/react/bundle-size/public/books-2.json create mode 100644 integrations/react/bundle-size/src/books.js create mode 100644 integrations/react/bundle-size/src/client.js create mode 100644 integrations/react/bundle-size/src/main.jsx create mode 100644 integrations/react/bundle-size/src/paginated.jsx create mode 100644 integrations/react/bundle-size/src/plugin-client.js create mode 100644 integrations/react/bundle-size/src/query.jsx create mode 100644 integrations/react/nodenext/src/sharedTypes.ts create mode 100644 packages/query-core/src/__tests__/clientOptions.ts create mode 100644 packages/query-core/src/runtimeBinding.ts create mode 100644 packages/query-types/oxlint.config.ts create mode 100644 packages/query-types/package.json create mode 120000 packages/query-types/root.oxlint.config.ts create mode 120000 packages/query-types/root.tsdown.config.js create mode 100644 packages/query-types/src/binding.ts create mode 100644 packages/query-types/src/bindings.ts create mode 100644 packages/query-types/src/contracts.ts create mode 100644 packages/query-types/src/environmentManager.ts create mode 100644 packages/query-types/src/focusManager.ts create mode 100644 packages/query-types/src/hydration.ts create mode 100644 packages/query-types/src/index.ts create mode 100644 packages/query-types/src/infiniteQueryObserver.ts create mode 100644 packages/query-types/src/mutation.ts create mode 100644 packages/query-types/src/mutationCache.ts create mode 100644 packages/query-types/src/mutationObserver.ts create mode 100644 packages/query-types/src/notifyManager.ts create mode 100644 packages/query-types/src/onlineManager.ts create mode 100644 packages/query-types/src/queriesObserver.ts create mode 100644 packages/query-types/src/query.ts create mode 100644 packages/query-types/src/queryCache.ts create mode 100644 packages/query-types/src/queryClient.ts create mode 100644 packages/query-types/src/queryObserver.ts create mode 100644 packages/query-types/src/retryer.ts create mode 100644 packages/query-types/src/streamedQuery.ts create mode 100644 packages/query-types/src/symbols.ts create mode 100644 packages/query-types/src/timeoutManager.ts create mode 100644 packages/query-types/src/types.ts create mode 100644 packages/query-types/src/utils.ts create mode 100644 packages/query-types/tsconfig.json create mode 100644 packages/query-types/tsconfig.legacy.json create mode 100644 packages/query-types/tsconfig.prod.json create mode 100644 packages/query-types/tsdown.config.ts create mode 100644 packages/react-query-no-core-pluggable/README.md create mode 100644 packages/react-query-no-core-pluggable/oxlint.config.ts create mode 100644 packages/react-query-no-core-pluggable/package.json create mode 120000 packages/react-query-no-core-pluggable/root.oxlint.config.ts create mode 120000 packages/react-query-no-core-pluggable/root.tsdown.config.js create mode 100644 packages/react-query-no-core-pluggable/src/HydrationBoundary.tsx create mode 100644 packages/react-query-no-core-pluggable/src/IsRestoringProvider.ts create mode 100644 packages/react-query-no-core-pluggable/src/QueryClientProvider.tsx create mode 100644 packages/react-query-no-core-pluggable/src/QueryErrorResetBoundary.tsx create mode 100644 packages/react-query-no-core-pluggable/src/__tests__/plugins.test.ts create mode 100644 packages/react-query-no-core-pluggable/src/errorBoundaryUtils.ts create mode 100644 packages/react-query-no-core-pluggable/src/index.ts create mode 100644 packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts create mode 100644 packages/react-query-no-core-pluggable/src/mutationOptions.ts create mode 100644 packages/react-query-no-core-pluggable/src/queryOptions.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/clientFeatures.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/environmentManager.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/focusManager.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/hydration.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/index.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/infiniteQueryBehavior.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/infiniteQueryObserver.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/mutation.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/mutationObserver.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/notifyManager.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/onlineManager.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/plugins.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/queriesObserver.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/query.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/queryCache.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/queryClient.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/removable.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/retryer.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/streamedQuery.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/subscribable.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/types.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/utils.ts create mode 100644 packages/react-query-no-core-pluggable/src/suspense.ts create mode 100644 packages/react-query-no-core-pluggable/src/types.ts create mode 100644 packages/react-query-no-core-pluggable/src/useBaseQuery.ts create mode 100644 packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts create mode 100644 packages/react-query-no-core-pluggable/src/useIsFetching.ts create mode 100644 packages/react-query-no-core-pluggable/src/useMutation.ts create mode 100644 packages/react-query-no-core-pluggable/src/useMutationState.ts create mode 100644 packages/react-query-no-core-pluggable/src/usePrefetchInfiniteQuery.tsx create mode 100644 packages/react-query-no-core-pluggable/src/usePrefetchQuery.tsx create mode 100644 packages/react-query-no-core-pluggable/src/useQueries.ts create mode 100644 packages/react-query-no-core-pluggable/src/useQuery.ts create mode 100644 packages/react-query-no-core-pluggable/src/useSuspenseInfiniteQuery.ts create mode 100644 packages/react-query-no-core-pluggable/src/useSuspenseQueries.ts create mode 100644 packages/react-query-no-core-pluggable/src/useSuspenseQuery.ts create mode 100644 packages/react-query-no-core-pluggable/test-setup.ts create mode 100644 packages/react-query-no-core-pluggable/tests/compat-client.ts create mode 100644 packages/react-query-no-core-pluggable/tsconfig.json create mode 100644 packages/react-query-no-core-pluggable/tsconfig.legacy.json create mode 100644 packages/react-query-no-core-pluggable/tsconfig.prod.json create mode 100644 packages/react-query-no-core-pluggable/tsdown.config.ts create mode 100644 packages/react-query-no-core-pluggable/vite.config.ts create mode 100644 packages/react-query-no-core/README.md create mode 100644 packages/react-query-no-core/oxlint.config.ts create mode 100644 packages/react-query-no-core/package.json create mode 120000 packages/react-query-no-core/root.oxlint.config.ts create mode 120000 packages/react-query-no-core/root.tsdown.config.js create mode 100644 packages/react-query-no-core/src/HydrationBoundary.tsx create mode 100644 packages/react-query-no-core/src/IsRestoringProvider.ts create mode 100644 packages/react-query-no-core/src/QueryClientProvider.tsx create mode 100644 packages/react-query-no-core/src/QueryErrorResetBoundary.tsx create mode 100644 packages/react-query-no-core/src/errorBoundaryUtils.ts create mode 100644 packages/react-query-no-core/src/index.ts create mode 100644 packages/react-query-no-core/src/infiniteQueryOptions.ts create mode 100644 packages/react-query-no-core/src/mutationOptions.ts create mode 100644 packages/react-query-no-core/src/queryOptions.ts create mode 100644 packages/react-query-no-core/src/runtime/environmentManager.ts create mode 100644 packages/react-query-no-core/src/runtime/focusManager.ts create mode 100644 packages/react-query-no-core/src/runtime/hydration.ts create mode 100644 packages/react-query-no-core/src/runtime/index.ts create mode 100644 packages/react-query-no-core/src/runtime/infiniteQueryBehavior.ts create mode 100644 packages/react-query-no-core/src/runtime/infiniteQueryObserver.ts create mode 100644 packages/react-query-no-core/src/runtime/mutation.ts create mode 100644 packages/react-query-no-core/src/runtime/mutationCache.ts create mode 100644 packages/react-query-no-core/src/runtime/mutationObserver.ts create mode 100644 packages/react-query-no-core/src/runtime/notifyManager.ts create mode 100644 packages/react-query-no-core/src/runtime/onlineManager.ts create mode 100644 packages/react-query-no-core/src/runtime/queriesObserver.ts create mode 100644 packages/react-query-no-core/src/runtime/query.ts create mode 100644 packages/react-query-no-core/src/runtime/queryCache.ts create mode 100644 packages/react-query-no-core/src/runtime/queryClient.ts create mode 100644 packages/react-query-no-core/src/runtime/queryObserver.ts create mode 100644 packages/react-query-no-core/src/runtime/removable.ts create mode 100644 packages/react-query-no-core/src/runtime/retryer.ts create mode 100644 packages/react-query-no-core/src/runtime/runtimeBinding.ts create mode 100644 packages/react-query-no-core/src/runtime/streamedQuery.ts create mode 100644 packages/react-query-no-core/src/runtime/subscribable.ts create mode 100644 packages/react-query-no-core/src/runtime/timeoutManager.ts create mode 100644 packages/react-query-no-core/src/runtime/types.ts create mode 100644 packages/react-query-no-core/src/runtime/utils.ts create mode 100644 packages/react-query-no-core/src/suspense.ts create mode 100644 packages/react-query-no-core/src/types.ts create mode 100644 packages/react-query-no-core/src/useBaseQuery.ts create mode 100644 packages/react-query-no-core/src/useInfiniteQuery.ts create mode 100644 packages/react-query-no-core/src/useIsFetching.ts create mode 100644 packages/react-query-no-core/src/useMutation.ts create mode 100644 packages/react-query-no-core/src/useMutationState.ts create mode 100644 packages/react-query-no-core/src/useObserverSnapshot.ts create mode 100644 packages/react-query-no-core/src/usePrefetchInfiniteQuery.tsx create mode 100644 packages/react-query-no-core/src/usePrefetchQuery.tsx create mode 100644 packages/react-query-no-core/src/useQueries.ts create mode 100644 packages/react-query-no-core/src/useQuery.ts create mode 100644 packages/react-query-no-core/src/useSuspenseInfiniteQuery.ts create mode 100644 packages/react-query-no-core/src/useSuspenseQueries.ts create mode 100644 packages/react-query-no-core/src/useSuspenseQuery.ts create mode 100644 packages/react-query-no-core/tsconfig.json create mode 100644 packages/react-query-no-core/tsconfig.legacy.json create mode 100644 packages/react-query-no-core/tsconfig.prod.json create mode 100644 packages/react-query-no-core/tsdown.config.ts create mode 100644 scripts/react-query-compat.config.ts create mode 100644 scripts/test-react-query-compat.mjs diff --git a/.changeset/react-query-standalone-adapters.md b/.changeset/react-query-standalone-adapters.md new file mode 100644 index 00000000000..bb67c7e3652 --- /dev/null +++ b/.changeset/react-query-standalone-adapters.md @@ -0,0 +1,8 @@ +--- +'@tanstack/query-types': minor +'@tanstack/query-core': patch +'@tanstack/react-query-no-core': minor +'@tanstack/react-query-no-core-pluggable': minor +--- + +Add experimental ESM React Query adapters with an integrated query runtime. The pluggable adapter lets applications opt in to mutations and infinite queries per client. All three runtimes share their TypeScript definitions through `@tanstack/query-types`. diff --git a/.github/workflows/react-query-bundle-size.yml b/.github/workflows/react-query-bundle-size.yml new file mode 100644 index 00000000000..b5ccaef0704 --- /dev/null +++ b/.github/workflows/react-query-bundle-size.yml @@ -0,0 +1,73 @@ +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-types/**' + - 'packages/react-query/**' + - 'packages/react-query-no-core*/**' + - '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 }} + 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: Build workspace dependencies + run: pnpm --filter '@tanstack/query-integration-react-bundle-size^...' run build + - name: Build and measure production apps + id: measure + 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" + 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 }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + REPORT: ${{ needs.measure.outputs.report }} + 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" --arg sha "$HEAD_SHA" --argjson report "$REPORT" \ + '{body: ($marker + "\n" + $report + "\nMeasured commit `" + $sha + "`.")}' | + gh api --silent --method "$method" "$endpoint" --input - diff --git a/integrations/react/bundle-size/README.md b/integrations/react/bundle-size/README.md new file mode 100644 index 00000000000..d95d0412680 --- /dev/null +++ b/integrations/react/bundle-size/README.md @@ -0,0 +1,12 @@ +# React Query app bundle size + +This workspace builds two browser apps against each adapter’s public package entry point. The read-only app fetches a book list. The paginated app fetches additional pages and saves bookmarks in browser storage. All three builds of each app include React and React DOM. The paginated pluggable build registers the mutation and infinite-query plugins. + +Run from the repository root after installing the workspace dependencies: + +```sh +pnpm --filter '@tanstack/query-integration-react-bundle-size^...' run build +pnpm --filter @tanstack/query-integration-react-bundle-size run measure +``` + +The report at `integrations/react/bundle-size/dist/report.md` shows total emitted JavaScript bytes and the sum of individually compressed chunks for gzip and Brotli. Each percentage uses the original adapter’s application size for that workload as its denominator. Serve a directory under `dist//` to try the built app. diff --git a/integrations/react/bundle-size/index.html b/integrations/react/bundle-size/index.html new file mode 100644 index 00000000000..43cc6a8fab6 --- /dev/null +++ b/integrations/react/bundle-size/index.html @@ -0,0 +1,12 @@ + + + + + + Reading list + + +
+ + + diff --git a/integrations/react/bundle-size/measure.mjs b/integrations/react/bundle-size/measure.mjs new file mode 100644 index 00000000000..832a2cf0819 --- /dev/null +++ b/integrations/react/bundle-size/measure.mjs @@ -0,0 +1,114 @@ +import { readFile, writeFile } from 'node:fs/promises' +import path from 'node:path' +import { brotliCompressSync, constants, gzipSync } from 'node:zlib' +import { build } from 'vite' + +const root = import.meta.dirname +const baseline = '@tanstack/react-query' +const pluggable = '@tanstack/react-query-no-core-pluggable' +const packages = [baseline, '@tanstack/react-query-no-core', pluggable] +const workloads = [ + { screen: 'query', title: 'Read-only list · useQuery' }, + { + screen: 'paginated', + title: + 'Paginated list with bookmarks · useQuery, useMutation, useInfiniteQuery', + }, +] + +async function measure(packageName, screen) { + const withPlugins = packageName === pluggable && screen === 'paginated' + const outDir = path.join(root, 'dist', screen, packageName.split('/')[1]) + const result = await build({ + root, + base: './', + configFile: false, + mode: 'production', + logLevel: 'warn', + resolve: { + alias: { + '#adapter': packageName, + '#client': path.join( + root, + 'src', + withPlugins ? 'plugin-client.js' : 'client.js', + ), + '#screen': path.join(root, 'src', `${screen}.jsx`), + }, + }, + build: { + outDir, + emptyOutDir: true, + reportCompressedSize: false, + // All modules in these apps execute on the client. + rolldownOptions: { checks: { moduleLevelDirective: false } }, + }, + }) + const chunks = result.output.filter((output) => output.type === 'chunk') + if (!chunks.some((chunk) => chunk.isEntry)) { + throw new Error(`Missing browser entry chunk for ${packageName}`) + } + if ( + packageName !== baseline && + chunks.some((chunk) => + Object.keys(chunk.modules).some((id) => + /\/(?:packages|node_modules\/@tanstack)\/query-core\//.test(id), + ), + ) + ) { + throw new Error(`${packageName} bundled @tanstack/query-core`) + } + + const sizes = { raw: 0, gzip: 0, brotli: 0 } + for (const chunk of chunks) { + const js = await readFile(path.join(outDir, chunk.fileName)) + sizes.raw += js.length + sizes.gzip += gzipSync(js, { level: 9 }).length + sizes.brotli += brotliCompressSync(js, { + params: { [constants.BROTLI_PARAM_QUALITY]: 11 }, + }).length + } + return sizes +} + +const integer = new Intl.NumberFormat('en-US') +function formatSize(bytes, baselineBytes, isBaseline) { + const size = `${integer.format(bytes)} B` + if (isBaseline) return size + const difference = bytes - baselineBytes + const sign = difference > 0 ? '+' : '' + const percent = ((100 * difference) / baselineBytes).toFixed(2) + return `${size} (${sign}${integer.format(difference)} B, ${sign}${percent}%)` +} + +const lines = [ + '## React Query app bundle size', + '', + 'Each row includes React, React DOM and the same production Vite app. Changes are relative to `@tanstack/react-query` in the same workload and commit. A negative change is a saving.', +] +for (const { screen, title } of workloads) { + lines.push( + '', + `### ${title}`, + '', + '| Package | Minified JS | Gzip | Brotli |', + '| --- | ---: | ---: | ---: |', + ) + let baselineSizes + for (const name of packages) { + const sizes = await measure(name, screen) + baselineSizes ??= sizes + const cells = Object.entries(sizes).map(([key, value]) => + formatSize(value, baselineSizes[key], name === baseline), + ) + lines.push(`| \`${name}\` | ${cells.join(' | ')} |`) + } +} +lines.push( + '', + 'Gzip level 9 and Brotli quality 11 are applied to each JavaScript chunk before summing. The pluggable client registers mutation and infinite-query support for the paginated workload.', + '', +) +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/package.json b/integrations/react/bundle-size/package.json new file mode 100644 index 00000000000..08a97f91b07 --- /dev/null +++ b/integrations/react/bundle-size/package.json @@ -0,0 +1,18 @@ +{ + "name": "@tanstack/query-integration-react-bundle-size", + "private": true, + "type": "module", + "scripts": { + "measure": "node measure.mjs" + }, + "dependencies": { + "@tanstack/react-query": "workspace:*", + "@tanstack/react-query-no-core": "workspace:*", + "@tanstack/react-query-no-core-pluggable": "workspace:*", + "react": "catalog:", + "react-dom": "catalog:" + }, + "devDependencies": { + "vite": "^8.3.8" + } +} 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.js b/integrations/react/bundle-size/src/books.js new file mode 100644 index 00000000000..d15211e5647 --- /dev/null +++ b/integrations/react/bundle-size/src/books.js @@ -0,0 +1,5 @@ +export async function fetchBooks(page, signal) { + const response = await fetch(`./books-${page}.json`, { signal }) + if (!response.ok) throw new Error(`Could not load page ${page}`) + return response.json() +} diff --git a/integrations/react/bundle-size/src/client.js b/integrations/react/bundle-size/src/client.js new file mode 100644 index 00000000000..723f2492e93 --- /dev/null +++ b/integrations/react/bundle-size/src/client.js @@ -0,0 +1,3 @@ +import { QueryClient } from '#adapter' + +export const client = new QueryClient() diff --git a/integrations/react/bundle-size/src/main.jsx b/integrations/react/bundle-size/src/main.jsx new file mode 100644 index 00000000000..cc09878b2a1 --- /dev/null +++ b/integrations/react/bundle-size/src/main.jsx @@ -0,0 +1,12 @@ +import * as React from 'react' +import { createRoot } from 'react-dom/client' +import { QueryClientProvider } from '#adapter' +import { client } from '#client' +import { ReadingList } from '#screen' + +createRoot(document.getElementById('root')).render( + +

Reading list

+ +
, +) diff --git a/integrations/react/bundle-size/src/paginated.jsx b/integrations/react/bundle-size/src/paginated.jsx new file mode 100644 index 00000000000..2cd97823030 --- /dev/null +++ b/integrations/react/bundle-size/src/paginated.jsx @@ -0,0 +1,46 @@ +import * as React from 'react' +import { useInfiniteQuery, useMutation, useQuery } from '#adapter' +import { fetchBooks } from './books.js' + +export function ReadingList() { + const books = useInfiniteQuery({ + queryKey: ['books'], + queryFn: ({ pageParam, signal }) => fetchBooks(pageParam, signal), + initialPageParam: 1, + getNextPageParam: (lastPage) => lastPage.next, + }) + const bookmark = useQuery({ + queryKey: ['bookmark'], + queryFn: () => localStorage.getItem('bookmark'), + }) + const save = useMutation({ + mutationFn: async (title) => localStorage.setItem('bookmark', title), + onSuccess: () => bookmark.refetch(), + }) + if (books.isPending) return

Loading books…

+ if (books.isError) 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/plugin-client.js b/integrations/react/bundle-size/src/plugin-client.js new file mode 100644 index 00000000000..d6b5b1ce612 --- /dev/null +++ b/integrations/react/bundle-size/src/plugin-client.js @@ -0,0 +1,5 @@ +import { QueryClient, infiniteQueryPlugin, mutationPlugin } from '#adapter' + +export const client = new QueryClient({ + plugins: [mutationPlugin, infiniteQueryPlugin], +}) diff --git a/integrations/react/bundle-size/src/query.jsx b/integrations/react/bundle-size/src/query.jsx new file mode 100644 index 00000000000..18f4324e063 --- /dev/null +++ b/integrations/react/bundle-size/src/query.jsx @@ -0,0 +1,19 @@ +import * as React from 'react' +import { useQuery } from '#adapter' +import { fetchBooks } from './books.js' + +export function ReadingList() { + const books = useQuery({ + queryKey: ['books', 1], + queryFn: ({ signal }) => fetchBooks(1, signal), + }) + if (books.isPending) return

Loading books…

+ if (books.isError) return

{books.error.message}

+ return ( +
    + {books.data.titles.map((title) => ( +
  • {title}
  • + ))} +
+ ) +} diff --git a/integrations/react/nodenext/package.json b/integrations/react/nodenext/package.json index c587035a285..f1c00328c42 100644 --- a/integrations/react/nodenext/package.json +++ b/integrations/react/nodenext/package.json @@ -9,7 +9,11 @@ "test:types:ts71": "node ../../../node_modules/typescript71/lib/tsc.js --pretty false --project tsconfig.json" }, "dependencies": { - "@tanstack/react-query": "workspace:*" + "@tanstack/query-core": "workspace:*", + "@tanstack/query-types": "workspace:*", + "@tanstack/react-query": "workspace:*", + "@tanstack/react-query-no-core": "workspace:*", + "@tanstack/react-query-no-core-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..c26755fec1d --- /dev/null +++ b/integrations/react/nodenext/src/sharedTypes.ts @@ -0,0 +1,38 @@ +import { QueryClient as CoreClient } from '@tanstack/query-core' +import { QueryClient, queryOptions } from '@tanstack/react-query-no-core' +import { QueryClient as PluggableClient } from '@tanstack/react-query-no-core-pluggable' +import type { QueryMeta as CoreMeta } from '@tanstack/query-core' +import type { QueryMeta } from '@tanstack/query-types' +import type { QueryMeta as DirectMeta } from '@tanstack/react-query-no-core' +import type { QueryMeta as PluggableMeta } from '@tanstack/react-query-no-core-pluggable' + +type BookMeta = { shelf: string } + +declare module '@tanstack/query-types' { + interface Register { + queryMeta: BookMeta + } +} + +type Assert = Matches +type Same = [A, B] extends [B, A] ? true : false + +// Consumers can augment the shared Register once for each runtime. +export type SharedMetadata = [ + Assert>, + Assert>, + Assert>, + Assert>, +] + +const book = queryOptions({ queryKey: ['book'], queryFn: () => 'Dune' }) + +// The unique symbols on a tagged key carry its data type across packages. +export const fromCore: string | undefined = new CoreClient().getQueryData( + book.queryKey, +) +export const fromDirect: string | undefined = new QueryClient().getQueryData( + book.queryKey, +) +export const fromPluggable: string | undefined = + new PluggableClient().getQueryData(book.queryKey) diff --git a/knip.config.ts b/knip.config.ts index 802c9b9a485..9ed4a6cd8a9 100644 --- a/knip.config.ts +++ b/knip.config.ts @@ -1,5 +1,7 @@ import reactQueryDevtools from './packages/react-query-devtools/package.json' import reactQueryNextExperimental from './packages/react-query-next-experimental/package.json' +import reactQueryPluggable from './packages/react-query-no-core-pluggable/package.json' +import reactQueryNoCore from './packages/react-query-no-core/package.json' import reactQueryPersistClient from './packages/react-query-persist-client/package.json' import reactQuery from './packages/react-query/package.json' import type { KnipConfig } from 'knip' @@ -14,6 +16,13 @@ const optionalPeerDependencies = (pkg: { .filter((dependency) => dependency in pkg.peerDependencies) .map((dependency) => `${dependency}!`) +// The compatibility runner creates test entry points for the adapter and runtime +// modules imported by the upstream suites. +const compatibilityEntries = [ + 'src/suspense.ts', + 'src/runtime/{query,notifyManager,timeoutManager,utils}.ts', +] + export default { ignore: [ 'scripts/*.{j,t}s', @@ -41,6 +50,14 @@ export default { 'packages/react-query': { ignoreDependencies: optionalPeerDependencies(reactQuery), }, + 'packages/react-query-no-core': { + entry: compatibilityEntries, + ignoreDependencies: optionalPeerDependencies(reactQueryNoCore), + }, + 'packages/react-query-no-core-pluggable': { + entry: [...compatibilityEntries, 'tests/compat-client.ts'], + ignoreDependencies: optionalPeerDependencies(reactQueryPluggable), + }, 'packages/react-query-devtools': { ignoreDependencies: optionalPeerDependencies(reactQueryDevtools), }, diff --git a/nx.json b/nx.json index 84ef0aa852b..c66d9f0bfa1 100644 --- a/nx.json +++ b/nx.json @@ -24,6 +24,17 @@ "!{projectRoot}/tests/**/*", "!{projectRoot}/eslint.config.js", "!{projectRoot}/oxlint.config.ts" + ], + "reactQueryCompatibility": [ + "{workspaceRoot}/scripts/test-react-query-compat.mjs", + "{workspaceRoot}/scripts/react-query-compat.config.ts", + "{workspaceRoot}/packages/query-core/src/__tests__/**/*", + "{workspaceRoot}/packages/query-core/vite.config.ts", + "{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/package.json b/packages/query-core/package.json index b0667e0cf84..8868c00ab15 100644 --- a/packages/query-core/package.json +++ b/packages/query-core/package.json @@ -48,6 +48,9 @@ "src", "!src/__tests__" ], + "dependencies": { + "@tanstack/query-types": "workspace:*" + }, "devDependencies": { "@tanstack/query-test-utils": "workspace:*", "typescript": "catalog:" diff --git a/packages/query-core/src/__tests__/clientOptions.ts b/packages/query-core/src/__tests__/clientOptions.ts new file mode 100644 index 00000000000..5fff2884662 --- /dev/null +++ b/packages/query-core/src/__tests__/clientOptions.ts @@ -0,0 +1,2 @@ +// Packages with an extended client configuration supply their extra keys here. +export type AdapterClientOptions = never diff --git a/packages/query-core/src/__tests__/queryClient.test-d.tsx b/packages/query-core/src/__tests__/queryClient.test-d.tsx index 4a8e15d3db1..62104b8fc65 100644 --- a/packages/query-core/src/__tests__/queryClient.test-d.tsx +++ b/packages/query-core/src/__tests__/queryClient.test-d.tsx @@ -26,6 +26,7 @@ import type { UnsetMarker, } from '../types' import type { MutationFilters, QueryFilters, Updater } from '../utils' +import type { AdapterClientOptions } from './clientOptions' type TypedData = { foo: string } type TypedError = DefaultError & { bar: string } @@ -1157,9 +1158,9 @@ describe('queryClient', () => { assertType>([]) }) - it('should declare exactly its three options', () => { + it('should declare exactly its supported options', () => { expectTypeOf().toEqualTypeOf< - 'queryCache' | 'mutationCache' | 'defaultOptions' + 'queryCache' | 'mutationCache' | 'defaultOptions' | AdapterClientOptions >() }) diff --git a/packages/query-core/src/environmentManager.ts b/packages/query-core/src/environmentManager.ts index 3a8997be946..8768c79d2da 100644 --- a/packages/query-core/src/environmentManager.ts +++ b/packages/query-core/src/environmentManager.ts @@ -1,7 +1,4 @@ -/** - * A function that returns whether the code is running on the server. - */ -export type IsServerValue = () => boolean +import type { IsServerValue } from '@tanstack/query-types/bindings' const defaultIsServer = typeof window === 'undefined' || 'Deno' in globalThis @@ -40,3 +37,5 @@ export const environmentManager = { isServerFn = isServerValue }, } + +export type { IsServerValue } from '@tanstack/query-types/bindings' diff --git a/packages/query-core/src/focusManager.ts b/packages/query-core/src/focusManager.ts index 0dd0c9e8d1a..50495d69580 100644 --- a/packages/query-core/src/focusManager.ts +++ b/packages/query-core/src/focusManager.ts @@ -1,10 +1,8 @@ import { Subscribable } from './subscribable' - -type Listener = (focused: boolean) => void - -type SetupFn = ( - setFocused: (focused?: boolean) => void, -) => (() => void) | undefined +import type { + FocusManagerListener as Listener, + FocusManagerSetupFn as SetupFn, +} from '@tanstack/query-types/bindings' /** * The `FocusManager` manages the focus state within TanStack Query. diff --git a/packages/query-core/src/hydration.ts b/packages/query-core/src/hydration.ts index 49b24a8ed1b..25f4fd5cac7 100644 --- a/packages/query-core/src/hydration.ts +++ b/packages/query-core/src/hydration.ts @@ -1,21 +1,15 @@ import { Mutation } from './mutation' import { noop } from './utils' -import type { MutationState } from './mutation' -import type { Query, QueryState } from './query' -import type { QueryClient } from './queryClient' +import type * as Shared from '@tanstack/query-types/bindings' import type { - DefaultError, - MutationKey, - MutationMeta, - MutationOptions, - MutationScope, - QueryKey, - QueryMeta, - QueryOptions, -} from './types' - -// TYPES -type TransformerFn = (data: any) => any + DehydratedMutation, + DehydratedQuery, + DehydratedState, + TransformerFn, +} from '@tanstack/query-types/bindings' +import type { Query } from './query' +import type { QueryClient } from './queryClient' +import type { QueryRuntime } from './runtimeBinding' /** * Reads the value of a promise synchronously if it has already resolved, e.g. a thenable that @@ -43,73 +37,9 @@ function tryResolveSync(promise: PromiseLike) { return undefined } -/** - * 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 -} +export type DehydrateOptions = Shared.DehydrateOptions -/** - * 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 - } -} - -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' -} - -/** - * 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 -} +export type HydrateOptions = Shared.HydrateOptions // FUNCTIONS @@ -434,3 +364,5 @@ export function hydrate( }, ) } + +export type { DehydratedState } from '@tanstack/query-types/bindings' diff --git a/packages/query-core/src/infiniteQueryObserver.ts b/packages/query-core/src/infiniteQueryObserver.ts index b662821e5ab..8fbd5546791 100644 --- a/packages/query-core/src/infiniteQueryObserver.ts +++ b/packages/query-core/src/infiniteQueryObserver.ts @@ -1,11 +1,17 @@ import { hasNextPage, hasPreviousPage } from './infiniteQueryBehavior' import { QueryObserver } from './queryObserver' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + InfiniteQueryObserverListener, + ReplaceReturnType, +} from '@tanstack/query-types/bindings' import type { Query } from './query' import type { QueryClient } from './queryClient' import type { QueryObserverResultContext, QueryObserverResultReader, } from './queryObserver' +import type { QueryRuntime } from './runtimeBinding' import type { Subscribable } from './subscribable' import type { DefaultError, @@ -14,37 +20,25 @@ import type { FetchPreviousPageOptions, InfiniteData, InfiniteQueryObserverBaseResult, - InfiniteQueryObserverOptions, InfiniteQueryObserverResult, QueryKey, QueryObserverResult, } from './types' -type InfiniteQueryObserverListener = ( - result: InfiniteQueryObserverResult, -) => void - type InfiniteObserverOptionsInput< TQueryFnData, TError, TData, TQueryKey extends QueryKey, TPageParam, -> = - | InfiniteQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - > - | DefaultedInfiniteQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - > +> = Shared.InfiniteObserverOptionsInput< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> /** * An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch @@ -281,8 +275,3 @@ export class InfiniteQueryObserver< return result as InfiniteQueryObserverResult } } - -type ReplaceReturnType< - TFunction extends (...args: Array) => unknown, - TReturn, -> = (...args: Parameters) => TReturn diff --git a/packages/query-core/src/mutation.ts b/packages/query-core/src/mutation.ts index 0c7690b84b8..79a3c27bf95 100644 --- a/packages/query-core/src/mutation.ts +++ b/packages/query-core/src/mutation.ts @@ -1,121 +1,31 @@ import { notifyManager } from './notifyManager' import { Removable } from './removable' import { createRetryer } from './retryer' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + MutationAction as Action, + MutationState, +} from '@tanstack/query-types/bindings' import type { MutationCache } from './mutationCache' import type { MutationObserver } from './mutationObserver' import type { QueryClient } from './queryClient' import type { Retryer } from './retryer' +import type { QueryRuntime } from './runtimeBinding' import type { DefaultError, MutationFunctionContext, MutationMeta, MutationOptions, - MutationStatus, } from './types' -// TYPES - -interface MutationConfig { - client: QueryClient - mutationId: number - mutationCache: MutationCache - options: MutationOptions - state?: MutationState -} - -/** - * 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 +type MutationConfig = + Shared.MutationConfig< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult + > // CLASS @@ -586,3 +496,8 @@ export function getDefaultState< submittedAt: 0, } } + +export type { + MutationState, + MutationAction as Action, +} from '@tanstack/query-types/bindings' diff --git a/packages/query-core/src/mutationCache.ts b/packages/query-core/src/mutationCache.ts index ae102bfc2b4..f2e4475c64a 100644 --- a/packages/query-core/src/mutationCache.ts +++ b/packages/query-core/src/mutationCache.ts @@ -1,114 +1,18 @@ import { notifyManager } from './notifyManager' import { Subscribable } from './subscribable' import { matchMutation, noop } from './utils' -import type { Action, Mutation } from './mutation' -import type { MutationObserver } from './mutationObserver' -import type { - CacheKeyConfig, - DefaultError, - MutationFunctionContext, - MutationKey, - NotifyEvent, -} from './types' +import type * as Shared from '@tanstack/query-types/bindings' +import type { Mutation } from './mutation' +import type { QueryRuntime } from './runtimeBinding' +import type { DefaultError } from './types' import type { MutationFilters } from './utils' -// TYPES +export type MutationCacheConfig = Shared.MutationCacheConfig -/** - * 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 -} - -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: Action -} - -/** - * 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 + Shared.MutationCacheNotifyEvent -type MutationCacheListener = (event: MutationCacheNotifyEvent) => void +type MutationCacheListener = Shared.MutationCacheListener // CLASS diff --git a/packages/query-core/src/mutationObserver.ts b/packages/query-core/src/mutationObserver.ts index 698416578bf..2feb3590d83 100644 --- a/packages/query-core/src/mutationObserver.ts +++ b/packages/query-core/src/mutationObserver.ts @@ -2,8 +2,10 @@ import { Mutation, getDefaultState } from './mutation' import { notifyManager } from './notifyManager' import { Subscribable } from './subscribable' import { hashKeyByOptions, shallowEqualObjects } from './utils' +import type * as Shared from '@tanstack/query-types/bindings' import type { Action } from './mutation' import type { QueryClient } from './queryClient' +import type { QueryRuntime } from './runtimeBinding' import type { DefaultError, MutateOptions, @@ -12,11 +14,14 @@ import type { MutationObserverResult, } from './types' -// TYPES - -type MutationObserverListener = ( - result: MutationObserverResult, -) => void +type MutationObserverListener = + Shared.MutationObserverListener< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult + > // CLASS diff --git a/packages/query-core/src/notifyManager.ts b/packages/query-core/src/notifyManager.ts index 1155f77841f..97ae9dd8bf3 100644 --- a/packages/query-core/src/notifyManager.ts +++ b/packages/query-core/src/notifyManager.ts @@ -1,12 +1,10 @@ -type NotifyCallback = () => void - -type NotifyFunction = (callback: () => void) => void - -type BatchNotifyFunction = (callback: () => void) => void - -type BatchCallsCallback> = (...args: T) => void - -type ScheduleFunction = (callback: () => void) => void +import type { + BatchCallsCallback, + BatchNotifyFunction, + NotifyCallback, + NotifyFunction, + ScheduleFunction, +} from '@tanstack/query-types/bindings' /** * Default scheduling function used by the notify manager. diff --git a/packages/query-core/src/onlineManager.ts b/packages/query-core/src/onlineManager.ts index f6704ede01a..4548b0fa815 100644 --- a/packages/query-core/src/onlineManager.ts +++ b/packages/query-core/src/onlineManager.ts @@ -1,7 +1,8 @@ import { Subscribable } from './subscribable' - -type Listener = (online: boolean) => void -type SetupFn = (setOnline: Listener) => (() => void) | undefined +import type { + OnlineManagerListener as Listener, + OnlineManagerSetupFn as SetupFn, +} from '@tanstack/query-types/bindings' /** * The `OnlineManager` manages the online state within TanStack Query. It can diff --git a/packages/query-core/src/queriesObserver.ts b/packages/query-core/src/queriesObserver.ts index a1ea988b4f7..1a9392c5ca5 100644 --- a/packages/query-core/src/queriesObserver.ts +++ b/packages/query-core/src/queriesObserver.ts @@ -6,15 +6,18 @@ import { shallowEqualObjects, shouldThrowError, } from './utils' -import type { QueryClient } from './queryClient' -import type { - ObserverOptionsInput, - QueryObserverResultReader, -} from './queryObserver' +import type * as Shared from '@tanstack/query-types/bindings' import type { - DefaultedQueryObserverOptions, - QueryObserverResult, -} from './types' + CombineContext, + CombineFn, + QueriesObserverListener, + QueriesObserverOptions, + QueriesObserverResultReader, +} from '@tanstack/query-types/bindings' +import type { QueryClient } from './queryClient' +import type { ObserverOptionsInput } from './queryObserver' +import type { QueryRuntime } from './runtimeBinding' +import type { QueryObserverResult } from './types' /** * Returns the items of `array1` that are not in `array2`. @@ -44,44 +47,6 @@ function equalResults( ) } -type QueriesObserverListener = (result: Array) => void - -type CombineFn = ( - result: Array, -) => TCombinedResult - -/** A cached reader for multiple query results and their combined value. */ -export interface QueriesObserverResultReader< - TCombinedResult, -> extends QueryObserverResultReader> { - /** Track result properties and combine the results with this reader's options. */ - combineResult: (result: Array) => TCombinedResult -} - -type CombineContext = { - result?: Array - combine?: CombineFn - value?: TCombinedResult - queryHashes?: Array -} - -/** - * Options for a `QueriesObserver` that apply to all of its queries at once. - */ -export interface QueriesObserverOptions< - TCombinedResult = Array, -> { - /** - * A function that combines the array of `QueryObserverResult`s (one per - * observed query) into a single value. The combined value is memoized and - * only recomputed when one of the underlying results, the query hashes, or - * the `combine` function itself changes. - * - * Defaults to returning the array of `QueryObserverResult`s unchanged. - */ - combine?: CombineFn -} - /** * A `QueriesObserver` watches an array of queries at once, exposing them as * a single array of `QueryObserverResult`s (or, when a `combine` option is @@ -495,8 +460,9 @@ export class QueriesObserver< } } -type QueryObserverMatch = { - defaultedQueryOptions: DefaultedQueryObserverOptions - observer: QueryObserver - reader?: QueryObserverResultReader -} +type QueryObserverMatch = Shared.QueryObserverMatch + +export type { + QueriesObserverResultReader, + QueriesObserverOptions, +} from '@tanstack/query-types/bindings' diff --git a/packages/query-core/src/query.ts b/packages/query-core/src/query.ts index 24bff3a6f95..4e7f7e3ceec 100644 --- a/packages/query-core/src/query.ts +++ b/packages/query-core/src/query.ts @@ -11,253 +11,48 @@ import { skipToken, timeUntilStale, } from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + FetchOptions, + QueryAction as Action, + QueryState, +} from '@tanstack/query-types/bindings' import type { QueryCache } from './queryCache' import type { QueryClient } from './queryClient' import type { QueryObserver } from './queryObserver' import type { Retryer } from './retryer' +import type { QueryRuntime } from './runtimeBinding' import type { CancelOptions, DefaultError, - FetchStatus, InitialDataFunction, QueryKey, QueryMeta, QueryOptions, - QueryStatus, SetDataOptions, StaleTime, } from './types' -// TYPES - -interface QueryConfig< +type QueryConfig< TQueryFnData, TError, TData, TQueryKey extends QueryKey = QueryKey, -> { - client: QueryClient - queryKey: TQueryKey - queryHash: string - options?: QueryOptions - defaultOptions?: QueryOptions - state?: QueryState -} - -/** - * The raw state stored on a `Query` instance. This is the underlying state - * that observer results (e.g. `QueryObserverResult`) are derived from. - */ -export interface QueryState { - /** - * The last successfully resolved data for the query. - */ - data: TData | undefined - /** - * The number of times the query has successfully resolved. - */ - dataUpdateCount: number - /** - * The timestamp for when the query most recently returned the `status` as `"success"`. - */ - dataUpdatedAt: number - /** - * The error object for the query, if the last attempt resulted in an error. - * - Defaults to `null`. - */ - error: TError | null - /** - * The sum of all errors, incremented every time the query resolves with an error. - */ - errorUpdateCount: number - /** - * The timestamp for when the query most recently returned the `status` as `"error"`. - */ - errorUpdatedAt: number - /** - * The failure count for the current fetch. - * - Incremented every time the fetch fails. - * - Reset to `0` when the fetch succeeds. - */ - fetchFailureCount: number - /** - * The reason the current fetch failed, as reported by the retryer. - * - Reset to `null` when the fetch succeeds. - */ - fetchFailureReason: TError | null - /** - * Metadata passed to the currently in-flight (or most recent) fetch, e.g. the - * `fetchMore` direction for infinite queries. - */ - fetchMeta: FetchMeta | null - /** - * Whether the query has been marked as invalidated via `invalidate()`. - * - Reset to `false` whenever the query resolves successfully. - */ - isInvalidated: boolean - /** - * The status of the query. - * - `pending` if there's no cached data and no attempt was finished yet. - * - `error` if the last attempt resulted in an error. - * - `success` if the query has data. - */ - status: QueryStatus - /** - * The fetch status of the query. - * - `fetching`: the `queryFn` is currently executing. - * - `paused`: a fetch wanted to run but has been paused (see network mode). - * - `idle`: the query is not fetching. - */ - fetchStatus: FetchStatus -} +> = Shared.QueryConfig -/** - * The context passed to a {@link QueryBehavior}'s `onFetch`, which can replace `fetchFn` to change - * how the query fetches (e.g. to fetch pages for an infinite query). - */ -export interface FetchContext< +export type FetchContext< TQueryFnData, TError, TData, TQueryKey extends QueryKey = QueryKey, -> { - /** - * The function that runs the fetch. By default it calls `queryFn`; `onFetch` can replace it. - */ - fetchFn: () => unknown | Promise - /** - * The options of this fetch. - */ - fetchOptions?: FetchOptions - /** - * The `AbortSignal` that aborts when the fetch is cancelled. - */ - signal: AbortSignal - /** - * The options of the query. - */ - options: QueryOptions - /** - * The `QueryClient` the query belongs to. - */ - client: QueryClient - /** - * The key of the query. - */ - queryKey: TQueryKey - /** - * The state of the query when the fetch starts. - */ - state: QueryState -} +> = Shared.FetchContext -/** - * Customizes how a query fetches, e.g. the behavior that fetches the pages of an infinite query. - */ -export interface QueryBehavior< +export type QueryBehavior< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> { - /** - * Called before each fetch of the query, e.g. to replace `fetchFn` in the context. - */ - onFetch: ( - context: FetchContext, - query: Query, - ) => void -} - -/** - * The direction an infinite query fetches in: `'forward'` for the next page, `'backward'` for the - * previous one. - */ -export type FetchDirection = 'forward' | 'backward' - -/** - * Metadata for a fetch, e.g. the direction when an infinite query fetches more pages. - */ -export interface FetchMeta { - /** - * Set when an infinite query fetches another page, with the direction to fetch in. - */ - fetchMore?: { direction: FetchDirection } -} - -/** - * Options for a single fetch of a query. - */ -export interface FetchOptions { - /** - * If `true`, an in-flight fetch is cancelled before starting a new one, when the query already - * has data. Otherwise, the in-flight fetch is reused. - */ - cancelRefetch?: boolean - /** - * Metadata of the fetch, stored in the query's `fetchMeta` state. - */ - meta?: FetchMeta - /** - * A promise to use for the first attempt instead of calling `fetchFn`, e.g. a pending promise - * restored by `hydrate`. - */ - initialPromise?: Promise -} - -interface FailedAction { - type: 'failed' - failureCount: number - error: TError -} - -interface FetchAction { - type: 'fetch' - meta?: FetchMeta -} - -interface SuccessAction { - data: TData | undefined - type: 'success' - dataUpdatedAt?: number - manual?: boolean -} - -interface ErrorAction { - type: 'error' - error: TError -} - -interface InvalidateAction { - type: 'invalidate' -} - -interface PauseAction { - type: 'pause' -} - -interface ContinueAction { - type: 'continue' -} - -interface SetStateAction { - type: 'setState' - state: Partial> -} - -/** - * The actions a query dispatches to update its state, e.g. when it starts fetching, fails, or - * succeeds. - */ -export type Action = - | ContinueAction - | ErrorAction - | FailedAction - | FetchAction - | InvalidateAction - | PauseAction - | SetStateAction - | SuccessAction +> = Shared.QueryBehavior // CLASS @@ -1105,3 +900,11 @@ function getDefaultState< fetchStatus: 'idle', } } + +export type { + QueryState, + FetchDirection, + FetchMeta, + FetchOptions, + QueryAction as Action, +} from '@tanstack/query-types/bindings' diff --git a/packages/query-core/src/queryCache.ts b/packages/query-core/src/queryCache.ts index 00279784a57..834a79a6eec 100644 --- a/packages/query-core/src/queryCache.ts +++ b/packages/query-core/src/queryCache.ts @@ -2,129 +2,25 @@ import { notifyManager } from './notifyManager' import { Query } from './query' import { Subscribable } from './subscribable' import { hashKeyByOptions, matchQuery } from './utils' -import type { Action, QueryState } from './query' +import type * as Shared from '@tanstack/query-types/bindings' +import type { QueryState } from './query' import type { QueryClient } from './queryClient' -import type { QueryObserver } from './queryObserver' +import type { QueryRuntime } from './runtimeBinding' import type { - CacheKeyConfig, DefaultError, - NotifyEvent, QueryKey, QueryOptions, WithRequired, } from './types' import type { QueryFilters } from './utils' -// TYPES +export type QueryCacheConfig = Shared.QueryCacheConfig -/** - * Global callbacks that fire for every query handled by a `QueryCache`, regardless of which - * component or observer triggered it. Unlike `QueryClient`'s `defaultOptions`, which a query can - * override, these callbacks are always called. Unlike `MutationCacheConfig`'s callbacks, these - * are fire-and-forget: their return value is not awaited before the query settles. - */ -export interface QueryCacheConfig { - /** - * Configures query key comparison and hashing globally. - * `equalityFn` compares individual values during partial matching and defaults to strict equality. - * `hashFn` hashes query keys and defaults to `hashKey`. - */ - queryKey?: CacheKeyConfig - /** Called when any query in the cache encounters an error. */ - onError?: ( - error: DefaultError, - query: Query, - ) => void - /** Called when any query in the cache is successful. */ - onSuccess?: (data: unknown, query: Query) => void - /** Called when any query in the cache is settled, either successfully or with an error. */ - onSettled?: ( - data: unknown | undefined, - error: DefaultError | null, - query: Query, - ) => void -} - -interface NotifyEventQueryAdded extends NotifyEvent { - type: 'added' - query: Query -} - -interface NotifyEventQueryRemoved extends NotifyEvent { - type: 'removed' - query: Query -} +export type QueryCacheNotifyEvent = Shared.QueryCacheNotifyEvent -interface NotifyEventQueryUpdated extends NotifyEvent { - type: 'updated' - query: Query - action: Action -} - -interface NotifyEventQueryObserverAdded extends NotifyEvent { - type: 'observerAdded' - query: Query - observer: QueryObserver -} - -interface NotifyEventQueryObserverRemoved extends NotifyEvent { - type: 'observerRemoved' - query: Query - observer: QueryObserver -} - -interface NotifyEventQueryObserverResultsUpdated extends NotifyEvent { - type: 'observerResultsUpdated' - query: Query -} - -interface NotifyEventQueryObserverOptionsUpdated extends NotifyEvent { - type: 'observerOptionsUpdated' - query: Query - observer: QueryObserver -} +type QueryCacheListener = Shared.QueryCacheListener -/** - * The event passed to a `QueryCache` subscriber. Fired whenever a query is added or removed from - * the cache, its state is updated (e.g. via `query.setState` or `queryClient.removeQueries`), or - * one of its observers is added, removed, or has its results or options updated. - */ -export type QueryCacheNotifyEvent = - | NotifyEventQueryAdded - | NotifyEventQueryRemoved - | NotifyEventQueryUpdated - | NotifyEventQueryObserverAdded - | NotifyEventQueryObserverRemoved - | NotifyEventQueryObserverResultsUpdated - | NotifyEventQueryObserverOptionsUpdated - -type QueryCacheListener = (event: QueryCacheNotifyEvent) => void - -/** - * The store a `QueryCache` keeps its queries in, keyed by query hash. - */ -export interface QueryStore { - /** - * Returns whether a query with the given hash is stored. - */ - has: (queryHash: string) => boolean - /** - * Stores a query under its hash. - */ - set: (queryHash: string, query: Query) => void - /** - * Returns the query with the given hash, if any. - */ - get: (queryHash: string) => Query | undefined - /** - * Removes the query with the given hash. - */ - delete: (queryHash: string) => void - /** - * Returns an iterator over all stored queries. - */ - values: () => IterableIterator -} +export type QueryStore = Shared.QueryStore // CLASS diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index 98b4771382c..481e1ca0c92 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -12,7 +12,10 @@ import { resolveQueryValue, skipToken, } from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { WithoutSkipToken } from '@tanstack/query-types/bindings' import type { QueryState } from './query' +import type { QueryRuntime } from './runtimeBinding' import type { CancelOptions, DefaultError, @@ -32,7 +35,6 @@ import type { QueryExecuteOptions, QueryKey, QueryObserverOptionsBase, - QueryOptions, RefetchOptions, RefetchQueryFilters, ResetOptions, @@ -40,21 +42,9 @@ import type { } from './types' import type { MutationFilters, QueryFilters, Updater } from './utils' -type WithoutSkipToken = Omit & { - queryFn?: Exclude -} - -// TYPES +type QueryDefaults = Shared.QueryDefaults -interface QueryDefaults { - queryKey: QueryKey - defaultOptions: OmitKeyof, 'queryKey'> -} - -interface MutationDefaults { - mutationKey: MutationKey - defaultOptions: MutationOptions -} +type MutationDefaults = Shared.MutationDefaults // CLASS diff --git a/packages/query-core/src/queryObserver.ts b/packages/query-core/src/queryObserver.ts index a76cfc492d8..5ba4e3d5190 100644 --- a/packages/query-core/src/queryObserver.ts +++ b/packages/query-core/src/queryObserver.ts @@ -12,8 +12,16 @@ import { shallowEqualObjects, timeUntilStale, } from './utils' -import type { FetchOptions, Query, QueryState } from './query' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + ObserverFetchOptions, + ProjectionFailure, + QueryObserverListener, + QueryObserverResultReader, +} from '@tanstack/query-types/bindings' +import type { Query, QueryState } from './query' import type { QueryClient } from './queryClient' +import type { QueryRuntime } from './runtimeBinding' import type { ManagedTimerId } from './timeoutManager' import type { DefaultError, @@ -21,113 +29,40 @@ import type { PlaceholderDataFunction, QueryKey, QueryObserverBaseResult, - QueryObserverOptions, QueryObserverOptionsBase, QueryObserverResult, - QueryOptions, RefetchOptions, } from './types' -type QueryObserverListener = ( - result: QueryObserverResult, -) => void - -interface ObserverFetchOptions extends FetchOptions { - throwOnError?: boolean -} - -/** A cached view of an observer for one set of render options. */ -export interface QueryObserverResultReader { - /** Read the result, retaining its reference while all fields are unchanged. */ - getSnapshot: () => TResult - /** Apply this reader's options and reusable computation state after commit. */ - commit: () => void -} - -type ProjectionFailure = { - error: TError - errorUpdatedAt: number -} - -/** - * Selection and placeholder computation state shared by reads of the same result. - * @internal - */ -export interface QueryObserverResultContext< +export type QueryObserverResultContext< TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey, -> { - /** The memo key and failure of the most recent selection. */ - selection?: { - key: { - input: TQueryData - select: (data: TQueryData) => TData - structuralSharing: QueryOptions< - TQueryFnData, - TError, - TQueryData, - TQueryKey - >['structuralSharing'] - } - failure?: ProjectionFailure - } - /** The last successful selection, used if selection fails. */ - selected?: { - data: TData - query?: Query - } - /** The unselected placeholder or factory error. */ - placeholder?: { - key: { - placeholderData: QueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >['placeholderData'] - structuralSharing: QueryOptions< - TQueryFnData, - TError, - TQueryData, - TQueryKey - >['structuralSharing'] - previousQuery: - | Query - | undefined - previousState: QueryState | undefined - previousOptions: - | QueryOptions - | undefined - } - sourceQuery?: Query - input: TQueryData | undefined - failure?: ProjectionFailure - } -} +> = Shared.QueryObserverResultContext< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +> -/** - * Options supplied to an observer by a caller or already resolved by the client. - * @internal - */ export type ObserverOptionsInput< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> = - | QueryObserverOptions - | DefaultedQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - > +> = Shared.ObserverOptionsInput< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +> /** * A `QueryObserver` watches a single query in the `QueryCache` and computes a @@ -1106,3 +1041,5 @@ function isStale( query.isStaleByTime(resolveQueryValue(options.staleTime, query)) ) } + +export type { QueryObserverResultReader } from '@tanstack/query-types/bindings' diff --git a/packages/query-core/src/retryer.ts b/packages/query-core/src/retryer.ts index 3e7ad7bb771..5ac6a5eece1 100644 --- a/packages/query-core/src/retryer.ts +++ b/packages/query-core/src/retryer.ts @@ -2,83 +2,13 @@ import { isServer as isServerEnvironment } from './environmentManager' import { focusManager } from './focusManager' import { onlineManager } from './onlineManager' import { noop, sleep } from './utils' +import type { + Retryer, + RetryerConfig, + RetryerStatus, +} from '@tanstack/query-types/bindings' import type { CancelOptions, DefaultError, NetworkMode } from './types' -// TYPES - -interface RetryerConfig { - fn: () => TData | Promise - initialPromise?: Promise - onCancel?: (error: TError) => void - onFail?: (failureCount: number, error: TError) => void - onPause?: () => void - onContinue?: () => void - retry?: RetryValue - retryDelay?: RetryDelayValue - networkMode: NetworkMode | undefined - canRun: () => boolean -} - -/** - * Runs a function with retries, and can pause, continue, or cancel it. Queries and mutations use - * one for each fetch or execution. - */ -export interface Retryer { - /** - * The promise that resolves with the data, or rejects once retries are exhausted or it is - * cancelled. - */ - promise: Promise - /** - * Cancels the run, rejecting `promise` with a `CancelledError`. - */ - cancel: (cancelOptions?: CancelOptions) => void - /** - * Resumes a paused run, and returns `promise`. - */ - continue: () => Promise - /** - * Stops further retries. The current attempt still finishes. - */ - cancelRetry: () => void - /** - * Allows retries again after `cancelRetry`. - */ - continueRetry: () => void - /** - * Returns whether the run can start now, based on the network mode and `canRun`. - */ - canStart: () => boolean - /** - * Starts the run, or waits until it can start, and returns `promise`. - */ - start: () => Promise - /** - * Returns whether `promise` is still pending, resolved, or rejected. - */ - status: () => 'pending' | 'resolved' | 'rejected' -} - -type RetryerStatus = 'pending' | 'resolved' | 'rejected' - -/** @inline */ -export type RetryValue = boolean | number | ShouldRetryFunction - -/** @inline */ -type ShouldRetryFunction = ( - failureCount: number, - error: TError, -) => boolean - -/** @inline */ -export type RetryDelayValue = number | RetryDelayFunction - -/** @inline */ -type RetryDelayFunction = ( - failureCount: number, - error: TError, -) => number - /** * Applies exponential backoff with jitter. The base delay starts at 1 second * and doubles for each retry, up to 30 seconds. @@ -303,3 +233,9 @@ export function createRetryer( }, } } + +export type { + Retryer, + RetryValue, + RetryDelayValue, +} from '@tanstack/query-types/bindings' diff --git a/packages/query-core/src/runtimeBinding.ts b/packages/query-core/src/runtimeBinding.ts new file mode 100644 index 00000000000..26f50dded36 --- /dev/null +++ b/packages/query-core/src/runtimeBinding.ts @@ -0,0 +1,49 @@ +import type { RuntimeBinding } from '@tanstack/query-types/bindings' +import type { Mutation } from './mutation' +import type { MutationCache } from './mutationCache' +import type { MutationObserver } from './mutationObserver' +import type { Query } from './query' +import type { QueryCache } from './queryCache' +import type { QueryClient } from './queryClient' +import type { QueryObserver } from './queryObserver' +import type { QueryKey } from './types' + +/** Binds shared option and callback types to the concrete classes in this runtime. */ +export interface QueryRuntime extends RuntimeBinding { + QueryClient: QueryClient + QueryCache: QueryCache + MutationCache: MutationCache + Query: this['args'] extends [ + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryKey extends QueryKey, + ] + ? Query + : never + Mutation: this['args'] extends [ + infer TData, + infer TError, + infer TVariables, + infer TOnMutateResult, + ] + ? Mutation + : never + QueryObserver: this['args'] extends [ + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryData, + infer TQueryKey extends QueryKey, + ] + ? QueryObserver + : never + MutationObserver: this['args'] extends [ + infer TData, + infer TError, + infer TVariables, + infer TOnMutateResult, + ] + ? MutationObserver + : never +} diff --git a/packages/query-core/src/streamedQuery.ts b/packages/query-core/src/streamedQuery.ts index 6e43572f762..6efb1dbfcdd 100644 --- a/packages/query-core/src/streamedQuery.ts +++ b/packages/query-core/src/streamedQuery.ts @@ -1,53 +1,14 @@ import { addConsumeAwareSignal, fetchSignal } from './utils' -import type { - OmitKeyof, - QueryFunction, - QueryFunctionContext, - QueryKey, -} from './types' +import type * as Shared from '@tanstack/query-types/bindings' +import type { QueryRuntime } from './runtimeBinding' +import type { OmitKeyof, QueryFunction, QueryKey } from './types' import type { FetchSignalContext } from './utils' -type BaseStreamedQueryParams = { - /** Returns an `AsyncIterable` or a promise that resolves to one. */ - streamFn: ( - context: QueryFunctionContext, - ) => AsyncIterable | Promise> - /** - * Defines how refetches are handled. - * - `'reset'` (default): resets the query to its initial state before reading the stream. - * - `'append'`: appends new data to the existing data. - * - `'replace'`: writes all data to the cache once the stream ends. - */ - refetchMode?: 'append' | 'reset' | 'replace' -} - -type SimpleStreamedQueryParams< - TQueryFnData, - TQueryKey extends QueryKey, -> = BaseStreamedQueryParams & { - reducer?: never - initialValue?: never -} - -type ReducibleStreamedQueryParams< +type StreamedQueryParams< TQueryFnData, TData, TQueryKey extends QueryKey, -> = BaseStreamedQueryParams & { - /** - * Combines the accumulated data with the next chunk. Provide `initialValue` with a custom reducer. - */ - reducer: (acc: TData, chunk: TQueryFnData) => TData - /** - * The starting value for the reducer when there is no cached data or when - * `refetchMode` is `'replace'` during a refetch. - */ - initialValue: TData -} - -type StreamedQueryParams = - | SimpleStreamedQueryParams - | ReducibleStreamedQueryParams +> = Shared.StreamedQueryParams /** * Creates a query function that streams data from an `AsyncIterable`. diff --git a/packages/query-core/src/timeoutManager.ts b/packages/query-core/src/timeoutManager.ts index adf349fb4fb..9ec5900daf2 100644 --- a/packages/query-core/src/timeoutManager.ts +++ b/packages/query-core/src/timeoutManager.ts @@ -1,52 +1,9 @@ -/** - * {@link TimeoutManager} does not support passing arguments to the callback. - * - * `(_: void)` is the argument type inferred by TypeScript's default typings for - * `setTimeout(cb, number)`. - * If we don't accept a single void argument, then - * `new Promise(resolve => timeoutManager.setTimeout(resolve, N))` is a type error. - */ -export type TimeoutCallback = (_: void) => void - -/** - * Wrapping `setTimeout` is awkward from a typing perspective because platform - * typings may extend the return type of `setTimeout`. For example, NodeJS - * typings add `NodeJS.Timeout`; but a non-default `timeoutManager` may not be - * able to return such a type. - */ -export type ManagedTimerId = number | { [Symbol.toPrimitive]: () => number } - -/** - * Backend for timer functions. - * - * Timers are performance-sensitive: short-lived timers (delays under a few seconds) tend to be - * latency-sensitive, while long-lived ones may benefit more from coalescing — batching timers - * with similar deadlines together — which the default provider (backed by the platform's global - * `setTimeout`/`setInterval`) does not do. A custom provider can implement coalescing, and can - * also support delays longer than the ~24-day maximum of the global `setTimeout`. - */ -export type TimeoutProvider = - { - /** - * Schedules `callback` to run once after `delay` milliseconds, like the global `setTimeout`. - */ - readonly setTimeout: (callback: TimeoutCallback, delay: number) => TTimerId - /** - * Cancels a timeout scheduled with `setTimeout`. - */ - readonly clearTimeout: (timeoutId: TTimerId | undefined) => void - - /** - * Schedules `callback` to run every `delay` milliseconds, like the global `setInterval`. - */ - readonly setInterval: (callback: TimeoutCallback, delay: number) => TTimerId - /** - * Cancels an interval scheduled with `setInterval`. - */ - readonly clearInterval: (intervalId: TTimerId | undefined) => void - } - -type SystemTimerId = ReturnType +import type { + ManagedTimerId, + SystemTimerId, + TimeoutCallback, + TimeoutProvider, +} from '@tanstack/query-types/bindings' export const defaultTimeoutProvider: TimeoutProvider = { // We need the wrapper function syntax below instead of direct references to @@ -258,3 +215,9 @@ export const timeoutManager = new TimeoutManager() export function systemSetTimeoutZero(callback: TimeoutCallback): void { setTimeout(callback, 0) } + +export type { + TimeoutCallback, + ManagedTimerId, + TimeoutProvider, +} from '@tanstack/query-types/bindings' diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index 113b83210cb..67aa6619cf5 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -1,700 +1,152 @@ -/* istanbul ignore file */ - -import type { DehydrateOptions, HydrateOptions } from './hydration' -import type { MutationState } from './mutation' -import type { MutationCache } from './mutationCache' -import type { Query } from './query' -import type { QueryCache } from './queryCache' -import type { QueryClient } from './queryClient' -import type { RetryDelayValue, RetryValue } from './retryer' +import type * as Shared from '@tanstack/query-types/bindings' import type { - DefaultQueryFn, - QueryFilters, - QueryTypeFilter, - SkipToken, -} from './utils' - -/** - * Excludes `undefined` from `T`. Used where a value must be defined, such as the data type that a - * defined `initialData` resolves to. - */ -export type NonUndefinedGuard = T extends undefined ? never : T - -/** - * Like `Omit`, but applied to each member of a union separately, so each member keeps its own keys. - */ -export type DistributiveOmit< - TObject, - TKey extends keyof TObject, -> = TObject extends any ? Omit : never - -/** - * Like `Omit`, but by default (`'strictly'`) `TKey` must be a key of `TObject`, so omitting a key - * that doesn't exist is a type error. Pass `'safely'` to allow other keys too. - */ -export type OmitKeyof< - TObject, - TKey extends (TStrictly extends 'safely' - ? | keyof TObject - | (string & Record) - | (number & Record) - | (symbol & Record) - : keyof TObject), - TStrictly extends 'strictly' | 'safely' = 'strictly', -> = Omit - -/** - * Replaces the types of the properties of `TTargetA` that also exist in `TTargetB` with their types - * in `TTargetB`. Properties that only exist in `TTargetB` are not added. - */ -export type Override = { - [AKey in keyof TTargetA]: AKey extends keyof TTargetB - ? TTargetB[AKey] - : TTargetA[AKey] -} - -/** - * The interface to augment via declaration merging to override Query's default types repository-wide. - * Each field it declares replaces the default of the matching type: `defaultError` for {@link DefaultError}, - * `queryKey` for {@link QueryKey}, `mutationKey` for {@link MutationKey}, `queryMeta` for {@link QueryMeta} and - * `mutationMeta` for {@link MutationMeta}. Leave a field out to keep that type's default. - * Augment the module you install — `@tanstack/react-query`, `@tanstack/vue-query`, - * `@tanstack/solid-query`, `@tanstack/svelte-query`, `@tanstack/preact-query`, - * `@tanstack/angular-query` or `@tanstack/lit-query`. Augmenting `@tanstack/query-core` - * works too and covers every adapter at once. - * @example - * ```ts - * // Use the module you installed — here, the React adapter. - * declare module '@tanstack/react-query' { - * interface Register { - * defaultError: AxiosError - * } - * } - * ``` - */ -export interface Register { - // defaultError: Error - // queryMeta: Record - // mutationMeta: Record - // queryKey: ReadonlyArray - // mutationKey: ReadonlyArray -} - -/** - * The error type used wherever an error is not given an explicit type parameter. - * Defaults to `Error`; declare `defaultError` on {@link Register} to change it everywhere at once. - */ -export type DefaultError = Register extends { - defaultError: infer TError -} - ? TError - : Error - -/** - * The type of a query key — the serializable array that identifies a query in the cache. - * Defaults to `ReadonlyArray`; declare `queryKey` on {@link Register} to narrow it repository-wide. - */ -export type QueryKey = Register extends { - queryKey: infer TQueryKey -} - ? TQueryKey extends ReadonlyArray - ? TQueryKey - : TQueryKey extends Array - ? TQueryKey - : ReadonlyArray - : ReadonlyArray - -export const dataTagSymbol = Symbol() + DefaultError, + InfiniteData, + QueryKey, + UnsetMarker as unsetMarkerType, + dataTagErrorSymbol as dataTagErrorSymbolType, + dataTagSymbol as dataTagSymbolType, +} from '@tanstack/query-types/bindings' +import type { QueryRuntime } from './runtimeBinding' + +export const dataTagSymbol: dataTagSymbolType = Symbol.for( + '@tanstack/query/dataTagSymbol', +) as dataTagSymbolType /** * The type of the `dataTagSymbol` key, under which a {@link DataTag} stores its data type. */ export type dataTagSymbol = typeof dataTagSymbol -export const dataTagErrorSymbol = Symbol() +export const dataTagErrorSymbol: dataTagErrorSymbolType = Symbol.for( + '@tanstack/query/dataTagErrorSymbol', +) as dataTagErrorSymbolType /** * The type of the `dataTagErrorSymbol` key, under which a {@link DataTag} stores its error type. */ export type dataTagErrorSymbol = typeof dataTagErrorSymbol -export const unsetMarker = Symbol() -/** - * The type of `unsetMarker`, the default error type of a {@link DataTag}. It marks that no error - * type was tagged. - */ -export type UnsetMarker = typeof unsetMarker -/** - * Matches any type that has been tagged with {@link DataTag}, whatever its data and error types. - */ -export type AnyDataTag = { - /** - * The data type the key was tagged with. - */ - [dataTagSymbol]: any - /** - * The error type the key was tagged with. - */ - [dataTagErrorSymbol]: any -} -/** - * Tags `TType` (usually a query key) with a data type and an optional error type, so that APIs that - * receive it, like `queryClient.getQueryData`, can infer them. A type that is already tagged is - * returned as is. - */ -export type DataTag< - TType, - TValue, - TError = UnsetMarker, -> = TType extends AnyDataTag - ? TType - : TType & { - [dataTagSymbol]: TValue - [dataTagErrorSymbol]: TError - } - -/** - * An object whose `queryKey` is tagged with {@link DataTag}, like the options returned by - * `queryOptions`. - */ -export type QueryKeyWithDataTag< - TQueryKey extends QueryKey = QueryKey, - TQueryFnData = unknown, - TError = DefaultError, -> = { - /** - * The query key, tagged with the query's data and error types. - */ - queryKey: DataTag -} - -/** - * The data type tagged on a query key by {@link DataTag}, or `TQueryFnData` if the key is not - * tagged. - */ -export type InferDataFromTag = - TTaggedQueryKey extends DataTag - ? TaggedValue - : TQueryFnData +export const unsetMarker: unsetMarkerType = Symbol.for( + '@tanstack/query/unsetMarker', +) as unsetMarkerType -/** - * The error type tagged on a query key by {@link DataTag}, or `TError` if the key is not tagged or - * was tagged without an error type. - */ -export type InferErrorFromTag = - TTaggedQueryKey extends DataTag - ? TaggedError extends UnsetMarker - ? TError - : TaggedError - : TError - -/** @inline */ export type QueryFunction< T = unknown, TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> = (context: QueryFunctionContext) => T | Promise - -/** @inline */ -export type StaleTime = number | 'static' +> = Shared.QueryFunction -/** @inline */ export type StaleTimeFunction< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> = - | StaleTime - | ((query: Query) => StaleTime) +> = Shared.StaleTimeFunction< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey +> -/** @inline */ export type QueryBooleanOption< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> = - | boolean - | ((query: Query) => boolean) +> = Shared.QueryBooleanOption< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey +> -/** @inline */ export type QueryPersister< T = unknown, TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> = [TPageParam] extends [never] - ? ( - queryFn: QueryFunction, - context: QueryFunctionContext, - query: Query, - ) => T | Promise - : ( - queryFn: QueryFunction, - context: QueryFunctionContext, - query: Query, - ) => T | Promise +> = Shared.QueryPersister -/** - * The object passed to `queryFn`: the `QueryClient`, the `queryKey`, an `AbortSignal` that aborts - * when the query is cancelled, the query's `meta`, and for infinite queries the `pageParam` of the - * page being fetched. - */ export type QueryFunctionContext< TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> = [TPageParam] extends [never] - ? { - client: QueryClient - queryKey: TQueryKey - signal: AbortSignal - meta: QueryMeta | undefined - pageParam?: unknown - } - : { - client: QueryClient - queryKey: TQueryKey - signal: AbortSignal - pageParam: TPageParam - meta: QueryMeta | undefined - } - -/** @inline */ -export type InitialDataFunction = () => T | undefined +> = Shared.QueryFunctionContext // oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes every function-like value, including constructors, from the value branch -type NonFunctionGuard = T extends Function ? never : T -/** @inline */ export type PlaceholderDataFunction< TQueryFnData = unknown, TError = DefaultError, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> = ( - previousData: TQueryData | undefined, - previousQuery: Query | undefined, -) => TQueryData | undefined - -/** - * The `placeholderData` function of a query in `useQueries` and its counterparts. Unlike - * {@link PlaceholderDataFunction}, it receives no previous data or query, because the number of - * queries can differ between renders. - */ -export type QueriesPlaceholderDataFunction = ( - previousData: undefined, - previousQuery: undefined, -) => TQueryData | undefined - -/** @inline */ -export type EqualityFn = (a: unknown, b: unknown) => boolean - -/** @inline */ -export type CacheKeyHashFunction< - TCacheKey extends ReadonlyArray = ReadonlyArray, -> = (cacheKey: TCacheKey) => string - -/** Configures the comparison and hashing of query or mutation keys for a cache. */ -export interface CacheKeyConfig< - TCacheKey extends ReadonlyArray = ReadonlyArray, -> { - /** - * Function used to compare values while partially matching keys. - * Defaults to strict equality. - */ - equalityFn?: EqualityFn - /** - * Function used to hash keys globally. - */ - hashFn?: CacheKeyHashFunction -} - -/** @inline */ -export type GetPreviousPageParamFunction = ( - firstPage: TQueryFnData, - allPages: Array, - firstPageParam: TPageParam, - allPageParams: Array, -) => TPageParam | undefined | null - -/** @inline */ -export type GetNextPageParamFunction = ( - lastPage: TQueryFnData, - allPages: Array, - lastPageParam: TPageParam, - allPageParams: Array, -) => TPageParam | undefined | null - -/** - * The data shape of an infinite query: every page fetched so far, plus the page param each one was fetched with. - * `pages` and `pageParams` are index-aligned — `pageParams[i]` is the param that produced `pages[i]`. - */ -export interface InfiniteData { - /** - * The data of every page fetched so far, in order. - */ - pages: Array - /** - * The page param each page was fetched with, aligned by index with `pages`. - */ - pageParams: Array -} - -/** - * The type of the `meta` object that can be attached to a query and read back from `queryFn`, callbacks and - * cache-level handlers. Defaults to `Record`; declare `queryMeta` on {@link Register} to narrow it. - */ -export type QueryMeta = Register extends { - queryMeta: infer TQueryMeta -} - ? TQueryMeta extends Record - ? TQueryMeta - : Record - : Record - -/** @inline */ -export type NetworkMode = 'online' | 'always' | 'offlineFirst' - -/** @inline */ -export type NotifyOnChangeProps = 'all' | 'none' +> = Shared.PlaceholderDataFunction< + QueryRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey +> -/** - * The options of a query itself — its `queryKey`, `queryFn`, retries, `gcTime`, `initialData`, - * `meta`, and so on — shared by observers and the `QueryClient` methods that fetch queries. - */ -export interface QueryOptions< +export type QueryOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> { - /** - * If `false`, failed queries will not retry by default. - * If `true`, failed queries will retry infinitely. - * If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. - * If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. - * - * Defaults to `3` on the client and `0` on the server. - */ - retry?: RetryValue - /** - * The delay in milliseconds before a retry. Use a number for a fixed delay or a function that receives - * the failure count and error and returns the delay. The count starts at 0 for the first retry. - * - * A function like `attempt => Math.min(1000 * 2 ** attempt, 30000)` applies exponential - * backoff. - * - * A function like `attempt => attempt * 1000` applies linear backoff. - * - * By default, each retry waits a random duration from 80% to 100% of the base delay. - * The base delay starts at 1 second and doubles for each retry, up to 30 seconds. - */ - retryDelay?: RetryDelayValue - /** - * Controls whether a query is allowed to run based on the current network connectivity. - * @defaultValue 'online' - * @see [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. - */ - networkMode?: NetworkMode - /** - * The time in milliseconds that unused/inactive cache data remains in memory. - * When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. - * When different garbage collection times are specified, the longest one will be used. - * Setting it to `Infinity` will disable garbage collection. - * - * Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. - * - * Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see - * `timeoutManager.setTimeoutProvider` for a workaround. - */ - gcTime?: number - /** - * The function that the query will use to request data. - * Pass `defaultQueryFn` to use the function configured in the client's query defaults. - * Pass `skipToken` to disable a query without a function where supported. - * Receives a {@link QueryFunctionContext}. - * Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. - */ - queryFn?: - | QueryFunction - | SkipToken - | DefaultQueryFn - /** - * This option can be used to persist the result of a query to an external storage, bypassing the need to actually - * call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. - */ - persister?: QueryPersister, TPageParam> - /** - * The cache key. If omitted, the query cache computes it from `queryKey` - * using its configured `hashFn` or the default hash function. - */ - queryHash?: string - /** - * The query key to use for this query. - * - * The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) - * for more information. - * - * The query will automatically update when this key changes (as long as `enabled` is not set to `false`). - */ - queryKey?: TQueryKey - /** - * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been - * created or cached yet). - * If set to a function, the function will be called **once** during the shared/root query initialization, and be - * expected to synchronously return the initial data. - * Initial data is considered stale by default unless a `staleTime` has been set. - * `initialData` **is persisted** to the cache. - */ - initialData?: TData | InitialDataFunction - /** - * If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. - */ - initialDataUpdatedAt?: number | (() => number | undefined) - /** - * Set this to `false` to disable structural sharing between query results. - * Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. - * @defaultValue true - */ - structuralSharing?: - | boolean - | ((oldData: unknown | undefined, newData: unknown) => unknown) - /** @internal */ - _defaulted?: boolean - /** @internal */ - _type?: 'infinite' - /** - * Additional payload to be stored on each query. - * Use this property to pass information that can be used in other places. - */ - meta?: QueryMeta - /** - * Maximum number of pages to store in the data of an infinite query. - */ - maxPages?: number -} - -/** - * Holds the `initialPageParam` option that every infinite query requires. - */ -export interface InitialPageParam { - /** - * The page param to start from when an infinite query has no pages yet. - * It is passed to `queryFn` as `pageParam` for the first page; every page after that gets the - * value returned by `getNextPageParam` or `getPreviousPageParam`. - * It only applies while the query has no pages: once a first page exists, refetching starts from - * that page's own param instead. - */ - initialPageParam: TPageParam -} - -/** - * The page param options of an infinite query: `initialPageParam`, and the `getNextPageParam` and - * `getPreviousPageParam` functions that compute the params of the pages around it. - */ -export interface InfiniteQueryPageParamsOptions< - TQueryFnData = unknown, - TPageParam = unknown, -> extends InitialPageParam { - /** - * This function can be set to automatically get the previous cursor for infinite queries. - * The result will also be used to determine the value of `hasPreviousPage`. - */ - getPreviousPageParam?: GetPreviousPageParamFunction - /** - * This function can be set to automatically get the next cursor for infinite queries. - * The result will also be used to determine the value of `hasNextPage`. - */ - getNextPageParam: GetNextPageParamFunction -} +> = Shared.QueryOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> -/** @inline */ export type ThrowOnError< TQueryFnData, TError, TQueryData, TQueryKey extends QueryKey, -> = - | boolean - | (( - error: TError, - query: Query, - ) => boolean) +> = Shared.ThrowOnError< + QueryRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey +> -/** - * Shared options for default resolution and resolved observer state. - * @internal - */ -export interface QueryObserverOptionsBase< +export type QueryObserverOptionsBase< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> extends WithRequired< - QueryOptions, - 'queryKey' -> { - /** - * Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. - * To refetch the query, use the `refetch` method returned from the `useQuery` instance. - * Accepts a boolean or function that returns a boolean. - * @defaultValue true - */ - enabled?: QueryBooleanOption - /** - * The time in milliseconds after data is considered stale. - * If set to `Infinity`, the data will never be considered stale. - * If set to `'static'`, the data will never be considered stale. - * If set to a function, the function will be executed with the query to compute a `staleTime`. - * @defaultValue 0 - */ - staleTime?: StaleTimeFunction - /** - * If set to a number, the query will continuously refetch at this frequency in milliseconds. - * If set to a function, the function will be executed with the latest data and query to compute a frequency - * @defaultValue false - */ - refetchInterval?: - | number - | false - | (( - query: Query, - ) => number | false | undefined) - /** - * If set to `true`, the query will continue to refetch while their tab/window is in the background. - * @defaultValue false - */ - refetchIntervalInBackground?: boolean - /** - * If set to `true`, the query will refetch on window focus if the data is stale. - * If set to `false`, the query will not refetch on window focus. - * If set to `'always'`, the query will always refetch on window focus (except when `staleTime: 'static'` is used). - * If set to a function, the function will be executed with the latest data and query to compute the value. - * @defaultValue true - */ - refetchOnWindowFocus?: - | boolean - | 'always' - | (( - query: Query, - ) => boolean | 'always') - /** - * If set to `true`, the query will refetch on reconnect if the data is stale. - * If set to `false`, the query will not refetch on reconnect. - * If set to `'always'`, the query will always refetch on reconnect (except when `staleTime: 'static'` is used). - * If set to a function, the function will be executed with the latest data and query to compute the value. - * - * Defaults to `true` unless `networkMode` is `'always'`. - */ - refetchOnReconnect?: - | boolean - | 'always' - | (( - query: Query, - ) => boolean | 'always') - /** - * If set to `true`, the query will refetch on mount if the data is stale. - * If set to `false`, will disable additional instances of a query to trigger background refetch. - * If set to `'always'`, the query will always refetch on mount (except when `staleTime: 'static'` is used). - * If set to a function, the function will be executed with the latest data and query to compute the value - * @defaultValue true - */ - refetchOnMount?: - | boolean - | 'always' - | (( - query: Query, - ) => boolean | 'always') - /** - * If set to `false`, the query will not be retried on mount if it contains an error. - * If set to a function, the function will be executed with the query to compute the value. - * @defaultValue true - */ - retryOnMount?: QueryBooleanOption - /** - * Controls when changes to the query result notify this observer's listeners. - * Use `'all'` to notify on every result change. - * Use `'none'` to suppress notifications while the query remains subscribed and can fetch. - * If `throwOnError` is set, changes to `error` still notify listeners. - * - * By default, adapters that track property reads notify listeners when a tracked property changes. - * If no properties are tracked, every result change notifies listeners. - */ - notifyOnChangeProps?: NotifyOnChangeProps - /** - * Whether errors should be thrown instead of setting the `error` property. - * If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. - * If set to `false` and `suspense` is `false`, errors are returned as state. - * If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`). - * @defaultValue false - */ - throwOnError?: ThrowOnError - /** - * This option can be used to transform or select a part of the data returned by the query function. It affects - * the returned `data` value, but does not affect what gets stored in the query cache. - * The `select` function will only run if `data` changed, or if the reference to the `select` function itself - * changes. To optimize, memoize the function so its reference stays stable across calls. - * If the selector throws, the observer reports the error and can keep the last valid selection. - */ - select?: (data: TQueryData) => TData - /** - * If set to `true`, the query will suspend when `status === 'pending'` - * and throw errors when `status === 'error'`. - * @defaultValue false - */ - suspense?: boolean - /** - * If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. - * If the placeholder function throws, the observer reports the error with no data. The query state in the cache is unaffected. - */ - placeholderData?: - | NonFunctionGuard - | PlaceholderDataFunction< - NonFunctionGuard, - TError, - NonFunctionGuard, - TQueryKey - > - - /** @internal */ - _optimisticResults?: 'optimistic' | 'isRestoring' -} +> = Shared.QueryObserverOptionsBase< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> -/** - * The options of a `QueryObserver`, and of the hooks built on it like `useQuery`: the - * {@link QueryOptions} of the query, plus options that control the observer, such as `enabled`, - * `staleTime`, `refetchInterval`, `select`, and `placeholderData`. - * Pass a `queryFn` or use `defaultQueryFn` to select the client defaults. - */ -export interface QueryObserverOptions< +export type QueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> extends WithRequired< - QueryObserverOptionsBase< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - >, - 'queryFn' -> {} - -/** - * Makes the `TKey` properties of `TTarget` required and non-nullable. - */ -export type WithRequired = TTarget & { - [_ in TKey]: {} -} +> = Shared.QueryObserverOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> -/** - * The {@link QueryObserverOptions} after `QueryClient#defaultQueryOptions` has applied the - * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. - */ export type DefaultedQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, @@ -702,1697 +154,303 @@ export type DefaultedQueryObserverOptions< TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> = WithRequired< - QueryObserverOptionsBase< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - >, - 'throwOnError' | 'refetchOnReconnect' | 'queryHash' +> = Shared.DefaultedQueryObserverOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam > -/** - * The options of an `InfiniteQueryObserver`: {@link QueryObserverOptions} whose query data is - * {@link InfiniteData}, plus the page param options. - */ -export interface InfiniteQueryObserverOptions< +export type InfiniteQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown, +> = Shared.InfiniteQueryObserverOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam > - extends - QueryObserverOptions< - TQueryFnData, - TError, - TData, - InfiniteData, - TQueryKey, - TPageParam - >, - InfiniteQueryPageParamsOptions {} -/** - * The {@link InfiniteQueryObserverOptions} after `QueryClient#defaultQueryOptions` has applied the - * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. - */ export type DefaultedInfiniteQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown, -> = DefaultedQueryObserverOptions< +> = Shared.DefaultedInfiniteQueryObserverOptions< + QueryRuntime, TQueryFnData, TError, TData, - InfiniteData, TQueryKey, TPageParam -> & - InfiniteQueryPageParamsOptions +> -/** - * The options of `queryClient.query`: the {@link QueryOptions} of the query, plus a `staleTime` - * that decides whether cached data is returned instead of fetching, and a `select` that only - * transforms the value the call resolves with. - */ -export interface QueryExecuteOptions< +export type QueryExecuteOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> extends WithRequired< - QueryOptions, - 'queryKey' -> { - /** - * Not allowed here, since `initialPageParam` only applies to infinite queries. - */ - initialPageParam?: never - /** - * This option can be used to transform or select a part of the data returned by the query function. It affects - * the value this call resolves with, but does not affect what gets stored in the query cache. - */ - select?: (data: TQueryData) => TData - /** - * The time in milliseconds after data is considered stale. - * If the data is fresh it will be returned from the cache. - */ - staleTime?: StaleTimeFunction -} - -type InfiniteQueryFetchPageOptions = Pick< - InfiniteQueryPageParamsOptions, - 'initialPageParam' | 'getNextPageParam' -> & { - /** - * The number of pages to fetch. Defaults to the number of cached pages, - * or one page if the cache has no pages. - */ - pages?: number -} +> = Shared.QueryExecuteOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> -/** - * The options of `queryClient.infiniteQuery`. Extends {@link QueryExecuteOptions} - * with `initialPageParam`, `getNextPageParam`, and the optional `pages` count. - */ export type InfiniteQueryExecuteOptions< TQueryFnData = unknown, TError = DefaultError, TData = InfiniteData, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown, -> = Omit< - QueryExecuteOptions< - TQueryFnData, - TError, - TData, - InfiniteData, - TQueryKey, - TPageParam - >, - 'initialPageParam' -> & - InfiniteQueryFetchPageOptions - -/** - * Options shared by the `QueryClient` and observer methods that refetch queries, controlling - * whether a failed refetch makes the returned promise reject. - */ -export interface ResultOptions { - /** - * If set to `true`, the method throws if any of the underlying query refetch tasks fail. - * If set to `false`, failed refetches are swallowed and not surfaced to the caller. - * @defaultValue false - */ - throwOnError?: boolean -} - -/** - * Options of the methods that refetch queries, like `refetch` and `queryClient.refetchQueries`. - */ -export interface RefetchOptions extends ResultOptions { - /** - * If set to `true`, a currently running request will be cancelled before a new request is made - * - * If set to `false`, no refetch will be made if there is already a request running. - * @defaultValue true - */ - cancelRefetch?: boolean -} - -/** - * The filters of `queryClient.invalidateQueries`: the {@link QueryFilters} that select the queries - * to invalidate, plus `refetchType` to choose which of them are refetched. - */ -export interface InvalidateQueryFilters< - TQueryKey extends QueryKey = QueryKey, -> extends QueryFilters { - /** - * Controls which of the matched (now-invalidated) queries are refetched in the background. - * - * - `'active'`: only queries with at least one active observer are refetched. - * - `'inactive'`: only queries with no active observer are refetched. - * - `'all'`: every matched query is refetched, active or not. - * - `'none'`: no query is refetched; matched queries are only marked as invalidated. - * @defaultValue 'active' - */ - refetchType?: QueryTypeFilter | 'none' -} - -/** - * The filters of `queryClient.refetchQueries`, which select the queries to refetch. - */ -export interface RefetchQueryFilters< - TQueryKey extends QueryKey = QueryKey, -> extends QueryFilters {} - -/** - * Options of `queryClient.invalidateQueries`, applied to the refetch that follows the invalidation. - */ -export interface InvalidateOptions extends RefetchOptions {} -/** - * Options of `queryClient.resetQueries`, applied to the refetch of the active queries after the - * reset. - */ -export interface ResetOptions extends RefetchOptions {} - -/** - * Options of `fetchNextPage` on an infinite query result. - */ -export interface FetchNextPageOptions extends ResultOptions { - /** - * If set to `true`, calling `fetchNextPage` repeatedly will invoke `queryFn` every time, - * whether the previous invocation has resolved or not. Also, the result from previous invocations will be ignored. - * - * If set to `false`, calling `fetchNextPage` repeatedly won't have any effect until the first invocation has resolved. - * @defaultValue true - */ - cancelRefetch?: boolean -} - -/** - * Options of `fetchPreviousPage` on an infinite query result. - */ -export interface FetchPreviousPageOptions extends ResultOptions { - /** - * If set to `true`, calling `fetchPreviousPage` repeatedly will invoke `queryFn` every time, - * whether the previous invocation has resolved or not. Also, the result from previous invocations will be ignored. - * - * If set to `false`, calling `fetchPreviousPage` repeatedly won't have any effect until the first invocation has resolved. - * @defaultValue true - */ - cancelRefetch?: boolean -} - -/** @inline */ -export type QueryStatus = 'pending' | 'error' | 'success' -/** @inline */ -export type FetchStatus = 'fetching' | 'paused' | 'idle' - -/** - * The properties shared by every state of a query result, like `data`, `error`, `status`, the - * `is*` flags, and `refetch`. Each `QueryObserver*Result` narrows them for one state. - */ -export interface QueryObserverBaseResult< - TData = unknown, - TError = DefaultError, -> { - /** - * The last successfully resolved data for the query. - */ - data: TData | undefined - /** - * The timestamp for when the query most recently returned the `status` as `"success"`. - */ - dataUpdatedAt: number - /** - * The error object for the query, if an error was thrown. - * - Defaults to `null`. - */ - error: TError | null - /** - * The timestamp for when the query most recently returned the `status` as `"error"`. - */ - errorUpdatedAt: number - /** - * The failure count for the query. - * - Incremented every time the query fails. - * - Reset to `0` when the query succeeds. - */ - failureCount: number - /** - * The failure reason for the query retry. - * - Reset to `null` when the query succeeds. - */ - failureReason: TError | null - /** - * The sum of all errors. - */ - errorUpdateCount: number - /** - * A derived boolean from the `status` variable, provided for convenience. - * - `true` if the query has an error from a fetch that failed after its retries, or if `select` threw. - */ - isError: boolean - /** - * Will be `true` if the query has been fetched. - */ - isFetched: boolean - /** - * Will be `true` if the query has been fetched after the component mounted. - * - This property can be used to not show any previously cached data. - */ - isFetchedAfterMount: boolean - /** - * A derived boolean from the `fetchStatus` variable, provided for convenience. - * - `true` whenever the `queryFn` is executing, which includes initial `pending` as well as background refetch. - */ - isFetching: boolean - /** - * Is `true` whenever the first fetch for a query is in-flight. - * - Is the same as `isFetching && isPending`. - */ - isLoading: boolean - /** - * Will be `true` if the query has no cached data, no data from `placeholderData` and no error. - */ - isPending: boolean - /** - * Will be `true` if the query has an error and no data to display. - */ - isLoadingError: boolean - /** - * A derived boolean from the `fetchStatus` variable, provided for convenience. - * - The query wanted to fetch, but has been `paused`. - */ - isPaused: boolean - /** - * Will be `true` if the data shown is the placeholder data. - */ - isPlaceholderData: boolean - /** - * Will be `true` if the query has an error and still has data to display (for infinite queries, not after a failed page fetch). - */ - isRefetchError: boolean - /** - * Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`. - * - Is the same as `isFetching && !isPending`. - */ - isRefetching: boolean - /** - * Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. - */ - isStale: boolean - /** - * A derived boolean from the `status` variable, provided for convenience. - * - `true` if the query has cached data or data from `placeholderData`, and no error. - */ - isSuccess: boolean - /** - * `true` if this observer is enabled, `false` otherwise. - */ - isEnabled: boolean - /** - * A function to manually refetch the query. - */ - refetch: ( - options?: RefetchOptions, - ) => Promise> - /** - * The status of the query. - * - Will be: - * - `error` if the query has an error from a fetch that failed after its retries, or if `select` threw. - * - `success` if the query has cached data (even if `select` returns `undefined`) or data from `placeholderData`, and no error. - * - `pending` otherwise, since the query has no cached data, no data from `placeholderData` and no error. - */ - status: QueryStatus - /** - * The fetch status of the query. - * - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. - * - `paused`: The query wanted to fetch, but has been `paused`. - * - `idle`: The query is not fetching. - * - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. - */ - fetchStatus: FetchStatus -} - -/** - * A query result in the `pending` state: the query has no data yet. - */ -export interface QueryObserverPendingResult< - TData = unknown, - TError = DefaultError, -> extends QueryObserverBaseResult { - /** - * `undefined`, since the query has no data yet. - */ - data: undefined - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `true`, since the query has no cached data, no data from `placeholderData` and no error. - */ - isPending: true - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. - */ - status: 'pending' -} - -/** - * A query result in the `pending` state while the first fetch is in flight, so `isLoading` is - * `true`. - */ -export interface QueryObserverLoadingResult< - TData = unknown, - TError = DefaultError, -> extends QueryObserverBaseResult { - /** - * `undefined`, since the query has no data yet. - */ - data: undefined - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `true`, since the query has no cached data, no data from `placeholderData` and no error. - */ - isPending: true - /** - * `true`, since the first fetch is in flight. - */ - isLoading: true - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. - */ - status: 'pending' -} - -/** - * A query result in the `error` state with no data to display, since a fetch or `select` failed. - */ -export interface QueryObserverLoadingErrorResult< - TData = unknown, - TError = DefaultError, -> extends QueryObserverBaseResult { - /** - * `undefined`, since there was no data to display when a fetch or `select` failed. - */ - data: undefined - /** - * The error the fetch or `select` failed with. - */ - error: TError - /** - * `true`, since the query is in the `error` state. - */ - isError: true - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `true`, since the query has an error and no data to display. - */ - isLoadingError: true - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'error'`, since a fetch failed after its retries or `select` threw. - */ - status: 'error' -} - -/** - * A query result in the `error` state that keeps the data from before a fetch or `select` failed. - */ -export interface QueryObserverRefetchErrorResult< - TData = unknown, - TError = DefaultError, -> extends QueryObserverBaseResult { - /** - * The data from before the fetch or `select` failed, which is kept. - */ - data: TData - /** - * The error the fetch or `select` failed with. - */ - error: TError - /** - * `true`, since the query is in the `error` state. - */ - isError: true - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `true`, since the query has an error and still has data to display. - */ - isRefetchError: true - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'error'`, since a fetch failed after its retries or `select` threw. - */ - status: 'error' -} - -/** - * A query result in the `success` state with data from the cache. - */ -export interface QueryObserverSuccessResult< - TData = unknown, - TError = DefaultError, -> extends QueryObserverBaseResult { - /** - * The last successfully resolved data for the query. - */ - data: TData - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `true`, since the query is in the `success` state. - */ - isSuccess: true - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'success'`, since the query has cached data and no error from a fetch or from - * `select`. - */ - status: 'success' -} - -/** - * A query result in the `success` state that shows `placeholderData` while the query has no data - * yet. - */ -export interface QueryObserverPlaceholderResult< - TData = unknown, - TError = DefaultError, -> extends QueryObserverBaseResult { - /** - * The `placeholderData` shown while the query has no data yet. - */ - data: TData - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `true`, since the query is in the `success` state. - */ - isSuccess: true - /** - * `true`, since the data shown is the `placeholderData`. - */ - isPlaceholderData: true - /** - * `'success'`, since the query shows `placeholderData` and has no error from a fetch or - * from `select`. - */ - status: 'success' -} - -/** - * A query result that always has `data`: the success and refetch error states. - */ -export type DefinedQueryObserverResult< - TData = unknown, - TError = DefaultError, -> = - | QueryObserverRefetchErrorResult - | QueryObserverSuccessResult - -/** - * The result of a `QueryObserver`, and of the hooks built on it like `useQuery`. Narrow it by - * `status` or the `is*` flags to get the type of each state. - */ -export type QueryObserverResult = - | DefinedQueryObserverResult - | QueryObserverLoadingErrorResult - | QueryObserverLoadingResult - | QueryObserverPendingResult - | QueryObserverPlaceholderResult - -/** - * The properties shared by every state of an infinite query result: those of - * {@link QueryObserverBaseResult}, plus `fetchNextPage`, `fetchPreviousPage`, and the flags about - * them, like `hasNextPage` and `isFetchingNextPage`. - */ -export interface InfiniteQueryObserverBaseResult< - TData = unknown, - TError = DefaultError, -> extends QueryObserverBaseResult { - /** - * This function allows you to fetch the next "page" of results. - */ - fetchNextPage: ( - options?: FetchNextPageOptions, - ) => Promise> - /** - * This function allows you to fetch the previous "page" of results. - */ - fetchPreviousPage: ( - options?: FetchPreviousPageOptions, - ) => Promise> - /** - * Will be `true` if there is a next page to be fetched (known via the `getNextPageParam` option). - */ - hasNextPage: boolean - /** - * Will be `true` if there is a previous page to be fetched (known via the `getPreviousPageParam` option). - */ - hasPreviousPage: boolean - /** - * Will be `true` if the query failed while fetching the next page. - */ - isFetchNextPageError: boolean - /** - * Will be `true` while fetching the next page with `fetchNextPage`. - */ - isFetchingNextPage: boolean - /** - * Will be `true` if the query failed while fetching the previous page. - */ - isFetchPreviousPageError: boolean - /** - * Will be `true` while fetching the previous page with `fetchPreviousPage`. - */ - isFetchingPreviousPage: boolean -} - -/** - * An infinite query result in the `pending` state: the query has no data yet. - */ -export interface InfiniteQueryObserverPendingResult< - TData = unknown, - TError = DefaultError, -> extends InfiniteQueryObserverBaseResult { - /** - * `undefined`, since the query has no data yet. - */ - data: undefined - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `true`, since the query has no cached data, no data from `placeholderData` and no error. - */ - isPending: true - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `false`, since fetching the next page didn't fail. - */ - isFetchNextPageError: false - /** - * `false`, since fetching the previous page didn't fail. - */ - isFetchPreviousPageError: false - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. - */ - status: 'pending' -} - -/** - * An infinite query result in the `pending` state while the first fetch is in flight, so - * `isLoading` is `true`. - */ -export interface InfiniteQueryObserverLoadingResult< - TData = unknown, - TError = DefaultError, -> extends InfiniteQueryObserverBaseResult { - /** - * `undefined`, since the query has no data yet. - */ - data: undefined - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `true`, since the query has no cached data, no data from `placeholderData` and no error. - */ - isPending: true - /** - * `true`, since the first fetch is in flight. - */ - isLoading: true - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `false`, since fetching the next page didn't fail. - */ - isFetchNextPageError: false - /** - * `false`, since fetching the previous page didn't fail. - */ - isFetchPreviousPageError: false - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. - */ - status: 'pending' -} - -/** - * An infinite query result in the `error` state with no data to display, since a fetch or `select` failed. - */ -export interface InfiniteQueryObserverLoadingErrorResult< - TData = unknown, - TError = DefaultError, -> extends InfiniteQueryObserverBaseResult { - /** - * `undefined`, since there was no data to display when a fetch or `select` failed. - */ - data: undefined - /** - * The error the fetch or `select` failed with. - */ - error: TError - /** - * `true`, since the query is in the `error` state. - */ - isError: true - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `true`, since the query has an error and no data to display. - */ - isLoadingError: true - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `false`, since fetching the next page didn't fail. - */ - isFetchNextPageError: false - /** - * `false`, since fetching the previous page didn't fail. - */ - isFetchPreviousPageError: false - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'error'`, since a fetch failed after its retries or `select` threw. - */ - status: 'error' -} - -/** - * An infinite query result in the `error` state that keeps the data from before a fetch or `select` - * failed. - */ -export interface InfiniteQueryObserverRefetchErrorResult< - TData = unknown, - TError = DefaultError, -> extends InfiniteQueryObserverBaseResult { - /** - * The data from before the fetch or `select` failed, which is kept. - */ - data: TData - /** - * The error the fetch or `select` failed with. - */ - error: TError - /** - * `true`, since the query is in the `error` state. - */ - isError: true - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `true`, since the query has an error, still has data to display, and didn't fail fetching a page. - */ - isRefetchError: true - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'error'`, since a fetch failed after its retries or `select` threw. - */ - status: 'error' -} +> = Shared.InfiniteQueryExecuteOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> -/** - * An infinite query result in the `success` state with data from the cache. - */ -export interface InfiniteQueryObserverSuccessResult< - TData = unknown, - TError = DefaultError, -> extends InfiniteQueryObserverBaseResult { - /** - * The last successfully resolved data for the query. - */ - data: TData - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `false`, since fetching the next page didn't fail. - */ - isFetchNextPageError: false - /** - * `false`, since fetching the previous page didn't fail. - */ - isFetchPreviousPageError: false - /** - * `true`, since the query is in the `success` state. - */ - isSuccess: true - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'success'`, since the query has cached data and no error from a fetch or from - * `select`. - */ - status: 'success' -} +export type InvalidateQueryFilters = + Shared.InvalidateQueryFilters -/** - * An infinite query result in the `success` state that shows `placeholderData` while the query has - * no data yet. - */ -export interface InfiniteQueryObserverPlaceholderResult< - TData = unknown, - TError = DefaultError, -> extends InfiniteQueryObserverBaseResult { - /** - * The `placeholderData` shown while the query has no data yet. - */ - data: TData - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `true`, since the query is in the `success` state. - */ - isSuccess: true - /** - * `true`, since the data shown is the `placeholderData`. - */ - isPlaceholderData: true - /** - * `false`, since fetching the next page didn't fail. - */ - isFetchNextPageError: false - /** - * `false`, since fetching the previous page didn't fail. - */ - isFetchPreviousPageError: false - /** - * `'success'`, since the query shows `placeholderData` and has no error from a fetch or - * from `select`. - */ - status: 'success' -} +export type RefetchQueryFilters = + Shared.RefetchQueryFilters -/** - * An infinite query result that always has `data`: the success and refetch error states. - */ -export type DefinedInfiniteQueryObserverResult< - TData = unknown, - TError = DefaultError, -> = - | InfiniteQueryObserverRefetchErrorResult - | InfiniteQueryObserverSuccessResult +export type MutationFunctionContext = + Shared.MutationFunctionContext -/** - * The result of an `InfiniteQueryObserver`, and of the hooks built on it like `useInfiniteQuery`. - * Narrow it by `status` or the `is*` flags to get the type of each state. - */ -export type InfiniteQueryObserverResult< +export type MutationFunction< TData = unknown, - TError = DefaultError, -> = - | DefinedInfiniteQueryObserverResult - | InfiniteQueryObserverLoadingErrorResult - | InfiniteQueryObserverLoadingResult - | InfiniteQueryObserverPendingResult - | InfiniteQueryObserverPlaceholderResult - -/** - * The type of a mutation key — the serializable array used to identify and filter mutations. - * Defaults to `ReadonlyArray`; declare `mutationKey` on {@link Register} to narrow it repository-wide. - */ -export type MutationKey = Register extends { - mutationKey: infer TMutationKey -} - ? TMutationKey extends ReadonlyArray - ? TMutationKey - : TMutationKey extends Array - ? TMutationKey - : ReadonlyArray - : ReadonlyArray - -/** @inline */ -export type MutationStatus = 'idle' | 'pending' | 'success' | 'error' - -/** - * Groups mutations so they run one after another instead of in parallel. - * Mutations that share the same `id` form a queue: while one is running, the others wait in `isPaused: true` - * state and resume automatically when their turn comes. Mutations with no scope always run in parallel. - */ -export type MutationScope = { - /** - * The scope's identifier. Mutations with the same `id` run one after another. - */ - id: string -} - -/** - * The type of the `meta` object that can be attached to a mutation and read back from `mutationFn`, callbacks and - * cache-level handlers. Defaults to `Record`; declare `mutationMeta` on {@link Register} to narrow it. - */ -export type MutationMeta = Register extends { - mutationMeta: infer TMutationMeta -} - ? TMutationMeta extends Record - ? TMutationMeta - : Record - : Record - -/** - * The object passed to `mutationFn` and the mutation callbacks: the `QueryClient`, the mutation's - * `meta`, and its `mutationKey`. - */ -export type MutationFunctionContext = { - /** - * The `QueryClient` the mutation runs in. - */ - client: QueryClient - /** - * The `meta` of the mutation options. - */ - meta: MutationMeta | undefined - /** - * The `mutationKey` of the mutation options, if set. - */ - mutationKey?: MutationKey -} + TVariables = unknown, +> = Shared.MutationFunction -/** @inline */ -export type MutationFunction = ( - variables: TVariables, - context: MutationFunctionContext, -) => Promise - -/** - * The options of a mutation: its `mutationFn`, `mutationKey`, callbacks, retries, `scope`, and so - * on. - */ -export interface MutationOptions< +export type MutationOptions< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> { - /** - * The function that performs the asynchronous task this mutation runs. - * Required, unless a default mutation function has been set for the matching `mutationKey` via - * `queryClient.setMutationDefaults`. - * Receives the `variables` passed to `mutate`, and a {@link MutationFunctionContext} holding the - * `QueryClient`, the `mutationKey` and `meta`. - * Must return a promise that resolves the mutation's data. - */ - mutationFn?: MutationFunction - /** - * The key to use for this mutation. Optional, but required to inherit defaults registered with - * `queryClient.setMutationDefaults`, and to match this mutation with `useMutationState` or - * `queryClient.isMutating`. - */ - mutationKey?: MutationKey - /** - * This function fires before the mutation function runs, and receives the same variables. - * Useful for optimistic updates applied in the hope that the mutation succeeds. - * The value it returns is passed to `onSuccess`, `onError` and `onSettled` as `onMutateResult`, - * which is where an optimistic update is usually rolled back. - * If a promise is returned, it is awaited before the mutation function runs. - */ - onMutate?: ( - variables: TVariables, - context: MutationFunctionContext, - ) => Promise | TOnMutateResult - /** - * This function fires when the mutation succeeds, and is passed the mutation's result. - * If a promise is returned, it is awaited before `onSettled` runs. - */ - onSuccess?: ( - data: TData, - variables: TVariables, - onMutateResult: TOnMutateResult, - context: MutationFunctionContext, - ) => Promise | unknown - /** - * This function fires when the mutation encounters an error, and is passed the error. - * If a promise is returned, it is awaited before `onSettled` runs. - */ - onError?: ( - error: TError, - variables: TVariables, - onMutateResult: TOnMutateResult | undefined, - context: MutationFunctionContext, - ) => Promise | unknown - /** - * This function fires when the mutation either succeeds or errors, and is passed either the data - * or the error. - * If a promise is returned, it is awaited before the mutation settles. - */ - onSettled?: ( - data: TData | undefined, - error: TError | null, - variables: TVariables, - onMutateResult: TOnMutateResult | undefined, - context: MutationFunctionContext, - ) => Promise | unknown - /** - * If `false`, failed mutations will not retry by default. - * If `true`, failed mutations will retry infinitely. - * If set to an integer number, e.g. 3, failed mutations will retry until the failed mutation count meets that number. - * If set to a function `(failureCount, error) => boolean` failed mutations will retry until the function returns false. - * @defaultValue 0 - */ - retry?: RetryValue - /** - * The delay in milliseconds before a retry. Use a number for a fixed delay or a function that receives - * the failure count and error and returns the delay. The count starts at 0 for the first retry. - * - * By default, each retry waits a random duration from 80% to 100% of the base delay. - * The base delay starts at 1 second and doubles for each retry, up to 30 seconds. - */ - retryDelay?: RetryDelayValue - /** - * Controls whether a mutation is allowed to run based on the current network connectivity. - * @defaultValue 'online' - * @see [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. - */ - networkMode?: NetworkMode - /** - * The time in milliseconds that an unused/inactive mutation remains in memory before it is - * garbage collected. - * - * Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. - */ - gcTime?: number - /** @internal */ - _defaulted?: boolean - /** - * Additional payload to be stored on the mutation cache entry. - * Use it to pass information that can be read wherever the `mutation` is available, such as the - * `onError` and `onSuccess` callbacks of the `MutationCache`. - */ - meta?: MutationMeta - /** - * Controls whether this mutation runs alongside others or waits its turn. - * Mutations sharing the same `scope.id` run serially, in the order they were started. - * Without a scope, a mutation runs as soon as it is triggered. - */ - scope?: MutationScope -} +> = Shared.MutationOptions< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> -/** - * The options of a `MutationObserver`, and of the hooks built on it like `useMutation`: the - * {@link MutationOptions}, plus `throwOnError`. - */ -export interface MutationObserverOptions< +export type MutationObserverOptions< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> extends MutationOptions { - /** - * Whether errors should be thrown instead of setting the `error` property. - * If set to `true`, all errors will be thrown to the nearest error boundary. - * If set to a function, it will be passed the error and should return a boolean indicating whether to throw the - * error (`true`) or return it as state (`false`). - * @defaultValue false - */ - throwOnError?: boolean | ((error: TError) => boolean) -} +> = Shared.MutationObserverOptions< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> -/** - * The callbacks that can be passed to `mutate` for a single call. They run after the callbacks of - * the mutation options. - */ -export interface MutateOptions< +export type MutateOptions< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> { - /** - * Called when the mutation of this call succeeds, after the `onSuccess` of the mutation options. - */ - onSuccess?: ( - data: TData, - variables: TVariables, - onMutateResult: TOnMutateResult | undefined, - context: MutationFunctionContext, - ) => void - /** - * Called when the mutation of this call fails, after the `onError` of the mutation options. - */ - onError?: ( - error: TError, - variables: TVariables, - onMutateResult: TOnMutateResult | undefined, - context: MutationFunctionContext, - ) => void - /** - * Called when the mutation of this call succeeds or fails, after the `onSettled` of the mutation - * options. - */ - onSettled?: ( - data: TData | undefined, - error: TError | null, - variables: TVariables, - onMutateResult: TOnMutateResult | undefined, - context: MutationFunctionContext, - ) => void -} +> = Shared.MutateOptions< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> -/** - * The parameters of {@link MutateFunction}: `variables`, optional when `TVariables` accepts - * `undefined`, and the {@link MutateOptions} for that call. - */ export type MutateFunctionRest< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> = undefined extends TVariables - ? [ - variables?: TVariables, - options?: MutateOptions, - ] - : [ - variables: TVariables, - options?: MutateOptions, - ] +> = Shared.MutateFunctionRest< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> -/** - * The `mutate` function of a `MutationObserver`: runs the mutation with the given variables and - * resolves with its data. - */ export type MutateFunction< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> = ( - ...rest: MutateFunctionRest -) => Promise +> = Shared.MutateFunction< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> -/** - * The properties shared by every state of a mutation result, like `data`, `error`, `variables`, - * `status`, the `is*` flags, `mutate`, and `reset`. - */ -export interface MutationObserverBaseResult< +export type MutationObserverBaseResult< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> extends MutationState { - /** - * The last successfully resolved data for the mutation. - */ - data: TData | undefined - /** - * The variables object passed to the `mutationFn`. - */ - variables: TVariables | undefined - /** - * The error object for the mutation, if an error was encountered. - * - Defaults to `null`. - */ - error: TError | null - /** - * A boolean variable derived from `status`. - * - `true` if the last mutation attempt resulted in an error. - */ - isError: boolean - /** - * A boolean variable derived from `status`. - * - `true` if the mutation is in its initial state prior to executing. - */ - isIdle: boolean - /** - * A boolean variable derived from `status`. - * - `true` if the mutation is currently executing. - */ - isPending: boolean - /** - * A boolean variable derived from `status`. - * - `true` if the last mutation attempt was successful. - */ - isSuccess: boolean - /** - * The status of the mutation. - * - Will be: - * - `idle` initial status prior to the mutation function executing. - * - `pending` if the mutation is currently executing. - * - `error` if the last mutation attempt resulted in an error. - * - `success` if the last mutation attempt was successful. - */ - status: MutationStatus - /** - * The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options. - * @param variables - The variables object to pass to the `mutationFn`. - * @param options.onSuccess - This function will fire when the mutation is successful and will be passed the mutation's result. - * @param options.onError - This function will fire if the mutation encounters an error and will be passed the error. - * @param options.onSettled - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error. - * @remarks - * - If you make multiple requests, `onSuccess` will fire only after the latest call you've made. - * - All the callback functions (`onSuccess`, `onError`, `onSettled`) are void functions, and the returned value will be ignored. - */ - mutate: MutateFunction - /** - * A function to clean the mutation internal state (i.e., it resets the mutation to its initial state). - */ - reset: () => void -} +> = Shared.MutationObserverBaseResult< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> -/** - * A mutation result in the `idle` state: the mutation hasn't run yet, or was reset. - */ -export interface MutationObserverIdleResult< +export type MutationObserverIdleResult< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> extends MutationObserverBaseResult< +> = Shared.MutationObserverIdleResult< + QueryRuntime, TData, TError, TVariables, TOnMutateResult -> { - /** - * `undefined`, since the mutation hasn't run. - */ - data: undefined - /** - * `undefined`, since the mutation hasn't run. - */ - variables: undefined - /** - * `null`, since the mutation hasn't failed. - */ - error: null - /** - * `false`, since the mutation hasn't failed. - */ - isError: false - /** - * `true`, since the mutation hasn't run yet or was reset. - */ - isIdle: true - /** - * `false`, since the mutation isn't running. - */ - isPending: false - /** - * `false`, since the mutation hasn't succeeded. - */ - isSuccess: false - /** - * `'idle'`, since the mutation hasn't run yet or was reset. - */ - status: 'idle' -} +> -/** - * A mutation result in the `pending` state while the mutation runs. - */ -export interface MutationObserverLoadingResult< +export type MutationObserverLoadingResult< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> extends MutationObserverBaseResult< +> = Shared.MutationObserverLoadingResult< + QueryRuntime, TData, TError, TVariables, TOnMutateResult -> { - /** - * `undefined`, since the mutation hasn't succeeded. - */ - data: undefined - /** - * The variables passed to `mutate` for this mutation. - */ - variables: TVariables - /** - * `null`, since the mutation hasn't failed. - */ - error: null - /** - * `false`, since the mutation hasn't failed. - */ - isError: false - /** - * `false`, since the mutation has run. - */ - isIdle: false - /** - * `true`, since the mutation is running. - */ - isPending: true - /** - * `false`, since the mutation hasn't succeeded. - */ - isSuccess: false - /** - * `'pending'`, since the mutation is running. - */ - status: 'pending' -} +> -/** - * A mutation result in the `error` state after the mutation failed. - */ -export interface MutationObserverErrorResult< +export type MutationObserverErrorResult< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> extends MutationObserverBaseResult< +> = Shared.MutationObserverErrorResult< + QueryRuntime, TData, TError, TVariables, TOnMutateResult -> { - /** - * `undefined`, since the mutation hasn't succeeded. - */ - data: undefined - /** - * The error the mutation failed with. - */ - error: TError - /** - * The variables passed to `mutate` for this mutation. - */ - variables: TVariables - /** - * `true`, since the mutation failed. - */ - isError: true - /** - * `false`, since the mutation has run. - */ - isIdle: false - /** - * `false`, since the mutation isn't running. - */ - isPending: false - /** - * `false`, since the mutation hasn't succeeded. - */ - isSuccess: false - /** - * `'error'`, since the mutation failed. - */ - status: 'error' -} +> -/** - * A mutation result in the `success` state after the mutation succeeded. - */ -export interface MutationObserverSuccessResult< +export type MutationObserverSuccessResult< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> extends MutationObserverBaseResult< +> = Shared.MutationObserverSuccessResult< + QueryRuntime, TData, TError, TVariables, TOnMutateResult -> { - /** - * The data the mutation resolved with. - */ - data: TData - /** - * `null`, since the mutation hasn't failed. - */ - error: null - /** - * The variables passed to `mutate` for this mutation. - */ - variables: TVariables - /** - * `false`, since the mutation hasn't failed. - */ - isError: false - /** - * `false`, since the mutation has run. - */ - isIdle: false - /** - * `false`, since the mutation isn't running. - */ - isPending: false - /** - * `true`, since the mutation succeeded. - */ - isSuccess: true - /** - * `'success'`, since the mutation succeeded. - */ - status: 'success' -} +> -/** - * The result of a `MutationObserver`, and of the hooks built on it like `useMutation`. Narrow it by - * `status` or the `is*` flags to get the type of each state. - */ export type MutationObserverResult< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> = - | MutationObserverIdleResult - | MutationObserverLoadingResult - | MutationObserverErrorResult - | MutationObserverSuccessResult - -/** - * The options of `new QueryClient()`: the `queryCache` and `mutationCache` to use, and the - * `defaultOptions` for its queries and mutations. - */ -export interface QueryClientConfig { - /** The query cache this client is connected to. A new `QueryCache` is created if not provided. */ - queryCache?: QueryCache - /** - * The mutation cache this client is connected to. A new `MutationCache` is created if not - * provided. - */ - mutationCache?: MutationCache - /** Default options for all queries and mutations created through this client. */ - defaultOptions?: DefaultOptions -} - -/** - * The default options of a `QueryClient`, applied to every query (`queries`), mutation - * (`mutations`), `hydrate`, and `dehydrate` call unless overridden. - */ -export interface DefaultOptions { - /** Default options applied to every query, unless overridden per-query. */ - queries?: OmitKeyof< - QueryObserverOptionsBase, - 'suspense' | 'queryKey' - > - /** Default options applied to every mutation, unless overridden per-mutation. */ - mutations?: MutationObserverOptions - /** Default options used when hydrating queries and mutations; see {@link HydrateOptions}. */ - hydrate?: HydrateOptions['defaultOptions'] - /** Default options used when dehydrating the client's caches; see {@link DehydrateOptions}. */ - dehydrate?: DehydrateOptions -} - -/** - * Options for cancelling an in-flight fetch, e.g. via `query.cancel()`. - * They are carried on the {@link CancelledError} that the cancelled fetch rejects with. - */ -export interface CancelOptions { - /** - * If `true`, the query goes back to the state it had before the fetch started, instead of getting - * the cancellation error. - */ - revert?: boolean - /** - * If `true`, the cancellation error isn't surfaced, e.g. because another fetch replaces the - * cancelled one. - */ - silent?: boolean -} +> = Shared.MutationObserverResult< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> -/** - * Options for writing data into the cache, e.g. via `queryClient.setQueryData()`. - * `updatedAt` overrides the timestamp the data is recorded with, which is what staleness is measured from; - * omit it to use the current time. - */ -export interface SetDataOptions { - /** - * The timestamp to record the data with, instead of the current time. Staleness is measured from - * it. - */ - updatedAt?: number -} +export type QueryClientConfig = Shared.QueryClientConfig -/** @inline */ -export type NotifyEventType = - | 'added' - | 'removed' - | 'updated' - | 'observerAdded' - | 'observerRemoved' - | 'observerResultsUpdated' - | 'observerOptionsUpdated' +export type DefaultOptions = Shared.DefaultOptions< + QueryRuntime, + TError +> -/** - * The base shape of the events that the query and mutation caches send to their listeners. - */ -export interface NotifyEvent { - /** - * The kind of event, e.g. `'added'`, `'removed'`, or `'updated'`. - */ - type: NotifyEventType -} +export type { + NonUndefinedGuard, + DistributiveOmit, + OmitKeyof, + Override, + Register, + DefaultError, + QueryKey, + 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, + QueryObserverResult, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverPendingResult, + InfiniteQueryObserverLoadingResult, + InfiniteQueryObserverLoadingErrorResult, + InfiniteQueryObserverRefetchErrorResult, + InfiniteQueryObserverSuccessResult, + InfiniteQueryObserverPlaceholderResult, + DefinedInfiniteQueryObserverResult, + InfiniteQueryObserverResult, + MutationKey, + MutationStatus, + MutationScope, + MutationMeta, + CancelOptions, + SetDataOptions, + NotifyEventType, + NotifyEvent, +} from '@tanstack/query-types/bindings' diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index 7f39a202c20..2ffd6135e6a 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -1,114 +1,41 @@ import { timeoutManager } from './timeoutManager' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + DefaultQueryFn, + DefaultQueryFn as defaultQueryFnType, + FetchSignal as fetchSignalType, + SkipToken, + SkipToken as skipTokenType, + Updater, +} from '@tanstack/query-types/bindings' import type { Mutation } from './mutation' import type { FetchOptions, Query } from './query' +import type { QueryRuntime } from './runtimeBinding' import type { CacheKeyConfig, DefaultError, EqualityFn, - FetchStatus, MutationKey, - MutationStatus, QueryFunction, QueryKey, QueryOptions, } from './types' -// TYPES - -type DropLast> = T extends readonly [ - ...infer R, - unknown, -] - ? readonly [...R] - : never - -type TuplePrefixes> = T extends readonly [] - ? readonly [] - : TuplePrefixes> | T - -/** - * Filters used to select queries, for example in `queryClient.getQueriesData` or `queryClient.invalidateQueries`. - * All provided filters must match; filters that are left unspecified are ignored. - */ -export interface QueryFilters { - /** - * Filter to active queries, inactive queries or all queries - * @defaultValue 'all' - */ - type?: QueryTypeFilter - /** - * Match query key exactly - */ - exact?: boolean - /** - * Include queries matching this predicate function - */ - predicate?: (query: Query) => boolean - /** - * Include queries matching this query key - */ - queryKey?: TQueryKey | TuplePrefixes - /** - * Include or exclude stale queries - */ - stale?: boolean - /** - * Include queries matching their fetchStatus - */ - fetchStatus?: FetchStatus -} +export type QueryFilters = + Shared.QueryFilters -/** - * Filters used to select mutations, for example in `mutationCache.findAll` or `queryClient.isMutating`. - * All provided filters must match; filters that are left unspecified are ignored. - */ -export interface MutationFilters< +export type MutationFilters< TData = unknown, TError = DefaultError, TVariables = unknown, TOnMutateResult = unknown, -> { - /** - * Match mutation key exactly - */ - exact?: boolean - /** - * Include mutations matching this predicate function - */ - predicate?: ( - mutation: Mutation, - ) => boolean - /** - * Include mutations matching this mutation key - */ - mutationKey?: TuplePrefixes - /** - * Filter by mutation status - */ - status?: MutationStatus -} - -/** - * Either a plain value of type `TOutput`, or a function that receives `TInput` and returns `TOutput`. - * Used for example by `setQueryData`-style updaters, which accept either the new data directly or a - * function that computes it from the previous data. See {@link functionalUpdate}. - * @example - * ```ts - * queryClient.setQueryData(['posts'], newPosts) - * - * // Or, using an updater function that receives the current data: - * queryClient.setQueryData(['posts'], (oldPosts) => - * oldPosts ? [...oldPosts, newPost] : oldPosts, - * ) - * ``` - */ -export type Updater = TOutput | ((input: TInput) => TOutput) - -/** - * Which queries a filter matches: all of them, only active ones (with enabled observers), or only - * inactive ones. - */ -export type QueryTypeFilter = 'all' | 'active' | 'inactive' +> = Shared.MutationFilters< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> // UTILS @@ -673,21 +600,18 @@ export function addToArray( * }) * ``` */ -export const skipToken = Symbol() -/** - * The type of the {@link skipToken} sentinel value. - */ -export type SkipToken = typeof skipToken +export const skipToken: skipTokenType = Symbol.for( + '@tanstack/query/skipToken', +) as skipTokenType /** * Pass this as `queryFn` to use the query function configured on the client. * The defaults for the query key take precedence over the client's global query defaults. * If no query function is configured, a fetch fails with a `Missing queryFn` error. */ -export const defaultQueryFn = Symbol() - -/** The type of the {@link defaultQueryFn} sentinel value. */ -export type DefaultQueryFn = typeof defaultQueryFn +export const defaultQueryFn: defaultQueryFnType = Symbol.for( + '@tanstack/query/defaultQueryFn', +) as defaultQueryFnType /** * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from @@ -767,15 +691,9 @@ export function shouldThrowError) => boolean>( return !!throwOnError } -export const fetchSignal = Symbol() - -/** Internal view of a context that can expose its signal without consuming it. */ -export type FetchSignalContext = { - /** The public signal, whose getter can mark it consumed. */ - readonly signal: AbortSignal - /** The original fetch signal, absent on application-created contexts. */ - readonly [fetchSignal]?: AbortSignal -} +export const fetchSignal: fetchSignalType = Symbol.for( + '@tanstack/query/fetchSignal', +) as fetchSignalType /** * Adds a lazy `signal` getter to an object, such as a query function context. The first time @@ -820,3 +738,11 @@ export function addConsumeAwareSignal( return object as T & { signal: AbortSignal } } + +export type { + Updater, + QueryTypeFilter, + SkipToken, + DefaultQueryFn, + FetchSignalContext, +} from '@tanstack/query-types/bindings' diff --git a/packages/query-core/tsconfig.json b/packages/query-core/tsconfig.json index 0cc454b2a77..bd0c9448b94 100644 --- a/packages/query-core/tsconfig.json +++ b/packages/query-core/tsconfig.json @@ -4,5 +4,10 @@ "outDir": "./dist-ts", "rootDir": "." }, - "include": ["src", "*.config.ts", "*.config.js", "package.json"] + "include": ["src", "*.config.ts", "*.config.js", "package.json"], + "references": [ + { + "path": "../query-types" + } + ] } diff --git a/packages/query-core/tsconfig.legacy.json b/packages/query-core/tsconfig.legacy.json index 84ebe1a984b..0525af804f1 100644 --- a/packages/query-core/tsconfig.legacy.json +++ b/packages/query-core/tsconfig.legacy.json @@ -4,5 +4,10 @@ "outDir": "./dist-ts/legacy" }, "include": ["src"], - "exclude": ["src/__tests__"] + "exclude": ["src/__tests__"], + "references": [ + { + "path": "../query-types" + } + ] } diff --git a/packages/query-types/oxlint.config.ts b/packages/query-types/oxlint.config.ts new file mode 100644 index 00000000000..396987b4462 --- /dev/null +++ b/packages/query-types/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-types/package.json b/packages/query-types/package.json new file mode 100644 index 00000000000..e02d3c1becf --- /dev/null +++ b/packages/query-types/package.json @@ -0,0 +1,57 @@ +{ + "name": "@tanstack/query-types", + "version": "5.108.4", + "description": "Shared TypeScript declarations for TanStack Query", + "author": "tannerlinsley", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/TanStack/query.git", + "directory": "packages/query-types" + }, + "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: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", + "./bindings": { + "@tanstack/custom-condition": "./src/bindings.ts", + "types": "./build/bindings.d.ts", + "default": "./build/bindings.js" + } + }, + "sideEffects": false, + "files": [ + "build", + "src", + "!src/__tests__" + ], + "devDependencies": { + "typescript": "catalog:" + } +} diff --git a/packages/query-types/root.oxlint.config.ts b/packages/query-types/root.oxlint.config.ts new file mode 120000 index 00000000000..56565c65534 --- /dev/null +++ b/packages/query-types/root.oxlint.config.ts @@ -0,0 +1 @@ +../../oxlint.config.ts \ No newline at end of file diff --git a/packages/query-types/root.tsdown.config.js b/packages/query-types/root.tsdown.config.js new file mode 120000 index 00000000000..a997d5d337c --- /dev/null +++ b/packages/query-types/root.tsdown.config.js @@ -0,0 +1 @@ +../../scripts/getTsdownConfig.js \ No newline at end of file diff --git a/packages/query-types/src/binding.ts b/packages/query-types/src/binding.ts new file mode 100644 index 00000000000..7b698d755c0 --- /dev/null +++ b/packages/query-types/src/binding.ts @@ -0,0 +1,61 @@ +import type { DefaultError, QueryKey } from './types' + +/** Runtime implementations bind these slots to their own nominal class types. */ +export interface RuntimeBinding { + args: unknown + QueryClient: unknown + QueryCache: unknown + MutationCache: unknown + Query: unknown + Mutation: unknown + QueryObserver: unknown + MutationObserver: unknown +} + +export type QueryClientOf = + TRuntime['QueryClient'] + +export type QueryCacheOf = + TRuntime['QueryCache'] + +export type MutationCacheOf = + TRuntime['MutationCache'] + +export type QueryOf< + TRuntime extends RuntimeBinding, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = (TRuntime & { args: [TQueryFnData, TError, TData, TQueryKey] })['Query'] + +export type MutationOf< + TRuntime extends RuntimeBinding, + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> = (TRuntime & { + args: [TData, TError, TVariables, TOnMutateResult] +})['Mutation'] + +export type QueryObserverOf< + TRuntime extends RuntimeBinding, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = (TRuntime & { + args: [TQueryFnData, TError, TData, TQueryData, TQueryKey] +})['QueryObserver'] + +export type MutationObserverOf< + TRuntime extends RuntimeBinding, + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = (TRuntime & { + args: [TData, TError, TVariables, TOnMutateResult] +})['MutationObserver'] diff --git a/packages/query-types/src/bindings.ts b/packages/query-types/src/bindings.ts new file mode 100644 index 00000000000..126a5983b2a --- /dev/null +++ b/packages/query-types/src/bindings.ts @@ -0,0 +1,235 @@ +export type { RuntimeBinding } from './binding' +export type { fetchSignal as FetchSignal } from './symbols' +export type { IsServerValue } from './environmentManager' +export type { FocusManagerListener, FocusManagerSetupFn } from './focusManager' +export type { + TransformerFn, + DehydrateOptions, + HydrateOptions, + DehydratedMutation, + DehydratedQuery, + DehydratedState, +} from './hydration' +export type { + InfiniteQueryObserverListener, + InfiniteObserverOptionsInput, + ReplaceReturnType, +} from './infiniteQueryObserver' +export type { + MutationConfig, + MutationState, + MutationFailedAction, + PendingAction, + MutationSuccessAction, + MutationErrorAction, + MutationPauseAction, + MutationContinueAction, + MutationAction, +} from './mutation' +export type { + MutationCacheConfig, + NotifyEventMutationAdded, + NotifyEventMutationRemoved, + NotifyEventMutationObserverAdded, + NotifyEventMutationObserverRemoved, + NotifyEventMutationObserverOptionsUpdated, + NotifyEventMutationUpdated, + MutationCacheNotifyEvent, + MutationCacheListener, +} from './mutationCache' +export type { MutationObserverListener } from './mutationObserver' +export type { + NotifyCallback, + NotifyFunction, + BatchNotifyFunction, + BatchCallsCallback, + ScheduleFunction, +} from './notifyManager' +export type { + OnlineManagerListener, + OnlineManagerSetupFn, +} from './onlineManager' +export type { + QueriesObserverListener, + CombineFn, + QueriesObserverResultReader, + CombineContext, + QueriesObserverOptions, + QueryObserverMatch, +} from './queriesObserver' +export type { + QueryConfig, + QueryState, + FetchContext, + QueryBehavior, + FetchDirection, + FetchMeta, + FetchOptions, + QueryFailedAction, + FetchAction, + QuerySuccessAction, + QueryErrorAction, + InvalidateAction, + QueryPauseAction, + QueryContinueAction, + SetStateAction, + QueryAction, +} from './query' +export type { + QueryCacheConfig, + NotifyEventQueryAdded, + NotifyEventQueryRemoved, + NotifyEventQueryUpdated, + NotifyEventQueryObserverAdded, + NotifyEventQueryObserverRemoved, + NotifyEventQueryObserverResultsUpdated, + NotifyEventQueryObserverOptionsUpdated, + QueryCacheNotifyEvent, + QueryCacheListener, + QueryStore, +} from './queryCache' +export type { + WithoutSkipToken, + QueryDefaults, + MutationDefaults, +} from './queryClient' +export type { + QueryObserverListener, + ObserverFetchOptions, + QueryObserverResultReader, + ProjectionFailure, + QueryObserverResultContext, + ObserverOptionsInput, +} from './queryObserver' +export type { + RetryerConfig, + Retryer, + RetryerStatus, + RetryValue, + ShouldRetryFunction, + RetryDelayValue, + RetryDelayFunction, +} from './retryer' +export type { + BaseStreamedQueryParams, + SimpleStreamedQueryParams, + ReducibleStreamedQueryParams, + StreamedQueryParams, +} from './streamedQuery' +export type { + TimeoutCallback, + ManagedTimerId, + TimeoutProvider, + SystemTimerId, +} from './timeoutManager' +export type { + NonUndefinedGuard, + DistributiveOmit, + OmitKeyof, + Override, + Register, + DefaultError, + QueryKey, + dataTagSymbol, + dataTagErrorSymbol, + UnsetMarker, + AnyDataTag, + DataTag, + QueryKeyWithDataTag, + InferDataFromTag, + InferErrorFromTag, + QueryFunction, + StaleTime, + StaleTimeFunction, + QueryBooleanOption, + QueryPersister, + QueryFunctionContext, + InitialDataFunction, + NonFunctionGuard, + PlaceholderDataFunction, + QueriesPlaceholderDataFunction, + EqualityFn, + CacheKeyHashFunction, + CacheKeyConfig, + GetPreviousPageParamFunction, + GetNextPageParamFunction, + InfiniteData, + QueryMeta, + NetworkMode, + NotifyOnChangeProps, + QueryOptions, + InitialPageParam, + InfiniteQueryPageParamsOptions, + ThrowOnError, + QueryObserverOptionsBase, + QueryObserverOptions, + WithRequired, + DefaultedQueryObserverOptions, + InfiniteQueryObserverOptions, + DefaultedInfiniteQueryObserverOptions, + QueryExecuteOptions, + InfiniteQueryFetchPageOptions, + InfiniteQueryExecuteOptions, + ResultOptions, + RefetchOptions, + InvalidateQueryFilters, + RefetchQueryFilters, + InvalidateOptions, + ResetOptions, + FetchNextPageOptions, + FetchPreviousPageOptions, + QueryStatus, + FetchStatus, + QueryObserverBaseResult, + QueryObserverPendingResult, + QueryObserverLoadingResult, + QueryObserverLoadingErrorResult, + QueryObserverRefetchErrorResult, + QueryObserverSuccessResult, + QueryObserverPlaceholderResult, + DefinedQueryObserverResult, + QueryObserverResult, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverPendingResult, + InfiniteQueryObserverLoadingResult, + InfiniteQueryObserverLoadingErrorResult, + InfiniteQueryObserverRefetchErrorResult, + InfiniteQueryObserverSuccessResult, + InfiniteQueryObserverPlaceholderResult, + DefinedInfiniteQueryObserverResult, + InfiniteQueryObserverResult, + MutationKey, + MutationStatus, + MutationScope, + MutationMeta, + MutationFunctionContext, + MutationFunction, + MutationOptions, + MutationObserverOptions, + MutateOptions, + MutateFunctionRest, + MutateFunction, + MutationObserverBaseResult, + MutationObserverIdleResult, + MutationObserverLoadingResult, + MutationObserverErrorResult, + MutationObserverSuccessResult, + MutationObserverResult, + QueryClientConfig, + DefaultOptions, + CancelOptions, + SetDataOptions, + NotifyEventType, + NotifyEvent, +} from './types' +export type { + DropLast, + TuplePrefixes, + QueryFilters, + MutationFilters, + Updater, + QueryTypeFilter, + SkipToken, + DefaultQueryFn, + FetchSignalContext, +} from './utils' diff --git a/packages/query-types/src/contracts.ts b/packages/query-types/src/contracts.ts new file mode 100644 index 00000000000..a2aa2bf61a6 --- /dev/null +++ b/packages/query-types/src/contracts.ts @@ -0,0 +1,541 @@ +import type { RuntimeBinding } from './binding' +import type { MutationCacheListener as SharedMutationCacheListener } from './mutationCache' +import type { MutationObserverListener as SharedMutationObserverListener } from './mutationObserver' +import type { QueryCacheListener as SharedQueryCacheListener } from './queryCache' +import type { WithoutSkipToken } from './queryClient' +import type { QueryObserverListener } from './queryObserver' +import type { + CancelOptions, + DefaultError, + DefaultOptions, + DefaultedQueryObserverOptions, + FetchOptions, + InferDataFromTag, + InferErrorFromTag, + InfiniteData, + InfiniteQueryExecuteOptions, + InvalidateOptions, + InvalidateQueryFilters, + MutateOptions, + MutationAction, + MutationCacheConfig, + MutationCacheNotifyEvent, + MutationFilters, + MutationKey, + MutationMeta, + MutationObserverOptions, + MutationObserverResult, + MutationOptions, + MutationState, + ObserverOptionsInput, + OmitKeyof, + QueryCacheConfig, + QueryCacheNotifyEvent, + QueryExecuteOptions, + QueryFilters, + QueryKey, + QueryMeta, + QueryObserverOptionsBase, + QueryObserverResult, + QueryObserverResultReader, + QueryOptions, + QueryState, + RefetchOptions, + RefetchQueryFilters, + ResetOptions, + SetDataOptions, + StaleTime, + Updater, + WithRequired, +} from './index' +interface Subscription { + subscribe(listener: TListener): () => void + hasListeners(): boolean +} +interface CacheEntry { + gcTime: number + destroy(): void +} +export interface QueryClient { + mount(): void + unmount(): void + isFetching(filters?: Omit): number + isMutating< + TMutationFilters extends MutationFilters = MutationFilters< + any, + any + >, + >( + filters?: NoInfer>, + ): number + getQueryData< + TQueryFnData = unknown, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, + >( + queryKey: TTaggedQueryKey, + ): TInferredQueryFnData | undefined + getQueriesData< + TQueryFnData = unknown, + TQueryFilters extends QueryFilters = QueryFilters, + >( + filters: TQueryFilters, + ): Array<[QueryKey, TQueryFnData | undefined]> + setQueryData< + TQueryFnData = unknown, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, + >( + queryKey: TTaggedQueryKey, + updater: Updater< + InferDataFromTag, TTaggedQueryKey> | undefined, + NoInfer | undefined + >, + options?: SetDataOptions, + ): NoInfer | undefined + setQueriesData< + TQueryFnData, + TQueryFilters extends QueryFilters = QueryFilters, + >( + filters: TQueryFilters, + updater: Updater< + NoInfer | undefined, + NoInfer | undefined + >, + options?: SetDataOptions, + ): Array<[QueryKey, TQueryFnData | undefined]> + getQueryState< + TQueryFnData = unknown, + TError = DefaultError, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, + TInferredError = InferErrorFromTag, + >( + queryKey: TTaggedQueryKey, + ): QueryState | undefined + removeQueries( + filters?: QueryFilters, + ): void + resetQueries( + filters?: QueryFilters, + options?: ResetOptions, + ): Promise + cancelQueries( + filters?: QueryFilters, + cancelOptions?: CancelOptions, + ): Promise + invalidateQueries( + filters?: InvalidateQueryFilters, + options?: InvalidateOptions, + ): Promise + refetchQueries( + filters?: RefetchQueryFilters, + options?: RefetchOptions, + ): Promise + query< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, + >( + options: WithoutSkipToken< + QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > + >, + ): Promise + query< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, + >( + options: QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + ): Promise + infiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: WithoutSkipToken< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + >, + ): Promise< + Array extends Array> + ? InfiniteData + : TData + > + infiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): Promise< + | undefined + | (Array extends Array> + ? InfiniteData + : TData) + > + resumePausedMutations(): Promise + getQueryCache(): QueryCache + getMutationCache(): MutationCache + getDefaultOptions(): DefaultOptions + setDefaultOptions(options: DefaultOptions): void + setQueryDefaults< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + >( + queryKey: QueryKey, + options: Partial< + OmitKeyof< + QueryObserverOptionsBase, + 'queryKey' + > + >, + ): void + getQueryDefaults( + queryKey: QueryKey, + ): OmitKeyof, 'queryKey'> + setMutationDefaults< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, + >( + mutationKey: MutationKey, + options: OmitKeyof< + MutationObserverOptions, + 'mutationKey' + >, + ): void + getMutationDefaults( + mutationKey: MutationKey, + ): OmitKeyof, 'mutationKey'> + defaultQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, + >( + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + ): DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > + defaultMutationOptions>( + options?: T, + ): T + clear(): void +} + +export interface QueryCache extends Subscription { + config: QueryCacheConfig + build< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + client: QueryClient, + options: WithRequired< + QueryOptions, + 'queryKey' + >, + state?: QueryState, + ): Query + add(query: Query): void + remove(query: Query): void + clear(): void + get< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + queryHash: string, + ): Query | undefined + getAll(): Array + find( + filters: WithRequired, + ): Query | undefined + findAll(filters?: QueryFilters): Array + notify(event: QueryCacheNotifyEvent): void + onFocus(): void + onOnline(): void +} + +export interface MutationCache extends Subscription { + config: MutationCacheConfig + register>(create: (id: number) => T): T + add(mutation: Mutation): void + remove(mutation: Mutation): void + has(mutation: Mutation): boolean + canRun(mutation: Mutation): boolean + runNext(mutation: Mutation): Promise + clear(): void + getAll(): Array + find< + TData = unknown, + TError = DefaultError, + TVariables = any, + TOnMutateResult = unknown, + >( + filters: MutationFilters, + ): Mutation | undefined + findAll(filters?: MutationFilters): Array + notify(event: MutationCacheNotifyEvent): void + resumePausedMutations(): Promise +} + +export interface Query< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends CacheEntry { + queryKey: TQueryKey + queryHash: string + options: QueryOptions + state: QueryState + observers: Array> + get meta(): QueryMeta | undefined + get queryType(): 'infinite' | undefined + get promise(): Promise | undefined + setOptions( + options?: QueryOptions, + ): void + setData( + newData: TData, + options?: SetDataOptions & { + manual: boolean + }, + ): TData + setState(state: Partial>): void + cancel(options?: CancelOptions): Promise + destroy(): void + get resetState(): QueryState + reset(): void + isActive(): boolean + isDisabled(): boolean + isFetched(): boolean + isStatic(): boolean + isStale(): boolean + isStaleByTime(staleTime?: StaleTime): boolean + onFocus(): void + onOnline(): void + addObserver(observer: QueryObserver): void + removeObserver(observer: QueryObserver): void + getObserversCount(): number + invalidate(): void + fetch( + options?: QueryOptions, + fetchOptions?: FetchOptions, + ): Promise +} + +export interface Mutation< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> extends CacheEntry { + state: MutationState + options: MutationOptions + readonly mutationId: number + setOptions( + options: MutationOptions, + ): void + get meta(): MutationMeta | undefined + addObserver(observer: MutationObserver): void + removeObserver(observer: MutationObserver): void + continue(): Promise + execute(variables: TVariables): Promise +} + +export interface QueryObserver< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends Subscription> { + options: ObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + > + shouldFetchOnReconnect(): boolean + shouldFetchOnWindowFocus(): boolean + destroy(): void + setOptions( + options: ObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ): void + createResultReader( + options: DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ): QueryObserverResultReader> + getCurrentResult(): QueryObserverResult + trackResult( + result: QueryObserverResult, + onPropTracked?: (key: keyof QueryObserverResult) => void, + ): QueryObserverResult + trackProp(key: keyof QueryObserverResult): void + getCurrentQuery(): Query + refetch(options?: RefetchOptions): Promise> + fetchOptimistic( + options: ObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ): Promise> + updateResult(): void + onQueryUpdate(): void +} + +export interface MutationObserver< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends Subscription< + MutationObserverListener +> { + options: MutationObserverOptions + setOptions( + options: MutationObserverOptions< + TData, + TError, + TVariables, + TOnMutateResult + >, + ): void + onMutationUpdate( + action: MutationAction, + ): void + getCurrentResult(): MutationObserverResult< + TData, + TError, + TVariables, + TOnMutateResult + > + reset(): void + mutate( + variables: TVariables, + options?: MutateOptions, + ): Promise +} + +type QueryCacheListener = SharedQueryCacheListener +type MutationCacheListener = SharedMutationCacheListener +type MutationObserverListener = + SharedMutationObserverListener< + DefaultRuntime, + TData, + TError, + TVariables, + TOnMutateResult + > + +/** Structural public class shapes used when importing types without a runtime. */ +export interface DefaultRuntime extends RuntimeBinding { + QueryClient: QueryClient + QueryCache: QueryCache + MutationCache: MutationCache + Query: this['args'] extends [ + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryKey extends QueryKey, + ] + ? Query + : never + Mutation: this['args'] extends [ + infer TData, + infer TError, + infer TVariables, + infer TOnMutateResult, + ] + ? Mutation + : never + QueryObserver: this['args'] extends [ + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryData, + infer TQueryKey extends QueryKey, + ] + ? QueryObserver + : never + MutationObserver: this['args'] extends [ + infer TData, + infer TError, + infer TVariables, + infer TOnMutateResult, + ] + ? MutationObserver + : never +} diff --git a/packages/query-types/src/environmentManager.ts b/packages/query-types/src/environmentManager.ts new file mode 100644 index 00000000000..e2d5f01ecbf --- /dev/null +++ b/packages/query-types/src/environmentManager.ts @@ -0,0 +1,4 @@ +/** + * A function that returns whether the code is running on the server. + */ +export type IsServerValue = () => boolean diff --git a/packages/query-types/src/focusManager.ts b/packages/query-types/src/focusManager.ts new file mode 100644 index 00000000000..f9c2a5eb0a4 --- /dev/null +++ b/packages/query-types/src/focusManager.ts @@ -0,0 +1,5 @@ +export type FocusManagerListener = (focused: boolean) => void + +export type FocusManagerSetupFn = ( + setFocused: (focused?: boolean) => void, +) => (() => void) | undefined diff --git a/packages/query-types/src/hydration.ts b/packages/query-types/src/hydration.ts new file mode 100644 index 00000000000..3938903f90a --- /dev/null +++ b/packages/query-types/src/hydration.ts @@ -0,0 +1,89 @@ +import type { MutationOf, QueryOf, RuntimeBinding } from './binding' +import type { MutationState } from './mutation' +import type { QueryState } from './query' +import type { + DefaultError, + MutationKey, + MutationMeta, + MutationOptions, + MutationScope, + QueryKey, + QueryMeta, + QueryOptions, +} from './types' + +export 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: MutationOf) => boolean + /** Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. */ + shouldDehydrateQuery?: (query: QueryOf) => 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< + TRuntime, + unknown, + DefaultError, + unknown, + unknown + > + } +} + +export interface DehydratedMutation { + mutationKey?: MutationKey + state: MutationState + meta?: MutationMeta + scope?: MutationScope +} + +export interface DehydratedQuery { + queryHash: string + queryKey: QueryKey + state: QueryState + dehydratedAt: number + promise?: Promise + meta?: QueryMeta + queryType?: 'infinite' +} + +/** + * 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-types/src/index.ts b/packages/query-types/src/index.ts new file mode 100644 index 00000000000..0a021f0c64d --- /dev/null +++ b/packages/query-types/src/index.ts @@ -0,0 +1,555 @@ +import type { DefaultRuntime } from './contracts' +import type { + DehydrateOptions as SharedDehydrateOptions, + HydrateOptions as SharedHydrateOptions, +} from './hydration' +import type { + MutationCacheConfig as SharedMutationCacheConfig, + MutationCacheNotifyEvent as SharedMutationCacheNotifyEvent, +} from './mutationCache' +import type { + FetchContext as SharedFetchContext, + QueryBehavior as SharedQueryBehavior, +} from './query' +import type { + QueryCacheConfig as SharedQueryCacheConfig, + QueryCacheNotifyEvent as SharedQueryCacheNotifyEvent, + QueryStore as SharedQueryStore, +} from './queryCache' +import type { + ObserverOptionsInput as SharedObserverOptionsInput, + QueryObserverResultContext as SharedQueryObserverResultContext, +} from './queryObserver' +import type { + DefaultError, + DefaultOptions as SharedDefaultOptions, + DefaultedInfiniteQueryObserverOptions as SharedDefaultedInfiniteQueryObserverOptions, + DefaultedQueryObserverOptions as SharedDefaultedQueryObserverOptions, + InfiniteData, + InfiniteQueryExecuteOptions as SharedInfiniteQueryExecuteOptions, + InfiniteQueryObserverOptions as SharedInfiniteQueryObserverOptions, + InvalidateQueryFilters as SharedInvalidateQueryFilters, + MutateFunction as SharedMutateFunction, + MutateFunctionRest as SharedMutateFunctionRest, + MutateOptions as SharedMutateOptions, + MutationFunction as SharedMutationFunction, + MutationFunctionContext as SharedMutationFunctionContext, + MutationObserverBaseResult as SharedMutationObserverBaseResult, + MutationObserverErrorResult as SharedMutationObserverErrorResult, + MutationObserverIdleResult as SharedMutationObserverIdleResult, + MutationObserverLoadingResult as SharedMutationObserverLoadingResult, + MutationObserverOptions as SharedMutationObserverOptions, + MutationObserverResult as SharedMutationObserverResult, + MutationObserverSuccessResult as SharedMutationObserverSuccessResult, + MutationOptions as SharedMutationOptions, + PlaceholderDataFunction as SharedPlaceholderDataFunction, + QueryBooleanOption as SharedQueryBooleanOption, + QueryClientConfig as SharedQueryClientConfig, + QueryExecuteOptions as SharedQueryExecuteOptions, + QueryFunction as SharedQueryFunction, + QueryFunctionContext as SharedQueryFunctionContext, + QueryKey, + QueryObserverOptions as SharedQueryObserverOptions, + QueryObserverOptionsBase as SharedQueryObserverOptionsBase, + QueryOptions as SharedQueryOptions, + QueryPersister as SharedQueryPersister, + RefetchQueryFilters as SharedRefetchQueryFilters, + StaleTimeFunction as SharedStaleTimeFunction, + ThrowOnError as SharedThrowOnError, +} from './types' +import type { + MutationFilters as SharedMutationFilters, + QueryFilters as SharedQueryFilters, +} from './utils' +export type { IsServerValue } from './environmentManager' +export type { DehydratedState } from './hydration' +export type { MutationState, MutationAction } from './mutation' +export type { + QueriesObserverResultReader, + QueriesObserverOptions, +} from './queriesObserver' +export type { + QueryState, + FetchDirection, + FetchMeta, + FetchOptions, + QueryAction, +} from './query' +export type { QueryObserverResultReader } from './queryObserver' +export type { Retryer, RetryValue, RetryDelayValue } from './retryer' +export type { + TimeoutCallback, + ManagedTimerId, + TimeoutProvider, +} from './timeoutManager' +export type { + NonUndefinedGuard, + DistributiveOmit, + OmitKeyof, + Override, + Register, + DefaultError, + QueryKey, + dataTagSymbol, + dataTagErrorSymbol, + 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, + QueryObserverResult, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverPendingResult, + InfiniteQueryObserverLoadingResult, + InfiniteQueryObserverLoadingErrorResult, + InfiniteQueryObserverRefetchErrorResult, + InfiniteQueryObserverSuccessResult, + InfiniteQueryObserverPlaceholderResult, + DefinedInfiniteQueryObserverResult, + InfiniteQueryObserverResult, + MutationKey, + MutationStatus, + MutationScope, + MutationMeta, + CancelOptions, + SetDataOptions, + NotifyEventType, + NotifyEvent, +} from './types' +export type { + Updater, + QueryTypeFilter, + SkipToken, + DefaultQueryFn, + FetchSignalContext, +} from './utils' +export type DehydrateOptions = SharedDehydrateOptions +export type HydrateOptions = SharedHydrateOptions +export type MutationCacheConfig = SharedMutationCacheConfig +export type MutationCacheNotifyEvent = + SharedMutationCacheNotifyEvent +export type FetchContext< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey = QueryKey, +> = SharedFetchContext +export type QueryBehavior< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = SharedQueryBehavior +export type QueryCacheConfig = SharedQueryCacheConfig +export type QueryCacheNotifyEvent = SharedQueryCacheNotifyEvent +export type QueryStore = SharedQueryStore +export type QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +> = SharedQueryObserverResultContext< + DefaultRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +> +export type ObserverOptionsInput< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = SharedObserverOptionsInput< + DefaultRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +> +export type QueryFunction< + T = unknown, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = SharedQueryFunction +export type StaleTimeFunction< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = SharedStaleTimeFunction< + DefaultRuntime, + TQueryFnData, + TError, + TData, + TQueryKey +> +export type QueryBooleanOption< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = SharedQueryBooleanOption< + DefaultRuntime, + TQueryFnData, + TError, + TData, + TQueryKey +> +export type QueryPersister< + T = unknown, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = SharedQueryPersister +export type QueryFunctionContext< + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = SharedQueryFunctionContext +export type PlaceholderDataFunction< + TQueryFnData = unknown, + TError = DefaultError, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = SharedPlaceholderDataFunction< + DefaultRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey +> +export type QueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = SharedQueryOptions< + DefaultRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> +export type ThrowOnError< + TQueryFnData, + TError, + TQueryData, + TQueryKey extends QueryKey, +> = SharedThrowOnError< + DefaultRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey +> +export type QueryObserverOptionsBase< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = SharedQueryObserverOptionsBase< + DefaultRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> +export type QueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = SharedQueryObserverOptions< + DefaultRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> +export type DefaultedQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = SharedDefaultedQueryObserverOptions< + DefaultRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> +export type InfiniteQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = SharedInfiniteQueryObserverOptions< + DefaultRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> +export type DefaultedInfiniteQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = SharedDefaultedInfiniteQueryObserverOptions< + DefaultRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> +export type QueryExecuteOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = SharedQueryExecuteOptions< + DefaultRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> +export type InfiniteQueryExecuteOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = SharedInfiniteQueryExecuteOptions< + DefaultRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> +export type InvalidateQueryFilters = + SharedInvalidateQueryFilters +export type RefetchQueryFilters = + SharedRefetchQueryFilters +export type MutationFunctionContext = + SharedMutationFunctionContext +export type MutationFunction< + TData = unknown, + TVariables = unknown, +> = SharedMutationFunction +export type MutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = SharedMutationOptions< + DefaultRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> +export type MutationObserverOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = SharedMutationObserverOptions< + DefaultRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> +export type MutateOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = SharedMutateOptions< + DefaultRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> +export type MutateFunctionRest< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = SharedMutateFunctionRest< + DefaultRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> +export type MutateFunction< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = SharedMutateFunction< + DefaultRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> +export type MutationObserverBaseResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = SharedMutationObserverBaseResult< + DefaultRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> +export type MutationObserverIdleResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = SharedMutationObserverIdleResult< + DefaultRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> +export type MutationObserverLoadingResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = SharedMutationObserverLoadingResult< + DefaultRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> +export type MutationObserverErrorResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = SharedMutationObserverErrorResult< + DefaultRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> +export type MutationObserverSuccessResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = SharedMutationObserverSuccessResult< + DefaultRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> +export type MutationObserverResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = SharedMutationObserverResult< + DefaultRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> +export type QueryClientConfig = SharedQueryClientConfig +export type DefaultOptions = SharedDefaultOptions< + DefaultRuntime, + TError +> +export type QueryFilters = + SharedQueryFilters +export type MutationFilters< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> = SharedMutationFilters< + DefaultRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> +export type { QueryClient } from './contracts' +export type { QueryCache } from './contracts' +export type { MutationCache } from './contracts' +export type { Query } from './contracts' +export type { Mutation } from './contracts' +export type { QueryObserver } from './contracts' +export type { MutationObserver } from './contracts' diff --git a/packages/query-types/src/infiniteQueryObserver.ts b/packages/query-types/src/infiniteQueryObserver.ts new file mode 100644 index 00000000000..4056817cabd --- /dev/null +++ b/packages/query-types/src/infiniteQueryObserver.ts @@ -0,0 +1,41 @@ +import type { RuntimeBinding } from './binding' +import type { + DefaultedInfiniteQueryObserverOptions, + InfiniteQueryObserverOptions, + InfiniteQueryObserverResult, + QueryKey, +} from './types' + +export type InfiniteQueryObserverListener = ( + result: InfiniteQueryObserverResult, +) => void + +export type InfiniteObserverOptionsInput< + TRuntime extends RuntimeBinding, + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, + TPageParam, +> = + | InfiniteQueryObserverOptions< + TRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + | DefaultedInfiniteQueryObserverOptions< + TRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + +export type ReplaceReturnType< + TFunction extends (...args: Array) => unknown, + TReturn, +> = (...args: Parameters) => TReturn diff --git a/packages/query-types/src/mutation.ts b/packages/query-types/src/mutation.ts new file mode 100644 index 00000000000..bd4bbf1d641 --- /dev/null +++ b/packages/query-types/src/mutation.ts @@ -0,0 +1,110 @@ +import type { MutationCacheOf, QueryClientOf, RuntimeBinding } from './binding' +import type { DefaultError, MutationOptions, MutationStatus } from './types' + +export interface MutationConfig< + TRuntime extends RuntimeBinding, + TData, + TError, + TVariables, + TOnMutateResult, +> { + client: QueryClientOf + mutationId: number + mutationCache: MutationCacheOf + options: MutationOptions + state?: MutationState +} + +/** + * 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 +} + +export interface MutationFailedAction { + type: 'failed' + failureCount: number + error: TError | null +} + +export interface PendingAction { + type: 'pending' + isPaused: boolean + variables?: TVariables + context?: TOnMutateResult +} + +export interface MutationSuccessAction { + type: 'success' + data: TData +} + +export interface MutationErrorAction { + type: 'error' + error: TError +} + +export interface MutationPauseAction { + type: 'pause' +} + +export interface MutationContinueAction { + type: 'continue' +} + +/** + * The actions a mutation dispatches to update its state, e.g. when it starts, fails, pauses, or + * succeeds. + */ +export type MutationAction = + | MutationContinueAction + | MutationErrorAction + | MutationFailedAction + | PendingAction + | MutationPauseAction + | MutationSuccessAction diff --git a/packages/query-types/src/mutationCache.ts b/packages/query-types/src/mutationCache.ts new file mode 100644 index 00000000000..55c9ae9c378 --- /dev/null +++ b/packages/query-types/src/mutationCache.ts @@ -0,0 +1,120 @@ +import type { MutationObserverOf, MutationOf, RuntimeBinding } from './binding' +import type { MutationAction } from './mutation' +import type { + CacheKeyConfig, + DefaultError, + MutationFunctionContext, + MutationKey, + NotifyEvent, +} from './types' + +/** + * 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: MutationOf, + context: MutationFunctionContext, + ) => Promise | unknown + /** Called when any mutation in the cache is successful. */ + onSuccess?: ( + data: unknown, + variables: unknown, + onMutateResult: unknown, + mutation: MutationOf, + context: MutationFunctionContext, + ) => Promise | unknown + /** Called before any mutation in the cache executes. */ + onMutate?: ( + variables: unknown, + mutation: MutationOf, + 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: MutationOf, + context: MutationFunctionContext, + ) => Promise | unknown +} + +export interface NotifyEventMutationAdded< + TRuntime extends RuntimeBinding, +> extends NotifyEvent { + type: 'added' + mutation: MutationOf +} + +export interface NotifyEventMutationRemoved< + TRuntime extends RuntimeBinding, +> extends NotifyEvent { + type: 'removed' + mutation: MutationOf +} + +export interface NotifyEventMutationObserverAdded< + TRuntime extends RuntimeBinding, +> extends NotifyEvent { + type: 'observerAdded' + mutation: MutationOf + observer: MutationObserverOf +} + +export interface NotifyEventMutationObserverRemoved< + TRuntime extends RuntimeBinding, +> extends NotifyEvent { + type: 'observerRemoved' + mutation: MutationOf + observer: MutationObserverOf +} + +export interface NotifyEventMutationObserverOptionsUpdated< + TRuntime extends RuntimeBinding, +> extends NotifyEvent { + type: 'observerOptionsUpdated' + mutation?: MutationOf + observer: MutationObserverOf +} + +export interface NotifyEventMutationUpdated< + TRuntime extends RuntimeBinding, +> extends NotifyEvent { + type: 'updated' + mutation: MutationOf + action: MutationAction +} + +/** + * 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 + +export type MutationCacheListener = ( + event: MutationCacheNotifyEvent, +) => void diff --git a/packages/query-types/src/mutationObserver.ts b/packages/query-types/src/mutationObserver.ts new file mode 100644 index 00000000000..ce96e07d8ec --- /dev/null +++ b/packages/query-types/src/mutationObserver.ts @@ -0,0 +1,18 @@ +import type { RuntimeBinding } from './binding' +import type { MutationObserverResult } from './types' + +export type MutationObserverListener< + TRuntime extends RuntimeBinding, + TData, + TError, + TVariables, + TOnMutateResult, +> = ( + result: MutationObserverResult< + TRuntime, + TData, + TError, + TVariables, + TOnMutateResult + >, +) => void diff --git a/packages/query-types/src/notifyManager.ts b/packages/query-types/src/notifyManager.ts new file mode 100644 index 00000000000..3c729c1bbbd --- /dev/null +++ b/packages/query-types/src/notifyManager.ts @@ -0,0 +1,9 @@ +export type NotifyCallback = () => void + +export type NotifyFunction = (callback: () => void) => void + +export type BatchNotifyFunction = (callback: () => void) => void + +export type BatchCallsCallback> = (...args: T) => void + +export type ScheduleFunction = (callback: () => void) => void diff --git a/packages/query-types/src/onlineManager.ts b/packages/query-types/src/onlineManager.ts new file mode 100644 index 00000000000..fcbd1f1d006 --- /dev/null +++ b/packages/query-types/src/onlineManager.ts @@ -0,0 +1,5 @@ +export type OnlineManagerListener = (online: boolean) => void + +export type OnlineManagerSetupFn = ( + setOnline: OnlineManagerListener, +) => (() => void) | undefined diff --git a/packages/query-types/src/queriesObserver.ts b/packages/query-types/src/queriesObserver.ts new file mode 100644 index 00000000000..74b492a3f2a --- /dev/null +++ b/packages/query-types/src/queriesObserver.ts @@ -0,0 +1,52 @@ +import type { QueryObserverOf, RuntimeBinding } from './binding' +import type { QueryObserverResultReader } from './queryObserver' +import type { + DefaultedQueryObserverOptions, + QueryObserverResult, +} from './types' + +export type QueriesObserverListener = ( + result: Array, +) => void + +export type CombineFn = ( + result: Array, +) => TCombinedResult + +/** A cached reader for multiple query results and their combined value. */ +export interface QueriesObserverResultReader< + TCombinedResult, +> extends QueryObserverResultReader> { + /** Track result properties and combine the results with this reader's options. */ + combineResult: (result: Array) => TCombinedResult +} + +export type CombineContext = { + result?: Array + combine?: CombineFn + value?: TCombinedResult + queryHashes?: Array +} + +/** + * Options for a `QueriesObserver` that apply to all of its queries at once. + */ +export interface QueriesObserverOptions< + TCombinedResult = Array, +> { + /** + * A function that combines the array of `QueryObserverResult`s (one per + * observed query) into a single value. The combined value is memoized and + * only recomputed when one of the underlying results, the query hashes, or + * the `combine` function itself changes. + * + * Defaults to returning the array of `QueryObserverResult`s unchanged. + */ + combine?: CombineFn +} + +export type QueryObserverMatch = { + defaultedQueryOptions: DefaultedQueryObserverOptions + observer: QueryObserverOf + reader?: QueryObserverResultReader +} diff --git a/packages/query-types/src/query.ts b/packages/query-types/src/query.ts new file mode 100644 index 00000000000..4c5041e1593 --- /dev/null +++ b/packages/query-types/src/query.ts @@ -0,0 +1,246 @@ +import type { QueryClientOf, QueryOf, RuntimeBinding } from './binding' +import type { + DefaultError, + FetchStatus, + QueryKey, + QueryOptions, + QueryStatus, +} from './types' + +export interface QueryConfig< + TRuntime extends RuntimeBinding, + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey = QueryKey, +> { + client: QueryClientOf + queryKey: TQueryKey + queryHash: string + options?: QueryOptions + defaultOptions?: QueryOptions< + TRuntime, + TQueryFnData, + TError, + TData, + TQueryKey + > + state?: QueryState +} + +/** + * The raw state stored on a `Query` instance. This is the underlying state + * that observer results (e.g. `QueryObserverResult`) are derived from. + */ +export interface QueryState { + /** + * The last successfully resolved data for the query. + */ + data: TData | undefined + /** + * The number of times the query has successfully resolved. + */ + dataUpdateCount: number + /** + * The timestamp for when the query most recently returned the `status` as `"success"`. + */ + dataUpdatedAt: number + /** + * The error object for the query, if the last attempt resulted in an error. + * - Defaults to `null`. + */ + error: TError | null + /** + * The sum of all errors, incremented every time the query resolves with an error. + */ + errorUpdateCount: number + /** + * The timestamp for when the query most recently returned the `status` as `"error"`. + */ + errorUpdatedAt: number + /** + * The failure count for the current fetch. + * - Incremented every time the fetch fails. + * - Reset to `0` when the fetch succeeds. + */ + fetchFailureCount: number + /** + * The reason the current fetch failed, as reported by the retryer. + * - Reset to `null` when the fetch succeeds. + */ + fetchFailureReason: TError | null + /** + * Metadata passed to the currently in-flight (or most recent) fetch, e.g. the + * `fetchMore` direction for infinite queries. + */ + fetchMeta: FetchMeta | null + /** + * Whether the query has been marked as invalidated via `invalidate()`. + * - Reset to `false` whenever the query resolves successfully. + */ + isInvalidated: boolean + /** + * The status of the query. + * - `pending` if there's no cached data and no attempt was finished yet. + * - `error` if the last attempt resulted in an error. + * - `success` if the query has data. + */ + status: QueryStatus + /** + * The fetch status of the query. + * - `fetching`: the `queryFn` is currently executing. + * - `paused`: a fetch wanted to run but has been paused (see network mode). + * - `idle`: the query is not fetching. + */ + fetchStatus: FetchStatus +} + +/** + * The context passed to a {@link QueryBehavior}'s `onFetch`, which can replace `fetchFn` to change + * how the query fetches (e.g. to fetch pages for an infinite query). + */ +export interface FetchContext< + TRuntime extends RuntimeBinding, + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey = QueryKey, +> { + /** + * The function that runs the fetch. By default it calls `queryFn`; `onFetch` can replace it. + */ + fetchFn: () => unknown | Promise + /** + * The options of this fetch. + */ + fetchOptions?: FetchOptions + /** + * The `AbortSignal` that aborts when the fetch is cancelled. + */ + signal: AbortSignal + /** + * The options of the query. + */ + options: QueryOptions + /** + * The `QueryClient` the query belongs to. + */ + client: QueryClientOf + /** + * The key of the query. + */ + queryKey: TQueryKey + /** + * The state of the query when the fetch starts. + */ + state: QueryState +} + +/** + * Customizes how a query fetches, e.g. the behavior that fetches the pages of an infinite query. + */ +export interface QueryBehavior< + TRuntime extends RuntimeBinding, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> { + /** + * Called before each fetch of the query, e.g. to replace `fetchFn` in the context. + */ + onFetch: ( + context: FetchContext, + query: QueryOf, + ) => void +} + +/** + * The direction an infinite query fetches in: `'forward'` for the next page, `'backward'` for the + * previous one. + */ +export type FetchDirection = 'forward' | 'backward' + +/** + * Metadata for a fetch, e.g. the direction when an infinite query fetches more pages. + */ +export interface FetchMeta { + /** + * Set when an infinite query fetches another page, with the direction to fetch in. + */ + fetchMore?: { direction: FetchDirection } +} + +/** + * Options for a single fetch of a query. + */ +export interface FetchOptions { + /** + * If `true`, an in-flight fetch is cancelled before starting a new one, when the query already + * has data. Otherwise, the in-flight fetch is reused. + */ + cancelRefetch?: boolean + /** + * Metadata of the fetch, stored in the query's `fetchMeta` state. + */ + meta?: FetchMeta + /** + * A promise to use for the first attempt instead of calling `fetchFn`, e.g. a pending promise + * restored by `hydrate`. + */ + initialPromise?: Promise +} + +export interface QueryFailedAction { + type: 'failed' + failureCount: number + error: TError +} + +export interface FetchAction { + type: 'fetch' + meta?: FetchMeta +} + +export interface QuerySuccessAction { + data: TData | undefined + type: 'success' + dataUpdatedAt?: number + manual?: boolean +} + +export interface QueryErrorAction { + type: 'error' + error: TError +} + +export interface InvalidateAction { + type: 'invalidate' +} + +export interface QueryPauseAction { + type: 'pause' +} + +export interface QueryContinueAction { + type: 'continue' +} + +export interface SetStateAction { + type: 'setState' + state: Partial> +} + +/** + * The actions a query dispatches to update its state, e.g. when it starts fetching, fails, or + * succeeds. + */ +export type QueryAction = + | QueryContinueAction + | QueryErrorAction + | QueryFailedAction + | FetchAction + | InvalidateAction + | QueryPauseAction + | SetStateAction + | QuerySuccessAction diff --git a/packages/query-types/src/queryCache.ts b/packages/query-types/src/queryCache.ts new file mode 100644 index 00000000000..cd75c838741 --- /dev/null +++ b/packages/query-types/src/queryCache.ts @@ -0,0 +1,136 @@ +import type { QueryObserverOf, QueryOf, RuntimeBinding } from './binding' +import type { QueryAction } from './query' +import type { + CacheKeyConfig, + DefaultError, + NotifyEvent, + QueryKey, +} from './types' + +/** + * Global callbacks that fire for every query handled by a `QueryCache`, regardless of which + * component or observer triggered it. Unlike `QueryClient`'s `defaultOptions`, which a query can + * override, these callbacks are always called. Unlike `MutationCacheConfig`'s callbacks, these + * are fire-and-forget: their return value is not awaited before the query settles. + */ +export interface QueryCacheConfig { + /** + * Configures query key comparison and hashing globally. + * `equalityFn` compares individual values during partial matching and defaults to strict equality. + * `hashFn` hashes query keys and defaults to `hashKey`. + */ + queryKey?: CacheKeyConfig + /** Called when any query in the cache encounters an error. */ + onError?: ( + error: DefaultError, + query: QueryOf, + ) => void + /** Called when any query in the cache is successful. */ + onSuccess?: ( + data: unknown, + query: QueryOf, + ) => void + /** Called when any query in the cache is settled, either successfully or with an error. */ + onSettled?: ( + data: unknown | undefined, + error: DefaultError | null, + query: QueryOf, + ) => void +} + +export interface NotifyEventQueryAdded< + TRuntime extends RuntimeBinding, +> extends NotifyEvent { + type: 'added' + query: QueryOf +} + +export interface NotifyEventQueryRemoved< + TRuntime extends RuntimeBinding, +> extends NotifyEvent { + type: 'removed' + query: QueryOf +} + +export interface NotifyEventQueryUpdated< + TRuntime extends RuntimeBinding, +> extends NotifyEvent { + type: 'updated' + query: QueryOf + action: QueryAction +} + +export interface NotifyEventQueryObserverAdded< + TRuntime extends RuntimeBinding, +> extends NotifyEvent { + type: 'observerAdded' + query: QueryOf + observer: QueryObserverOf +} + +export interface NotifyEventQueryObserverRemoved< + TRuntime extends RuntimeBinding, +> extends NotifyEvent { + type: 'observerRemoved' + query: QueryOf + observer: QueryObserverOf +} + +export interface NotifyEventQueryObserverResultsUpdated< + TRuntime extends RuntimeBinding, +> extends NotifyEvent { + type: 'observerResultsUpdated' + query: QueryOf +} + +export interface NotifyEventQueryObserverOptionsUpdated< + TRuntime extends RuntimeBinding, +> extends NotifyEvent { + type: 'observerOptionsUpdated' + query: QueryOf + observer: QueryObserverOf +} + +/** + * The event passed to a `QueryCache` subscriber. Fired whenever a query is added or removed from + * the cache, its state is updated (e.g. via `query.setState` or `queryClient.removeQueries`), or + * one of its observers is added, removed, or has its results or options updated. + */ +export type QueryCacheNotifyEvent = + | NotifyEventQueryAdded + | NotifyEventQueryRemoved + | NotifyEventQueryUpdated + | NotifyEventQueryObserverAdded + | NotifyEventQueryObserverRemoved + | NotifyEventQueryObserverResultsUpdated + | NotifyEventQueryObserverOptionsUpdated + +export type QueryCacheListener = ( + event: QueryCacheNotifyEvent, +) => void + +/** + * The store a `QueryCache` keeps its queries in, keyed by query hash. + */ +export interface QueryStore { + /** + * Returns whether a query with the given hash is stored. + */ + has: (queryHash: string) => boolean + /** + * Stores a query under its hash. + */ + set: (queryHash: string, query: QueryOf) => void + /** + * Returns the query with the given hash, if any. + */ + get: (queryHash: string) => QueryOf | undefined + /** + * Removes the query with the given hash. + */ + delete: (queryHash: string) => void + /** + * Returns an iterator over all stored queries. + */ + values: () => IterableIterator> +} diff --git a/packages/query-types/src/queryClient.ts b/packages/query-types/src/queryClient.ts new file mode 100644 index 00000000000..8ee82603d31 --- /dev/null +++ b/packages/query-types/src/queryClient.ts @@ -0,0 +1,26 @@ +import type { RuntimeBinding } from './binding' +import type { skipToken } from './symbols' +import type { + MutationKey, + MutationOptions, + OmitKeyof, + QueryKey, + QueryOptions, +} from './types' + +export type WithoutSkipToken = Omit< + T, + 'queryFn' +> & { + queryFn?: Exclude +} + +export interface QueryDefaults { + queryKey: QueryKey + defaultOptions: OmitKeyof, 'queryKey'> +} + +export interface MutationDefaults { + mutationKey: MutationKey + defaultOptions: MutationOptions +} diff --git a/packages/query-types/src/queryObserver.ts b/packages/query-types/src/queryObserver.ts new file mode 100644 index 00000000000..3981a974abc --- /dev/null +++ b/packages/query-types/src/queryObserver.ts @@ -0,0 +1,124 @@ +import type { QueryOf, RuntimeBinding } from './binding' +import type { FetchOptions, QueryState } from './query' +import type { + DefaultError, + DefaultedQueryObserverOptions, + QueryKey, + QueryObserverOptions, + QueryObserverResult, + QueryOptions, +} from './types' + +export type QueryObserverListener = ( + result: QueryObserverResult, +) => void + +export interface ObserverFetchOptions extends FetchOptions { + throwOnError?: boolean +} + +/** A cached view of an observer for one set of render options. */ +export interface QueryObserverResultReader { + /** Read the result, retaining its reference while all fields are unchanged. */ + getSnapshot: () => TResult + /** Apply this reader's options and reusable computation state after commit. */ + commit: () => void +} + +export type ProjectionFailure = { + error: TError + errorUpdatedAt: number +} + +/** + * Selection and placeholder computation state shared by reads of the same result. + * @internal + */ +export interface QueryObserverResultContext< + TRuntime extends RuntimeBinding, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +> { + /** The memo key and failure of the most recent selection. */ + selection?: { + key: { + input: TQueryData + select: (data: TQueryData) => TData + structuralSharing: QueryOptions< + TRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey + >['structuralSharing'] + } + failure?: ProjectionFailure + } + /** The last successful selection, used if selection fails. */ + selected?: { + data: TData + query?: QueryOf + } + /** The unselected placeholder or factory error. */ + placeholder?: { + key: { + placeholderData: QueryObserverOptions< + TRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >['placeholderData'] + structuralSharing: QueryOptions< + TRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey + >['structuralSharing'] + previousQuery: + | QueryOf + | undefined + previousState: QueryState | undefined + previousOptions: + | QueryOptions + | undefined + } + sourceQuery?: QueryOf + input: TQueryData | undefined + failure?: ProjectionFailure + } +} + +/** + * Options supplied to an observer by a caller or already resolved by the client. + * @internal + */ +export type ObserverOptionsInput< + TRuntime extends RuntimeBinding, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = + | QueryObserverOptions< + TRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + > + | DefaultedQueryObserverOptions< + TRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + > diff --git a/packages/query-types/src/retryer.ts b/packages/query-types/src/retryer.ts new file mode 100644 index 00000000000..5060ff9902b --- /dev/null +++ b/packages/query-types/src/retryer.ts @@ -0,0 +1,74 @@ +import type { CancelOptions, DefaultError, NetworkMode } from './types' + +export interface RetryerConfig { + fn: () => TData | Promise + initialPromise?: Promise + onCancel?: (error: TError) => void + onFail?: (failureCount: number, error: TError) => void + onPause?: () => void + onContinue?: () => void + retry?: RetryValue + retryDelay?: RetryDelayValue + networkMode: NetworkMode | undefined + canRun: () => boolean +} + +/** + * Runs a function with retries, and can pause, continue, or cancel it. Queries and mutations use + * one for each fetch or execution. + */ +export interface Retryer { + /** + * The promise that resolves with the data, or rejects once retries are exhausted or it is + * cancelled. + */ + promise: Promise + /** + * Cancels the run, rejecting `promise` with a `CancelledError`. + */ + cancel: (cancelOptions?: CancelOptions) => void + /** + * Resumes a paused run, and returns `promise`. + */ + continue: () => Promise + /** + * Stops further retries. The current attempt still finishes. + */ + cancelRetry: () => void + /** + * Allows retries again after `cancelRetry`. + */ + continueRetry: () => void + /** + * Returns whether the run can start now, based on the network mode and `canRun`. + */ + canStart: () => boolean + /** + * Starts the run, or waits until it can start, and returns `promise`. + */ + start: () => Promise + /** + * Returns whether `promise` is still pending, resolved, or rejected. + */ + status: () => 'pending' | 'resolved' | 'rejected' +} + +export type RetryerStatus = 'pending' | 'resolved' | 'rejected' + +/** @inline */ +export type RetryValue = boolean | number | ShouldRetryFunction + +/** @inline */ +export type ShouldRetryFunction = ( + failureCount: number, + error: TError, +) => boolean + +/** @inline */ +export type RetryDelayValue = number | RetryDelayFunction + +/** @inline */ +export type RetryDelayFunction = ( + failureCount: number, + error: TError, +) => number diff --git a/packages/query-types/src/streamedQuery.ts b/packages/query-types/src/streamedQuery.ts new file mode 100644 index 00000000000..b3d799df924 --- /dev/null +++ b/packages/query-types/src/streamedQuery.ts @@ -0,0 +1,55 @@ +import type { RuntimeBinding } from './binding' +import type { QueryFunctionContext, QueryKey } from './types' + +export type BaseStreamedQueryParams< + TRuntime extends RuntimeBinding, + TQueryFnData, + TQueryKey extends QueryKey, +> = { + /** Returns an `AsyncIterable` or a promise that resolves to one. */ + streamFn: ( + context: QueryFunctionContext, + ) => AsyncIterable | Promise> + /** + * Defines how refetches are handled. + * - `'reset'` (default): resets the query to its initial state before reading the stream. + * - `'append'`: appends new data to the existing data. + * - `'replace'`: writes all data to the cache once the stream ends. + */ + refetchMode?: 'append' | 'reset' | 'replace' +} + +export type SimpleStreamedQueryParams< + TRuntime extends RuntimeBinding, + TQueryFnData, + TQueryKey extends QueryKey, +> = BaseStreamedQueryParams & { + reducer?: never + initialValue?: never +} + +export type ReducibleStreamedQueryParams< + TRuntime extends RuntimeBinding, + TQueryFnData, + TData, + TQueryKey extends QueryKey, +> = BaseStreamedQueryParams & { + /** + * Combines the accumulated data with the next chunk. Provide `initialValue` with a custom reducer. + */ + reducer: (acc: TData, chunk: TQueryFnData) => TData + /** + * The starting value for the reducer when there is no cached data or when + * `refetchMode` is `'replace'` during a refetch. + */ + initialValue: TData +} + +export type StreamedQueryParams< + TRuntime extends RuntimeBinding, + TQueryFnData, + TData, + TQueryKey extends QueryKey, +> = + | SimpleStreamedQueryParams + | ReducibleStreamedQueryParams diff --git a/packages/query-types/src/symbols.ts b/packages/query-types/src/symbols.ts new file mode 100644 index 00000000000..290b51bdc7c --- /dev/null +++ b/packages/query-types/src/symbols.ts @@ -0,0 +1,26 @@ +declare const dataTagSymbol: unique symbol +type dataTagSymbol = typeof dataTagSymbol + +declare const dataTagErrorSymbol: unique symbol +type dataTagErrorSymbol = typeof dataTagErrorSymbol + +declare const unsetMarker: unique symbol +type unsetMarker = typeof unsetMarker + +declare const skipToken: unique symbol +type skipToken = typeof skipToken + +declare const defaultQueryFn: unique symbol +type defaultQueryFn = typeof defaultQueryFn + +declare const fetchSignal: unique symbol +type fetchSignal = typeof fetchSignal + +export type { + dataTagSymbol, + dataTagErrorSymbol, + unsetMarker, + skipToken, + defaultQueryFn, + fetchSignal, +} diff --git a/packages/query-types/src/timeoutManager.ts b/packages/query-types/src/timeoutManager.ts new file mode 100644 index 00000000000..24eb5fed13d --- /dev/null +++ b/packages/query-types/src/timeoutManager.ts @@ -0,0 +1,49 @@ +/** + * {@link TimeoutManager} does not support passing arguments to the callback. + * + * `(_: void)` is the argument type inferred by TypeScript's default typings for + * `setTimeout(cb, number)`. + * If we don't accept a single void argument, then + * `new Promise(resolve => timeoutManager.setTimeout(resolve, N))` is a type error. + */ +export type TimeoutCallback = (_: void) => void + +/** + * Wrapping `setTimeout` is awkward from a typing perspective because platform + * typings may extend the return type of `setTimeout`. For example, NodeJS + * typings add `NodeJS.Timeout`; but a non-default `timeoutManager` may not be + * able to return such a type. + */ +export type ManagedTimerId = number | { [Symbol.toPrimitive]: () => number } + +/** + * Backend for timer functions. + * + * Timers are performance-sensitive: short-lived timers (delays under a few seconds) tend to be + * latency-sensitive, while long-lived ones may benefit more from coalescing — batching timers + * with similar deadlines together — which the default provider (backed by the platform's global + * `setTimeout`/`setInterval`) does not do. A custom provider can implement coalescing, and can + * also support delays longer than the ~24-day maximum of the global `setTimeout`. + */ +export type TimeoutProvider = + { + /** + * Schedules `callback` to run once after `delay` milliseconds, like the global `setTimeout`. + */ + readonly setTimeout: (callback: TimeoutCallback, delay: number) => TTimerId + /** + * Cancels a timeout scheduled with `setTimeout`. + */ + readonly clearTimeout: (timeoutId: TTimerId | undefined) => void + + /** + * Schedules `callback` to run every `delay` milliseconds, like the global `setInterval`. + */ + readonly setInterval: (callback: TimeoutCallback, delay: number) => TTimerId + /** + * Cancels an interval scheduled with `setInterval`. + */ + readonly clearInterval: (intervalId: TTimerId | undefined) => void + } + +export type SystemTimerId = ReturnType diff --git a/packages/query-types/src/types.ts b/packages/query-types/src/types.ts new file mode 100644 index 00000000000..1f1ff068988 --- /dev/null +++ b/packages/query-types/src/types.ts @@ -0,0 +1,2552 @@ +import type { + MutationCacheOf, + QueryCacheOf, + QueryClientOf, + QueryOf, + RuntimeBinding, +} from './binding' +import type { DehydrateOptions, HydrateOptions } from './hydration' +import type { MutationState } from './mutation' +import type { RetryDelayValue, RetryValue } from './retryer' +import type { + dataTagErrorSymbol, + dataTagSymbol, + unsetMarker as UnsetMarker, +} from './symbols' +import type { + DefaultQueryFn, + QueryFilters, + QueryTypeFilter, + SkipToken, +} from './utils' + +/** + * Excludes `undefined` from `T`. Used where a value must be defined, such as the data type that a + * defined `initialData` resolves to. + */ +export type NonUndefinedGuard = T extends undefined ? never : T + +/** + * Like `Omit`, but applied to each member of a union separately, so each member keeps its own keys. + */ +export type DistributiveOmit< + TObject, + TKey extends keyof TObject, +> = TObject extends any ? Omit : never + +/** + * Like `Omit`, but by default (`'strictly'`) `TKey` must be a key of `TObject`, so omitting a key + * that doesn't exist is a type error. Pass `'safely'` to allow other keys too. + */ +export type OmitKeyof< + TObject, + TKey extends (TStrictly extends 'safely' + ? | keyof TObject + | (string & Record) + | (number & Record) + | (symbol & Record) + : keyof TObject), + TStrictly extends 'strictly' | 'safely' = 'strictly', +> = Omit + +/** + * Replaces the types of the properties of `TTargetA` that also exist in `TTargetB` with their types + * in `TTargetB`. Properties that only exist in `TTargetB` are not added. + */ +export type Override = { + [AKey in keyof TTargetA]: AKey extends keyof TTargetB + ? TTargetB[AKey] + : TTargetA[AKey] +} + +/** + * The interface to augment via declaration merging to override Query's default types repository-wide. + * Each field it declares replaces the default of the matching type: `defaultError` for {@link DefaultError}, + * `queryKey` for {@link QueryKey}, `mutationKey` for {@link MutationKey}, `queryMeta` for {@link QueryMeta} and + * `mutationMeta` for {@link MutationMeta}. Leave a field out to keep that type's default. + * Augment the module you install — `@tanstack/react-query`, `@tanstack/vue-query`, + * `@tanstack/solid-query`, `@tanstack/svelte-query`, `@tanstack/preact-query`, + * `@tanstack/angular-query` or `@tanstack/lit-query`. Augmenting `@tanstack/query-core` + * works too and covers every adapter at once. + * @example + * ```ts + * // Use the module you installed — here, the React adapter. + * declare module '@tanstack/react-query' { + * interface Register { + * defaultError: AxiosError + * } + * } + * ``` + */ +export interface Register { + // defaultError: Error + // queryMeta: Record + // mutationMeta: Record + // queryKey: ReadonlyArray + // mutationKey: ReadonlyArray +} + +/** + * The error type used wherever an error is not given an explicit type parameter. + * Defaults to `Error`; declare `defaultError` on {@link Register} to change it everywhere at once. + */ +export type DefaultError = Register extends { + defaultError: infer TError +} + ? TError + : Error + +/** + * The type of a query key — the serializable array that identifies a query in the cache. + * Defaults to `ReadonlyArray`; declare `queryKey` on {@link Register} to narrow it repository-wide. + */ +export type QueryKey = Register extends { + queryKey: infer TQueryKey +} + ? TQueryKey extends ReadonlyArray + ? TQueryKey + : TQueryKey extends Array + ? TQueryKey + : ReadonlyArray + : ReadonlyArray + +export type { dataTagSymbol } from './symbols' + +export type { dataTagErrorSymbol } from './symbols' + +export type { unsetMarker as UnsetMarker } from './symbols' + +/** + * Matches any type that has been tagged with {@link DataTag}, whatever its data and error types. + */ +export type AnyDataTag = { + /** + * The data type the key was tagged with. + */ + [dataTagSymbol]: any + /** + * The error type the key was tagged with. + */ + [dataTagErrorSymbol]: any +} + +/** + * Tags `TType` (usually a query key) with a data type and an optional error type, so that APIs that + * receive it, like `queryClient.getQueryData`, can infer them. A type that is already tagged is + * returned as is. + */ +export type DataTag< + TType, + TValue, + TError = UnsetMarker, +> = TType extends AnyDataTag + ? TType + : TType & { + [dataTagSymbol]: TValue + [dataTagErrorSymbol]: TError + } + +/** + * An object whose `queryKey` is tagged with {@link DataTag}, like the options returned by + * `queryOptions`. + */ +export type QueryKeyWithDataTag< + TQueryKey extends QueryKey = QueryKey, + TQueryFnData = unknown, + TError = DefaultError, +> = { + /** + * The query key, tagged with the query's data and error types. + */ + queryKey: DataTag +} + +/** + * The data type tagged on a query key by {@link DataTag}, or `TQueryFnData` if the key is not + * tagged. + */ +export type InferDataFromTag = + TTaggedQueryKey extends DataTag + ? TaggedValue + : TQueryFnData + +/** + * The error type tagged on a query key by {@link DataTag}, or `TError` if the key is not tagged or + * was tagged without an error type. + */ +export type InferErrorFromTag = + TTaggedQueryKey extends DataTag + ? TaggedError extends UnsetMarker + ? TError + : TaggedError + : TError + +/** @inline */ +export type QueryFunction< + TRuntime extends RuntimeBinding, + T = unknown, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = ( + context: QueryFunctionContext, +) => T | Promise + +/** @inline */ +export type StaleTime = number | 'static' + +/** @inline */ +export type StaleTimeFunction< + TRuntime extends RuntimeBinding, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = + | StaleTime + | (( + query: QueryOf, + ) => StaleTime) + +/** @inline */ +export type QueryBooleanOption< + TRuntime extends RuntimeBinding, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = + | boolean + | (( + query: QueryOf, + ) => boolean) + +/** @inline */ +export type QueryPersister< + TRuntime extends RuntimeBinding, + T = unknown, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = [TPageParam] extends [never] + ? ( + queryFn: QueryFunction, + context: QueryFunctionContext, + query: QueryOf, + ) => T | Promise + : ( + queryFn: QueryFunction, + context: QueryFunctionContext, + query: QueryOf, + ) => T | Promise + +/** + * The object passed to `queryFn`: the `QueryClient`, the `queryKey`, an `AbortSignal` that aborts + * when the query is cancelled, the query's `meta`, and for infinite queries the `pageParam` of the + * page being fetched. + */ +export type QueryFunctionContext< + TRuntime extends RuntimeBinding, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = [TPageParam] extends [never] + ? { + client: QueryClientOf + queryKey: TQueryKey + signal: AbortSignal + meta: QueryMeta | undefined + pageParam?: unknown + } + : { + client: QueryClientOf + queryKey: TQueryKey + signal: AbortSignal + pageParam: TPageParam + meta: QueryMeta | undefined + } + +/** @inline */ +export type InitialDataFunction = () => T | undefined + +export type NonFunctionGuard = T extends Function ? never : T + +/** @inline */ +export type PlaceholderDataFunction< + TRuntime extends RuntimeBinding, + TQueryFnData = unknown, + TError = DefaultError, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = ( + previousData: TQueryData | undefined, + previousQuery: + | QueryOf + | undefined, +) => TQueryData | undefined + +/** + * The `placeholderData` function of a query in `useQueries` and its counterparts. Unlike + * {@link PlaceholderDataFunction}, it receives no previous data or query, because the number of + * queries can differ between renders. + */ +export type QueriesPlaceholderDataFunction = ( + previousData: undefined, + previousQuery: undefined, +) => TQueryData | undefined + +/** @inline */ +export type EqualityFn = (a: unknown, b: unknown) => boolean + +/** @inline */ +export type CacheKeyHashFunction< + TCacheKey extends ReadonlyArray = ReadonlyArray, +> = (cacheKey: TCacheKey) => string + +/** Configures the comparison and hashing of query or mutation keys for a cache. */ +export interface CacheKeyConfig< + TCacheKey extends ReadonlyArray = ReadonlyArray, +> { + /** + * Function used to compare values while partially matching keys. + * Defaults to strict equality. + */ + equalityFn?: EqualityFn + /** + * Function used to hash keys globally. + */ + hashFn?: CacheKeyHashFunction +} + +/** @inline */ +export type GetPreviousPageParamFunction = ( + firstPage: TQueryFnData, + allPages: Array, + firstPageParam: TPageParam, + allPageParams: Array, +) => TPageParam | undefined | null + +/** @inline */ +export type GetNextPageParamFunction = ( + lastPage: TQueryFnData, + allPages: Array, + lastPageParam: TPageParam, + allPageParams: Array, +) => TPageParam | undefined | null + +/** + * The data shape of an infinite query: every page fetched so far, plus the page param each one was fetched with. + * `pages` and `pageParams` are index-aligned — `pageParams[i]` is the param that produced `pages[i]`. + */ +export interface InfiniteData { + /** + * The data of every page fetched so far, in order. + */ + pages: Array + /** + * The page param each page was fetched with, aligned by index with `pages`. + */ + pageParams: Array +} + +/** + * The type of the `meta` object that can be attached to a query and read back from `queryFn`, callbacks and + * cache-level handlers. Defaults to `Record`; declare `queryMeta` on {@link Register} to narrow it. + */ +export type QueryMeta = Register extends { + queryMeta: infer TQueryMeta +} + ? TQueryMeta extends Record + ? TQueryMeta + : Record + : Record + +/** @inline */ +export type NetworkMode = 'online' | 'always' | 'offlineFirst' + +/** @inline */ +export type NotifyOnChangeProps = 'all' | 'none' + +/** + * The options of a query itself — its `queryKey`, `queryFn`, retries, `gcTime`, `initialData`, + * `meta`, and so on — shared by observers and the `QueryClient` methods that fetch queries. + */ +export interface QueryOptions< + TRuntime extends RuntimeBinding, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> { + /** + * If `false`, failed queries will not retry by default. + * If `true`, failed queries will retry infinitely. + * If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. + * If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. + * + * Defaults to `3` on the client and `0` on the server. + */ + retry?: RetryValue + /** + * The delay in milliseconds before a retry. Use a number for a fixed delay or a function that receives + * the failure count and error and returns the delay. The count starts at 0 for the first retry. + * + * A function like `attempt => Math.min(1000 * 2 ** attempt, 30000)` applies exponential + * backoff. + * + * A function like `attempt => attempt * 1000` applies linear backoff. + * + * By default, each retry waits a random duration from 80% to 100% of the base delay. + * The base delay starts at 1 second and doubles for each retry, up to 30 seconds. + */ + retryDelay?: RetryDelayValue + /** + * Controls whether a query is allowed to run based on the current network connectivity. + * @defaultValue 'online' + * @see [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. + */ + networkMode?: NetworkMode + /** + * The time in milliseconds that unused/inactive cache data remains in memory. + * When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. + * When different garbage collection times are specified, the longest one will be used. + * Setting it to `Infinity` will disable garbage collection. + * + * Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. + * + * Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see + * `timeoutManager.setTimeoutProvider` for a workaround. + */ + gcTime?: number + /** + * The function that the query will use to request data. + * Pass `defaultQueryFn` to use the function configured in the client's query defaults. + * Pass `skipToken` to disable a query without a function where supported. + * Receives a {@link QueryFunctionContext}. + * Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. + */ + queryFn?: + | QueryFunction + | SkipToken + | DefaultQueryFn + /** + * This option can be used to persist the result of a query to an external storage, bypassing the need to actually + * call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. + */ + persister?: QueryPersister< + TRuntime, + TQueryFnData, + NoInfer, + TPageParam + > + /** + * The cache key. If omitted, the query cache computes it from `queryKey` + * using its configured `hashFn` or the default hash function. + */ + queryHash?: string + /** + * The query key to use for this query. + * + * The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) + * for more information. + * + * The query will automatically update when this key changes (as long as `enabled` is not set to `false`). + */ + queryKey?: TQueryKey + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). + * If set to a function, the function will be called **once** during the shared/root query initialization, and be + * expected to synchronously return the initial data. + * Initial data is considered stale by default unless a `staleTime` has been set. + * `initialData` **is persisted** to the cache. + */ + initialData?: TData | InitialDataFunction + /** + * If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. + */ + initialDataUpdatedAt?: number | (() => number | undefined) + /** + * Set this to `false` to disable structural sharing between query results. + * Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. + * @defaultValue true + */ + structuralSharing?: + | boolean + | ((oldData: unknown | undefined, newData: unknown) => unknown) + /** @internal */ + _defaulted?: boolean + /** @internal */ + _type?: 'infinite' + /** + * Additional payload to be stored on each query. + * Use this property to pass information that can be used in other places. + */ + meta?: QueryMeta + /** + * Maximum number of pages to store in the data of an infinite query. + */ + maxPages?: number +} + +/** + * Holds the `initialPageParam` option that every infinite query requires. + */ +export interface InitialPageParam { + /** + * The page param to start from when an infinite query has no pages yet. + * It is passed to `queryFn` as `pageParam` for the first page; every page after that gets the + * value returned by `getNextPageParam` or `getPreviousPageParam`. + * It only applies while the query has no pages: once a first page exists, refetching starts from + * that page's own param instead. + */ + initialPageParam: TPageParam +} + +/** + * The page param options of an infinite query: `initialPageParam`, and the `getNextPageParam` and + * `getPreviousPageParam` functions that compute the params of the pages around it. + */ +export interface InfiniteQueryPageParamsOptions< + TQueryFnData = unknown, + TPageParam = unknown, +> extends InitialPageParam { + /** + * This function can be set to automatically get the previous cursor for infinite queries. + * The result will also be used to determine the value of `hasPreviousPage`. + */ + getPreviousPageParam?: GetPreviousPageParamFunction + /** + * This function can be set to automatically get the next cursor for infinite queries. + * The result will also be used to determine the value of `hasNextPage`. + */ + getNextPageParam: GetNextPageParamFunction +} + +/** @inline */ +export type ThrowOnError< + TRuntime extends RuntimeBinding, + TQueryFnData, + TError, + TQueryData, + TQueryKey extends QueryKey, +> = + | boolean + | (( + error: TError, + query: QueryOf, + ) => boolean) + +/** + * Shared options for default resolution and resolved observer state. + * @internal + */ +export interface QueryObserverOptionsBase< + TRuntime extends RuntimeBinding, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> extends WithRequired< + QueryOptions< + TRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey, + TPageParam + >, + 'queryKey' +> { + /** + * Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. + * To refetch the query, use the `refetch` method returned from the `useQuery` instance. + * Accepts a boolean or function that returns a boolean. + * @defaultValue true + */ + enabled?: QueryBooleanOption< + TRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey + > + /** + * The time in milliseconds after data is considered stale. + * If set to `Infinity`, the data will never be considered stale. + * If set to `'static'`, the data will never be considered stale. + * If set to a function, the function will be executed with the query to compute a `staleTime`. + * @defaultValue 0 + */ + staleTime?: StaleTimeFunction< + TRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey + > + /** + * If set to a number, the query will continuously refetch at this frequency in milliseconds. + * If set to a function, the function will be executed with the latest data and query to compute a frequency + * @defaultValue false + */ + refetchInterval?: + | number + | false + | (( + query: QueryOf, + ) => number | false | undefined) + /** + * If set to `true`, the query will continue to refetch while their tab/window is in the background. + * @defaultValue false + */ + refetchIntervalInBackground?: boolean + /** + * If set to `true`, the query will refetch on window focus if the data is stale. + * If set to `false`, the query will not refetch on window focus. + * If set to `'always'`, the query will always refetch on window focus (except when `staleTime: 'static'` is used). + * If set to a function, the function will be executed with the latest data and query to compute the value. + * @defaultValue true + */ + refetchOnWindowFocus?: + | boolean + | 'always' + | (( + query: QueryOf, + ) => boolean | 'always') + /** + * If set to `true`, the query will refetch on reconnect if the data is stale. + * If set to `false`, the query will not refetch on reconnect. + * If set to `'always'`, the query will always refetch on reconnect (except when `staleTime: 'static'` is used). + * If set to a function, the function will be executed with the latest data and query to compute the value. + * + * Defaults to `true` unless `networkMode` is `'always'`. + */ + refetchOnReconnect?: + | boolean + | 'always' + | (( + query: QueryOf, + ) => boolean | 'always') + /** + * If set to `true`, the query will refetch on mount if the data is stale. + * If set to `false`, will disable additional instances of a query to trigger background refetch. + * If set to `'always'`, the query will always refetch on mount (except when `staleTime: 'static'` is used). + * If set to a function, the function will be executed with the latest data and query to compute the value + * @defaultValue true + */ + refetchOnMount?: + | boolean + | 'always' + | (( + query: QueryOf, + ) => boolean | 'always') + /** + * If set to `false`, the query will not be retried on mount if it contains an error. + * If set to a function, the function will be executed with the query to compute the value. + * @defaultValue true + */ + retryOnMount?: QueryBooleanOption< + TRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey + > + /** + * Controls when changes to the query result notify this observer's listeners. + * Use `'all'` to notify on every result change. + * Use `'none'` to suppress notifications while the query remains subscribed and can fetch. + * If `throwOnError` is set, changes to `error` still notify listeners. + * + * By default, adapters that track property reads notify listeners when a tracked property changes. + * If no properties are tracked, every result change notifies listeners. + */ + notifyOnChangeProps?: NotifyOnChangeProps + /** + * Whether errors should be thrown instead of setting the `error` property. + * If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. + * If set to `false` and `suspense` is `false`, errors are returned as state. + * If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`). + * @defaultValue false + */ + throwOnError?: ThrowOnError< + TRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey + > + /** + * This option can be used to transform or select a part of the data returned by the query function. It affects + * the returned `data` value, but does not affect what gets stored in the query cache. + * The `select` function will only run if `data` changed, or if the reference to the `select` function itself + * changes. To optimize, memoize the function so its reference stays stable across calls. + * If the selector throws, the observer reports the error and can keep the last valid selection. + */ + select?: (data: TQueryData) => TData + /** + * If set to `true`, the query will suspend when `status === 'pending'` + * and throw errors when `status === 'error'`. + * @defaultValue false + */ + suspense?: boolean + /** + * If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. + * If the placeholder function throws, the observer reports the error with no data. The query state in the cache is unaffected. + */ + placeholderData?: + | NonFunctionGuard + | PlaceholderDataFunction< + TRuntime, + NonFunctionGuard, + TError, + NonFunctionGuard, + TQueryKey + > + + /** @internal */ + _optimisticResults?: 'optimistic' | 'isRestoring' +} + +/** + * The options of a `QueryObserver`, and of the hooks built on it like `useQuery`: the + * {@link QueryOptions} of the query, plus options that control the observer, such as `enabled`, + * `staleTime`, `refetchInterval`, `select`, and `placeholderData`. + * Pass a `queryFn` or use `defaultQueryFn` to select the client defaults. + */ +export interface QueryObserverOptions< + TRuntime extends RuntimeBinding, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> extends WithRequired< + QueryObserverOptionsBase< + TRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + 'queryFn' +> {} + +/** + * Makes the `TKey` properties of `TTarget` required and non-nullable. + */ +export type WithRequired = TTarget & { + [_ in TKey]: {} +} + +/** + * The {@link QueryObserverOptions} after `QueryClient#defaultQueryOptions` has applied the + * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. + */ +export type DefaultedQueryObserverOptions< + TRuntime extends RuntimeBinding, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = WithRequired< + QueryObserverOptionsBase< + TRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + 'throwOnError' | 'refetchOnReconnect' | 'queryHash' +> + +/** + * The options of an `InfiniteQueryObserver`: {@link QueryObserverOptions} whose query data is + * {@link InfiniteData}, plus the page param options. + */ +export interface InfiniteQueryObserverOptions< + TRuntime extends RuntimeBinding, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> + extends + QueryObserverOptions< + TRuntime, + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey, + TPageParam + >, + InfiniteQueryPageParamsOptions {} + +/** + * The {@link InfiniteQueryObserverOptions} after `QueryClient#defaultQueryOptions` has applied the + * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. + */ +export type DefaultedInfiniteQueryObserverOptions< + TRuntime extends RuntimeBinding, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = DefaultedQueryObserverOptions< + TRuntime, + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey, + TPageParam +> & + InfiniteQueryPageParamsOptions + +/** + * The options of `queryClient.query`: the {@link QueryOptions} of the query, plus a `staleTime` + * that decides whether cached data is returned instead of fetching, and a `select` that only + * transforms the value the call resolves with. + */ +export interface QueryExecuteOptions< + TRuntime extends RuntimeBinding, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> extends WithRequired< + QueryOptions< + TRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey, + TPageParam + >, + 'queryKey' +> { + /** + * Not allowed here, since `initialPageParam` only applies to infinite queries. + */ + initialPageParam?: never + /** + * This option can be used to transform or select a part of the data returned by the query function. It affects + * the value this call resolves with, but does not affect what gets stored in the query cache. + */ + select?: (data: TQueryData) => TData + /** + * The time in milliseconds after data is considered stale. + * If the data is fresh it will be returned from the cache. + */ + staleTime?: StaleTimeFunction< + TRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey + > +} + +export type InfiniteQueryFetchPageOptions = Pick< + InfiniteQueryPageParamsOptions, + 'initialPageParam' | 'getNextPageParam' +> & { + /** + * The number of pages to fetch. Defaults to the number of cached pages, + * or one page if the cache has no pages. + */ + pages?: number +} + +/** + * The options of `queryClient.infiniteQuery`. Extends {@link QueryExecuteOptions} + * with `initialPageParam`, `getNextPageParam`, and the optional `pages` count. + */ +export type InfiniteQueryExecuteOptions< + TRuntime extends RuntimeBinding, + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = Omit< + QueryExecuteOptions< + TRuntime, + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey, + TPageParam + >, + 'initialPageParam' +> & + InfiniteQueryFetchPageOptions + +/** + * Options shared by the `QueryClient` and observer methods that refetch queries, controlling + * whether a failed refetch makes the returned promise reject. + */ +export interface ResultOptions { + /** + * If set to `true`, the method throws if any of the underlying query refetch tasks fail. + * If set to `false`, failed refetches are swallowed and not surfaced to the caller. + * @defaultValue false + */ + throwOnError?: boolean +} + +/** + * Options of the methods that refetch queries, like `refetch` and `queryClient.refetchQueries`. + */ +export interface RefetchOptions extends ResultOptions { + /** + * If set to `true`, a currently running request will be cancelled before a new request is made + * + * If set to `false`, no refetch will be made if there is already a request running. + * @defaultValue true + */ + cancelRefetch?: boolean +} + +/** + * The filters of `queryClient.invalidateQueries`: the {@link QueryFilters} that select the queries + * to invalidate, plus `refetchType` to choose which of them are refetched. + */ +export interface InvalidateQueryFilters< + TRuntime extends RuntimeBinding, + TQueryKey extends QueryKey = QueryKey, +> extends QueryFilters { + /** + * Controls which of the matched (now-invalidated) queries are refetched in the background. + * + * - `'active'`: only queries with at least one active observer are refetched. + * - `'inactive'`: only queries with no active observer are refetched. + * - `'all'`: every matched query is refetched, active or not. + * - `'none'`: no query is refetched; matched queries are only marked as invalidated. + * @defaultValue 'active' + */ + refetchType?: QueryTypeFilter | 'none' +} + +/** + * The filters of `queryClient.refetchQueries`, which select the queries to refetch. + */ +export interface RefetchQueryFilters< + TRuntime extends RuntimeBinding, + TQueryKey extends QueryKey = QueryKey, +> extends QueryFilters {} + +/** + * Options of `queryClient.invalidateQueries`, applied to the refetch that follows the invalidation. + */ +export interface InvalidateOptions extends RefetchOptions {} + +/** + * Options of `queryClient.resetQueries`, applied to the refetch of the active queries after the + * reset. + */ +export interface ResetOptions extends RefetchOptions {} + +/** + * Options of `fetchNextPage` on an infinite query result. + */ +export interface FetchNextPageOptions extends ResultOptions { + /** + * If set to `true`, calling `fetchNextPage` repeatedly will invoke `queryFn` every time, + * whether the previous invocation has resolved or not. Also, the result from previous invocations will be ignored. + * + * If set to `false`, calling `fetchNextPage` repeatedly won't have any effect until the first invocation has resolved. + * @defaultValue true + */ + cancelRefetch?: boolean +} + +/** + * Options of `fetchPreviousPage` on an infinite query result. + */ +export interface FetchPreviousPageOptions extends ResultOptions { + /** + * If set to `true`, calling `fetchPreviousPage` repeatedly will invoke `queryFn` every time, + * whether the previous invocation has resolved or not. Also, the result from previous invocations will be ignored. + * + * If set to `false`, calling `fetchPreviousPage` repeatedly won't have any effect until the first invocation has resolved. + * @defaultValue true + */ + cancelRefetch?: boolean +} + +/** @inline */ +export type QueryStatus = 'pending' | 'error' | 'success' + +/** @inline */ +export type FetchStatus = 'fetching' | 'paused' | 'idle' + +/** + * The properties shared by every state of a query result, like `data`, `error`, `status`, the + * `is*` flags, and `refetch`. Each `QueryObserver*Result` narrows them for one state. + */ +export interface QueryObserverBaseResult< + TData = unknown, + TError = DefaultError, +> { + /** + * The last successfully resolved data for the query. + */ + data: TData | undefined + /** + * The timestamp for when the query most recently returned the `status` as `"success"`. + */ + dataUpdatedAt: number + /** + * The error object for the query, if an error was thrown. + * - Defaults to `null`. + */ + error: TError | null + /** + * The timestamp for when the query most recently returned the `status` as `"error"`. + */ + errorUpdatedAt: number + /** + * The failure count for the query. + * - Incremented every time the query fails. + * - Reset to `0` when the query succeeds. + */ + failureCount: number + /** + * The failure reason for the query retry. + * - Reset to `null` when the query succeeds. + */ + failureReason: TError | null + /** + * The sum of all errors. + */ + errorUpdateCount: number + /** + * A derived boolean from the `status` variable, provided for convenience. + * - `true` if the query has an error from a fetch that failed after its retries, or if `select` threw. + */ + isError: boolean + /** + * Will be `true` if the query has been fetched. + */ + isFetched: boolean + /** + * Will be `true` if the query has been fetched after the component mounted. + * - This property can be used to not show any previously cached data. + */ + isFetchedAfterMount: boolean + /** + * A derived boolean from the `fetchStatus` variable, provided for convenience. + * - `true` whenever the `queryFn` is executing, which includes initial `pending` as well as background refetch. + */ + isFetching: boolean + /** + * Is `true` whenever the first fetch for a query is in-flight. + * - Is the same as `isFetching && isPending`. + */ + isLoading: boolean + /** + * Will be `true` if the query has no cached data, no data from `placeholderData` and no error. + */ + isPending: boolean + /** + * Will be `true` if the query has an error and no data to display. + */ + isLoadingError: boolean + /** + * A derived boolean from the `fetchStatus` variable, provided for convenience. + * - The query wanted to fetch, but has been `paused`. + */ + isPaused: boolean + /** + * Will be `true` if the data shown is the placeholder data. + */ + isPlaceholderData: boolean + /** + * Will be `true` if the query has an error and still has data to display (for infinite queries, not after a failed page fetch). + */ + isRefetchError: boolean + /** + * Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`. + * - Is the same as `isFetching && !isPending`. + */ + isRefetching: boolean + /** + * Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. + */ + isStale: boolean + /** + * A derived boolean from the `status` variable, provided for convenience. + * - `true` if the query has cached data or data from `placeholderData`, and no error. + */ + isSuccess: boolean + /** + * `true` if this observer is enabled, `false` otherwise. + */ + isEnabled: boolean + /** + * A function to manually refetch the query. + */ + refetch: ( + options?: RefetchOptions, + ) => Promise> + /** + * The status of the query. + * - Will be: + * - `error` if the query has an error from a fetch that failed after its retries, or if `select` threw. + * - `success` if the query has cached data (even if `select` returns `undefined`) or data from `placeholderData`, and no error. + * - `pending` otherwise, since the query has no cached data, no data from `placeholderData` and no error. + */ + status: QueryStatus + /** + * The fetch status of the query. + * - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. + * - `paused`: The query wanted to fetch, but has been `paused`. + * - `idle`: The query is not fetching. + * - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. + */ + fetchStatus: FetchStatus +} + +/** + * A query result in the `pending` state: the query has no data yet. + */ +export interface QueryObserverPendingResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * `undefined`, since the query has no data yet. + */ + data: undefined + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `true`, since the query has no cached data, no data from `placeholderData` and no error. + */ + isPending: true + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. + */ + status: 'pending' +} + +/** + * A query result in the `pending` state while the first fetch is in flight, so `isLoading` is + * `true`. + */ +export interface QueryObserverLoadingResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * `undefined`, since the query has no data yet. + */ + data: undefined + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `true`, since the query has no cached data, no data from `placeholderData` and no error. + */ + isPending: true + /** + * `true`, since the first fetch is in flight. + */ + isLoading: true + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. + */ + status: 'pending' +} + +/** + * A query result in the `error` state with no data to display, since a fetch or `select` failed. + */ +export interface QueryObserverLoadingErrorResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * `undefined`, since there was no data to display when a fetch or `select` failed. + */ + data: undefined + /** + * The error the fetch or `select` failed with. + */ + error: TError + /** + * `true`, since the query is in the `error` state. + */ + isError: true + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `true`, since the query has an error and no data to display. + */ + isLoadingError: true + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'error'`, since a fetch failed after its retries or `select` threw. + */ + status: 'error' +} + +/** + * A query result in the `error` state that keeps the data from before a fetch or `select` failed. + */ +export interface QueryObserverRefetchErrorResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * The data from before the fetch or `select` failed, which is kept. + */ + data: TData + /** + * The error the fetch or `select` failed with. + */ + error: TError + /** + * `true`, since the query is in the `error` state. + */ + isError: true + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `true`, since the query has an error and still has data to display. + */ + isRefetchError: true + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'error'`, since a fetch failed after its retries or `select` threw. + */ + status: 'error' +} + +/** + * A query result in the `success` state with data from the cache. + */ +export interface QueryObserverSuccessResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * The last successfully resolved data for the query. + */ + data: TData + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `true`, since the query is in the `success` state. + */ + isSuccess: true + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'success'`, since the query has cached data and no error from a fetch or from + * `select`. + */ + status: 'success' +} + +/** + * A query result in the `success` state that shows `placeholderData` while the query has no data + * yet. + */ +export interface QueryObserverPlaceholderResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * The `placeholderData` shown while the query has no data yet. + */ + data: TData + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `true`, since the query is in the `success` state. + */ + isSuccess: true + /** + * `true`, since the data shown is the `placeholderData`. + */ + isPlaceholderData: true + /** + * `'success'`, since the query shows `placeholderData` and has no error from a fetch or + * from `select`. + */ + status: 'success' +} + +/** + * A query result that always has `data`: the success and refetch error states. + */ +export type DefinedQueryObserverResult< + TData = unknown, + TError = DefaultError, +> = + | QueryObserverRefetchErrorResult + | QueryObserverSuccessResult + +/** + * The result of a `QueryObserver`, and of the hooks built on it like `useQuery`. Narrow it by + * `status` or the `is*` flags to get the type of each state. + */ +export type QueryObserverResult = + | DefinedQueryObserverResult + | QueryObserverLoadingErrorResult + | QueryObserverLoadingResult + | QueryObserverPendingResult + | QueryObserverPlaceholderResult + +/** + * The properties shared by every state of an infinite query result: those of + * {@link QueryObserverBaseResult}, plus `fetchNextPage`, `fetchPreviousPage`, and the flags about + * them, like `hasNextPage` and `isFetchingNextPage`. + */ +export interface InfiniteQueryObserverBaseResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * This function allows you to fetch the next "page" of results. + */ + fetchNextPage: ( + options?: FetchNextPageOptions, + ) => Promise> + /** + * This function allows you to fetch the previous "page" of results. + */ + fetchPreviousPage: ( + options?: FetchPreviousPageOptions, + ) => Promise> + /** + * Will be `true` if there is a next page to be fetched (known via the `getNextPageParam` option). + */ + hasNextPage: boolean + /** + * Will be `true` if there is a previous page to be fetched (known via the `getPreviousPageParam` option). + */ + hasPreviousPage: boolean + /** + * Will be `true` if the query failed while fetching the next page. + */ + isFetchNextPageError: boolean + /** + * Will be `true` while fetching the next page with `fetchNextPage`. + */ + isFetchingNextPage: boolean + /** + * Will be `true` if the query failed while fetching the previous page. + */ + isFetchPreviousPageError: boolean + /** + * Will be `true` while fetching the previous page with `fetchPreviousPage`. + */ + isFetchingPreviousPage: boolean +} + +/** + * An infinite query result in the `pending` state: the query has no data yet. + */ +export interface InfiniteQueryObserverPendingResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * `undefined`, since the query has no data yet. + */ + data: undefined + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `true`, since the query has no cached data, no data from `placeholderData` and no error. + */ + isPending: true + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `false`, since fetching the next page didn't fail. + */ + isFetchNextPageError: false + /** + * `false`, since fetching the previous page didn't fail. + */ + isFetchPreviousPageError: false + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. + */ + status: 'pending' +} + +/** + * An infinite query result in the `pending` state while the first fetch is in flight, so + * `isLoading` is `true`. + */ +export interface InfiniteQueryObserverLoadingResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * `undefined`, since the query has no data yet. + */ + data: undefined + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `true`, since the query has no cached data, no data from `placeholderData` and no error. + */ + isPending: true + /** + * `true`, since the first fetch is in flight. + */ + isLoading: true + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `false`, since fetching the next page didn't fail. + */ + isFetchNextPageError: false + /** + * `false`, since fetching the previous page didn't fail. + */ + isFetchPreviousPageError: false + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. + */ + status: 'pending' +} + +/** + * An infinite query result in the `error` state with no data to display, since a fetch or `select` failed. + */ +export interface InfiniteQueryObserverLoadingErrorResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * `undefined`, since there was no data to display when a fetch or `select` failed. + */ + data: undefined + /** + * The error the fetch or `select` failed with. + */ + error: TError + /** + * `true`, since the query is in the `error` state. + */ + isError: true + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `true`, since the query has an error and no data to display. + */ + isLoadingError: true + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `false`, since fetching the next page didn't fail. + */ + isFetchNextPageError: false + /** + * `false`, since fetching the previous page didn't fail. + */ + isFetchPreviousPageError: false + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'error'`, since a fetch failed after its retries or `select` threw. + */ + status: 'error' +} + +/** + * An infinite query result in the `error` state that keeps the data from before a fetch or `select` + * failed. + */ +export interface InfiniteQueryObserverRefetchErrorResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * The data from before the fetch or `select` failed, which is kept. + */ + data: TData + /** + * The error the fetch or `select` failed with. + */ + error: TError + /** + * `true`, since the query is in the `error` state. + */ + isError: true + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `true`, since the query has an error, still has data to display, and didn't fail fetching a page. + */ + isRefetchError: true + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'error'`, since a fetch failed after its retries or `select` threw. + */ + status: 'error' +} + +/** + * An infinite query result in the `success` state with data from the cache. + */ +export interface InfiniteQueryObserverSuccessResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * The last successfully resolved data for the query. + */ + data: TData + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `false`, since fetching the next page didn't fail. + */ + isFetchNextPageError: false + /** + * `false`, since fetching the previous page didn't fail. + */ + isFetchPreviousPageError: false + /** + * `true`, since the query is in the `success` state. + */ + isSuccess: true + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'success'`, since the query has cached data and no error from a fetch or from + * `select`. + */ + status: 'success' +} + +/** + * An infinite query result in the `success` state that shows `placeholderData` while the query has + * no data yet. + */ +export interface InfiniteQueryObserverPlaceholderResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * The `placeholderData` shown while the query has no data yet. + */ + data: TData + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `true`, since the query is in the `success` state. + */ + isSuccess: true + /** + * `true`, since the data shown is the `placeholderData`. + */ + isPlaceholderData: true + /** + * `false`, since fetching the next page didn't fail. + */ + isFetchNextPageError: false + /** + * `false`, since fetching the previous page didn't fail. + */ + isFetchPreviousPageError: false + /** + * `'success'`, since the query shows `placeholderData` and has no error from a fetch or + * from `select`. + */ + status: 'success' +} + +/** + * An infinite query result that always has `data`: the success and refetch error states. + */ +export type DefinedInfiniteQueryObserverResult< + TData = unknown, + TError = DefaultError, +> = + | InfiniteQueryObserverRefetchErrorResult + | InfiniteQueryObserverSuccessResult + +/** + * The result of an `InfiniteQueryObserver`, and of the hooks built on it like `useInfiniteQuery`. + * Narrow it by `status` or the `is*` flags to get the type of each state. + */ +export type InfiniteQueryObserverResult< + TData = unknown, + TError = DefaultError, +> = + | DefinedInfiniteQueryObserverResult + | InfiniteQueryObserverLoadingErrorResult + | InfiniteQueryObserverLoadingResult + | InfiniteQueryObserverPendingResult + | InfiniteQueryObserverPlaceholderResult + +/** + * The type of a mutation key — the serializable array used to identify and filter mutations. + * Defaults to `ReadonlyArray`; declare `mutationKey` on {@link Register} to narrow it repository-wide. + */ +export type MutationKey = Register extends { + mutationKey: infer TMutationKey +} + ? TMutationKey extends ReadonlyArray + ? TMutationKey + : TMutationKey extends Array + ? TMutationKey + : ReadonlyArray + : ReadonlyArray + +/** @inline */ +export type MutationStatus = 'idle' | 'pending' | 'success' | 'error' + +/** + * Groups mutations so they run one after another instead of in parallel. + * Mutations that share the same `id` form a queue: while one is running, the others wait in `isPaused: true` + * state and resume automatically when their turn comes. Mutations with no scope always run in parallel. + */ +export type MutationScope = { + /** + * The scope's identifier. Mutations with the same `id` run one after another. + */ + id: string +} + +/** + * The type of the `meta` object that can be attached to a mutation and read back from `mutationFn`, callbacks and + * cache-level handlers. Defaults to `Record`; declare `mutationMeta` on {@link Register} to narrow it. + */ +export type MutationMeta = Register extends { + mutationMeta: infer TMutationMeta +} + ? TMutationMeta extends Record + ? TMutationMeta + : Record + : Record + +/** + * The object passed to `mutationFn` and the mutation callbacks: the `QueryClient`, the mutation's + * `meta`, and its `mutationKey`. + */ +export type MutationFunctionContext = { + /** + * The `QueryClient` the mutation runs in. + */ + client: QueryClientOf + /** + * The `meta` of the mutation options. + */ + meta: MutationMeta | undefined + /** + * The `mutationKey` of the mutation options, if set. + */ + mutationKey?: MutationKey +} + +/** @inline */ +export type MutationFunction< + TRuntime extends RuntimeBinding, + TData = unknown, + TVariables = unknown, +> = ( + variables: TVariables, + context: MutationFunctionContext, +) => Promise + +/** + * The options of a mutation: its `mutationFn`, `mutationKey`, callbacks, retries, `scope`, and so + * on. + */ +export interface MutationOptions< + TRuntime extends RuntimeBinding, + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> { + /** + * The function that performs the asynchronous task this mutation runs. + * Required, unless a default mutation function has been set for the matching `mutationKey` via + * `queryClient.setMutationDefaults`. + * Receives the `variables` passed to `mutate`, and a {@link MutationFunctionContext} holding the + * `QueryClient`, the `mutationKey` and `meta`. + * Must return a promise that resolves the mutation's data. + */ + mutationFn?: MutationFunction + /** + * The key to use for this mutation. Optional, but required to inherit defaults registered with + * `queryClient.setMutationDefaults`, and to match this mutation with `useMutationState` or + * `queryClient.isMutating`. + */ + mutationKey?: MutationKey + /** + * This function fires before the mutation function runs, and receives the same variables. + * Useful for optimistic updates applied in the hope that the mutation succeeds. + * The value it returns is passed to `onSuccess`, `onError` and `onSettled` as `onMutateResult`, + * which is where an optimistic update is usually rolled back. + * If a promise is returned, it is awaited before the mutation function runs. + */ + onMutate?: ( + variables: TVariables, + context: MutationFunctionContext, + ) => Promise | TOnMutateResult + /** + * This function fires when the mutation succeeds, and is passed the mutation's result. + * If a promise is returned, it is awaited before `onSettled` runs. + */ + onSuccess?: ( + data: TData, + variables: TVariables, + onMutateResult: TOnMutateResult, + context: MutationFunctionContext, + ) => Promise | unknown + /** + * This function fires when the mutation encounters an error, and is passed the error. + * If a promise is returned, it is awaited before `onSettled` runs. + */ + onError?: ( + error: TError, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => Promise | unknown + /** + * This function fires when the mutation either succeeds or errors, and is passed either the data + * or the error. + * If a promise is returned, it is awaited before the mutation settles. + */ + onSettled?: ( + data: TData | undefined, + error: TError | null, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => Promise | unknown + /** + * If `false`, failed mutations will not retry by default. + * If `true`, failed mutations will retry infinitely. + * If set to an integer number, e.g. 3, failed mutations will retry until the failed mutation count meets that number. + * If set to a function `(failureCount, error) => boolean` failed mutations will retry until the function returns false. + * @defaultValue 0 + */ + retry?: RetryValue + /** + * The delay in milliseconds before a retry. Use a number for a fixed delay or a function that receives + * the failure count and error and returns the delay. The count starts at 0 for the first retry. + * + * By default, each retry waits a random duration from 80% to 100% of the base delay. + * The base delay starts at 1 second and doubles for each retry, up to 30 seconds. + */ + retryDelay?: RetryDelayValue + /** + * Controls whether a mutation is allowed to run based on the current network connectivity. + * @defaultValue 'online' + * @see [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. + */ + networkMode?: NetworkMode + /** + * The time in milliseconds that an unused/inactive mutation remains in memory before it is + * garbage collected. + * + * Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. + */ + gcTime?: number + /** @internal */ + _defaulted?: boolean + /** + * Additional payload to be stored on the mutation cache entry. + * Use it to pass information that can be read wherever the `mutation` is available, such as the + * `onError` and `onSuccess` callbacks of the `MutationCache`. + */ + meta?: MutationMeta + /** + * Controls whether this mutation runs alongside others or waits its turn. + * Mutations sharing the same `scope.id` run serially, in the order they were started. + * Without a scope, a mutation runs as soon as it is triggered. + */ + scope?: MutationScope +} + +/** + * The options of a `MutationObserver`, and of the hooks built on it like `useMutation`: the + * {@link MutationOptions}, plus `throwOnError`. + */ +export interface MutationObserverOptions< + TRuntime extends RuntimeBinding, + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends MutationOptions< + TRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> { + /** + * Whether errors should be thrown instead of setting the `error` property. + * If set to `true`, all errors will be thrown to the nearest error boundary. + * If set to a function, it will be passed the error and should return a boolean indicating whether to throw the + * error (`true`) or return it as state (`false`). + * @defaultValue false + */ + throwOnError?: boolean | ((error: TError) => boolean) +} + +/** + * The callbacks that can be passed to `mutate` for a single call. They run after the callbacks of + * the mutation options. + */ +export interface MutateOptions< + TRuntime extends RuntimeBinding, + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> { + /** + * Called when the mutation of this call succeeds, after the `onSuccess` of the mutation options. + */ + onSuccess?: ( + data: TData, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => void + /** + * Called when the mutation of this call fails, after the `onError` of the mutation options. + */ + onError?: ( + error: TError, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => void + /** + * Called when the mutation of this call succeeds or fails, after the `onSettled` of the mutation + * options. + */ + onSettled?: ( + data: TData | undefined, + error: TError | null, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => void +} + +/** + * The parameters of {@link MutateFunction}: `variables`, optional when `TVariables` accepts + * `undefined`, and the {@link MutateOptions} for that call. + */ +export type MutateFunctionRest< + TRuntime extends RuntimeBinding, + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = undefined extends TVariables + ? [ + variables?: TVariables, + options?: MutateOptions< + TRuntime, + TData, + TError, + TVariables, + TOnMutateResult + >, + ] + : [ + variables: TVariables, + options?: MutateOptions< + TRuntime, + TData, + TError, + TVariables, + TOnMutateResult + >, + ] + +/** + * The `mutate` function of a `MutationObserver`: runs the mutation with the given variables and + * resolves with its data. + */ +export type MutateFunction< + TRuntime extends RuntimeBinding, + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = ( + ...rest: MutateFunctionRest< + TRuntime, + TData, + TError, + TVariables, + TOnMutateResult + > +) => Promise + +/** + * The properties shared by every state of a mutation result, like `data`, `error`, `variables`, + * `status`, the `is*` flags, `mutate`, and `reset`. + */ +export interface MutationObserverBaseResult< + TRuntime extends RuntimeBinding, + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends MutationState { + /** + * The last successfully resolved data for the mutation. + */ + data: TData | undefined + /** + * The variables object passed to the `mutationFn`. + */ + variables: TVariables | undefined + /** + * The error object for the mutation, if an error was encountered. + * - Defaults to `null`. + */ + error: TError | null + /** + * A boolean variable derived from `status`. + * - `true` if the last mutation attempt resulted in an error. + */ + isError: boolean + /** + * A boolean variable derived from `status`. + * - `true` if the mutation is in its initial state prior to executing. + */ + isIdle: boolean + /** + * A boolean variable derived from `status`. + * - `true` if the mutation is currently executing. + */ + isPending: boolean + /** + * A boolean variable derived from `status`. + * - `true` if the last mutation attempt was successful. + */ + isSuccess: boolean + /** + * The status of the mutation. + * - Will be: + * - `idle` initial status prior to the mutation function executing. + * - `pending` if the mutation is currently executing. + * - `error` if the last mutation attempt resulted in an error. + * - `success` if the last mutation attempt was successful. + */ + status: MutationStatus + /** + * The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options. + * @param variables - The variables object to pass to the `mutationFn`. + * @param options.onSuccess - This function will fire when the mutation is successful and will be passed the mutation's result. + * @param options.onError - This function will fire if the mutation encounters an error and will be passed the error. + * @param options.onSettled - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error. + * @remarks + * - If you make multiple requests, `onSuccess` will fire only after the latest call you've made. + * - All the callback functions (`onSuccess`, `onError`, `onSettled`) are void functions, and the returned value will be ignored. + */ + mutate: MutateFunction + /** + * A function to clean the mutation internal state (i.e., it resets the mutation to its initial state). + */ + reset: () => void +} + +/** + * A mutation result in the `idle` state: the mutation hasn't run yet, or was reset. + */ +export interface MutationObserverIdleResult< + TRuntime extends RuntimeBinding, + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends MutationObserverBaseResult< + TRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> { + /** + * `undefined`, since the mutation hasn't run. + */ + data: undefined + /** + * `undefined`, since the mutation hasn't run. + */ + variables: undefined + /** + * `null`, since the mutation hasn't failed. + */ + error: null + /** + * `false`, since the mutation hasn't failed. + */ + isError: false + /** + * `true`, since the mutation hasn't run yet or was reset. + */ + isIdle: true + /** + * `false`, since the mutation isn't running. + */ + isPending: false + /** + * `false`, since the mutation hasn't succeeded. + */ + isSuccess: false + /** + * `'idle'`, since the mutation hasn't run yet or was reset. + */ + status: 'idle' +} + +/** + * A mutation result in the `pending` state while the mutation runs. + */ +export interface MutationObserverLoadingResult< + TRuntime extends RuntimeBinding, + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends MutationObserverBaseResult< + TRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> { + /** + * `undefined`, since the mutation hasn't succeeded. + */ + data: undefined + /** + * The variables passed to `mutate` for this mutation. + */ + variables: TVariables + /** + * `null`, since the mutation hasn't failed. + */ + error: null + /** + * `false`, since the mutation hasn't failed. + */ + isError: false + /** + * `false`, since the mutation has run. + */ + isIdle: false + /** + * `true`, since the mutation is running. + */ + isPending: true + /** + * `false`, since the mutation hasn't succeeded. + */ + isSuccess: false + /** + * `'pending'`, since the mutation is running. + */ + status: 'pending' +} + +/** + * A mutation result in the `error` state after the mutation failed. + */ +export interface MutationObserverErrorResult< + TRuntime extends RuntimeBinding, + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends MutationObserverBaseResult< + TRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> { + /** + * `undefined`, since the mutation hasn't succeeded. + */ + data: undefined + /** + * The error the mutation failed with. + */ + error: TError + /** + * The variables passed to `mutate` for this mutation. + */ + variables: TVariables + /** + * `true`, since the mutation failed. + */ + isError: true + /** + * `false`, since the mutation has run. + */ + isIdle: false + /** + * `false`, since the mutation isn't running. + */ + isPending: false + /** + * `false`, since the mutation hasn't succeeded. + */ + isSuccess: false + /** + * `'error'`, since the mutation failed. + */ + status: 'error' +} + +/** + * A mutation result in the `success` state after the mutation succeeded. + */ +export interface MutationObserverSuccessResult< + TRuntime extends RuntimeBinding, + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends MutationObserverBaseResult< + TRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> { + /** + * The data the mutation resolved with. + */ + data: TData + /** + * `null`, since the mutation hasn't failed. + */ + error: null + /** + * The variables passed to `mutate` for this mutation. + */ + variables: TVariables + /** + * `false`, since the mutation hasn't failed. + */ + isError: false + /** + * `false`, since the mutation has run. + */ + isIdle: false + /** + * `false`, since the mutation isn't running. + */ + isPending: false + /** + * `true`, since the mutation succeeded. + */ + isSuccess: true + /** + * `'success'`, since the mutation succeeded. + */ + status: 'success' +} + +/** + * The result of a `MutationObserver`, and of the hooks built on it like `useMutation`. Narrow it by + * `status` or the `is*` flags to get the type of each state. + */ +export type MutationObserverResult< + TRuntime extends RuntimeBinding, + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = + | MutationObserverIdleResult< + TRuntime, + TData, + TError, + TVariables, + TOnMutateResult + > + | MutationObserverLoadingResult< + TRuntime, + TData, + TError, + TVariables, + TOnMutateResult + > + | MutationObserverErrorResult< + TRuntime, + TData, + TError, + TVariables, + TOnMutateResult + > + | MutationObserverSuccessResult< + TRuntime, + TData, + TError, + TVariables, + TOnMutateResult + > + +/** + * The options of `new QueryClient()`: the `queryCache` and `mutationCache` to use, and the + * `defaultOptions` for its queries and mutations. + */ +export interface QueryClientConfig { + /** The query cache this client is connected to. A new `QueryCache` is created if not provided. */ + queryCache?: QueryCacheOf + /** + * The mutation cache this client is connected to. A new `MutationCache` is created if not + * provided. + */ + mutationCache?: MutationCacheOf + /** Default options for all queries and mutations created through this client. */ + defaultOptions?: DefaultOptions +} + +/** + * The default options of a `QueryClient`, applied to every query (`queries`), mutation + * (`mutations`), `hydrate`, and `dehydrate` call unless overridden. + */ +export interface DefaultOptions< + TRuntime extends RuntimeBinding, + TError = DefaultError, +> { + /** Default options applied to every query, unless overridden per-query. */ + queries?: OmitKeyof< + QueryObserverOptionsBase, + 'suspense' | 'queryKey' + > + /** Default options applied to every mutation, unless overridden per-mutation. */ + mutations?: MutationObserverOptions< + TRuntime, + unknown, + TError, + unknown, + unknown + > + /** Default options used when hydrating queries and mutations; see {@link HydrateOptions}. */ + hydrate?: HydrateOptions['defaultOptions'] + /** Default options used when dehydrating the client's caches; see {@link DehydrateOptions}. */ + dehydrate?: DehydrateOptions +} + +/** + * Options for cancelling an in-flight fetch, e.g. via `query.cancel()`. + * They are carried on the {@link CancelledError} that the cancelled fetch rejects with. + */ +export interface CancelOptions { + /** + * If `true`, the query goes back to the state it had before the fetch started, instead of getting + * the cancellation error. + */ + revert?: boolean + /** + * If `true`, the cancellation error isn't surfaced, e.g. because another fetch replaces the + * cancelled one. + */ + silent?: boolean +} + +/** + * Options for writing data into the cache, e.g. via `queryClient.setQueryData()`. + * `updatedAt` overrides the timestamp the data is recorded with, which is what staleness is measured from; + * omit it to use the current time. + */ +export interface SetDataOptions { + /** + * The timestamp to record the data with, instead of the current time. Staleness is measured from + * it. + */ + updatedAt?: number +} + +/** @inline */ +export type NotifyEventType = + | 'added' + | 'removed' + | 'updated' + | 'observerAdded' + | 'observerRemoved' + | 'observerResultsUpdated' + | 'observerOptionsUpdated' + +/** + * The base shape of the events that the query and mutation caches send to their listeners. + */ +export interface NotifyEvent { + /** + * The kind of event, e.g. `'added'`, `'removed'`, or `'updated'`. + */ + type: NotifyEventType +} diff --git a/packages/query-types/src/utils.ts b/packages/query-types/src/utils.ts new file mode 100644 index 00000000000..c97aa1ce003 --- /dev/null +++ b/packages/query-types/src/utils.ts @@ -0,0 +1,117 @@ +import type { MutationOf, QueryOf, RuntimeBinding } from './binding' +import type { fetchSignal } from './symbols' +import type { + DefaultError, + FetchStatus, + MutationKey, + MutationStatus, + QueryKey, +} from './types' + +export type DropLast> = T extends readonly [ + ...infer R, + unknown, +] + ? readonly [...R] + : never + +export type TuplePrefixes> = + T extends readonly [] ? readonly [] : TuplePrefixes> | T + +/** + * Filters used to select queries, for example in `queryClient.getQueriesData` or `queryClient.invalidateQueries`. + * All provided filters must match; filters that are left unspecified are ignored. + */ +export interface QueryFilters< + TRuntime extends RuntimeBinding, + TQueryKey extends QueryKey = QueryKey, +> { + /** + * Filter to active queries, inactive queries or all queries + * @defaultValue 'all' + */ + type?: QueryTypeFilter + /** + * Match query key exactly + */ + exact?: boolean + /** + * Include queries matching this predicate function + */ + predicate?: (query: QueryOf) => boolean + /** + * Include queries matching this query key + */ + queryKey?: TQueryKey | TuplePrefixes + /** + * Include or exclude stale queries + */ + stale?: boolean + /** + * Include queries matching their fetchStatus + */ + fetchStatus?: FetchStatus +} + +/** + * Filters used to select mutations, for example in `mutationCache.findAll` or `queryClient.isMutating`. + * All provided filters must match; filters that are left unspecified are ignored. + */ +export interface MutationFilters< + TRuntime extends RuntimeBinding, + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> { + /** + * Match mutation key exactly + */ + exact?: boolean + /** + * Include mutations matching this predicate function + */ + predicate?: ( + mutation: MutationOf, + ) => boolean + /** + * Include mutations matching this mutation key + */ + mutationKey?: TuplePrefixes + /** + * Filter by mutation status + */ + status?: MutationStatus +} + +/** + * Either a plain value of type `TOutput`, or a function that receives `TInput` and returns `TOutput`. + * Used for example by `setQueryData`-style updaters, which accept either the new data directly or a + * function that computes it from the previous data. See {@link functionalUpdate}. + * @example + * ```ts + * queryClient.setQueryData(['posts'], newPosts) + * + * // Or, using an updater function that receives the current data: + * queryClient.setQueryData(['posts'], (oldPosts) => + * oldPosts ? [...oldPosts, newPost] : oldPosts, + * ) + * ``` + */ +export type Updater = TOutput | ((input: TInput) => TOutput) + +/** + * Which queries a filter matches: all of them, only active ones (with enabled observers), or only + * inactive ones. + */ +export type QueryTypeFilter = 'all' | 'active' | 'inactive' + +export type { skipToken as SkipToken } from './symbols' + +export type { defaultQueryFn as DefaultQueryFn } from './symbols' + +/** Internal view of a context that exposes its signal without consuming it. */ +export interface FetchSignalContext { + readonly signal: AbortSignal + readonly [fetchSignal]?: AbortSignal +} diff --git a/packages/query-types/tsconfig.json b/packages/query-types/tsconfig.json new file mode 100644 index 00000000000..0cc454b2a77 --- /dev/null +++ b/packages/query-types/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "./dist-ts", + "rootDir": "." + }, + "include": ["src", "*.config.ts", "*.config.js", "package.json"] +} diff --git a/packages/query-types/tsconfig.legacy.json b/packages/query-types/tsconfig.legacy.json new file mode 100644 index 00000000000..84ebe1a984b --- /dev/null +++ b/packages/query-types/tsconfig.legacy.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "./dist-ts/legacy" + }, + "include": ["src"], + "exclude": ["src/__tests__"] +} diff --git a/packages/query-types/tsconfig.prod.json b/packages/query-types/tsconfig.prod.json new file mode 100644 index 00000000000..2bb29fdf02a --- /dev/null +++ b/packages/query-types/tsconfig.prod.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "incremental": false, + "composite": false, + "rootDir": "../../" + }, + "include": ["src"], + "exclude": ["src/__tests__"] +} diff --git a/packages/query-types/tsdown.config.ts b/packages/query-types/tsdown.config.ts new file mode 100644 index 00000000000..8f94eb145bc --- /dev/null +++ b/packages/query-types/tsdown.config.ts @@ -0,0 +1,6 @@ +import { defineConfig } from 'tsdown' +import { getTsdownConfig } from './root.tsdown.config.js' + +export default defineConfig( + getTsdownConfig({ entry: ['src/index.ts', 'src/bindings.ts'] }), +) diff --git a/packages/react-query-no-core-pluggable/README.md b/packages/react-query-no-core-pluggable/README.md new file mode 100644 index 00000000000..85fbbf7b317 --- /dev/null +++ b/packages/react-query-no-core-pluggable/README.md @@ -0,0 +1,46 @@ +# @tanstack/react-query-no-core-pluggable + +An experimental ESM React Query adapter for React 19. The default client supports ordinary queries, including suspense, parallel queries, prefetching and query hydration. + +```tsx +import { + QueryClient, + QueryClientProvider, + useQuery, +} from '@tanstack/react-query-no-core-pluggable' + +const client = new QueryClient() + +function Greeting() { + const { data } = useQuery({ + queryKey: ['greeting'], + queryFn: () => Promise.resolve('Hello'), + }) + return

{data}

+} + +export function App() { + return ( + + + + ) +} +``` + +Import the plugins your application uses and register them on its client. Each client installs its own plugins and owns its caches. + +```ts +import { + QueryClient, + infiniteQueryPlugin, + mutationPlugin, +} from '@tanstack/react-query-no-core-pluggable' + +const client = new QueryClient({ + plugins: [infiniteQueryPlugin, mutationPlugin], +}) +``` + +- `infiniteQueryPlugin` enables paginated fetching through `useInfiniteQuery`, `client.infiniteQuery` and their related APIs. Install it when restoring infinite queries from a server snapshot. +- `mutationPlugin` enables mutation observers, mutation state subscriptions and mutation hydration. To supply a custom cache, pass `mutationCache` alongside the plugin. diff --git a/packages/react-query-no-core-pluggable/oxlint.config.ts b/packages/react-query-no-core-pluggable/oxlint.config.ts new file mode 100644 index 00000000000..91da02f7ef4 --- /dev/null +++ b/packages/react-query-no-core-pluggable/oxlint.config.ts @@ -0,0 +1,51 @@ +import pluginReact from '@eslint-react/eslint-plugin' +import reactHooks from 'eslint-plugin-react-hooks' +import { defineConfig } from 'oxlint' +import rootConfig from './root.oxlint.config.ts' + +export default defineConfig({ + extends: [rootConfig], + settings: rootConfig.settings, + jsPlugins: [ + // 'react-hooks' is reserved for Oxlint's native plugin, which lacks the React Compiler rules + { name: 'react-hooks-js', specifier: 'eslint-plugin-react-hooks' }, + '@eslint-react/eslint-plugin', + ], + rules: { + ...Object.fromEntries( + Object.entries(reactHooks.configs.flat.recommended.rules).map( + ([name, value]) => [ + name.replace(/^react-hooks\//, 'react-hooks-js/'), + value, + ], + ), + ), + ...pluginReact.configs.recommended.rules, + 'react-hooks-js/exhaustive-deps': 'error', + 'react-hooks-js/unsupported-syntax': 'error', + 'react-hooks-js/incompatible-library': 'error', + '@eslint-react/no-context-provider': 'off', // We need to be React 18 compatible + '@eslint-react/no-use-context': 'off', // We need to be React 18 compatible + // Covered by 'eslint-plugin-react-hooks' + '@eslint-react/error-boundaries': 'off', + '@eslint-react/exhaustive-deps': 'off', + '@eslint-react/globals': 'off', + '@eslint-react/immutability': 'off', + '@eslint-react/purity': 'off', + '@eslint-react/refs': 'off', + '@eslint-react/rules-of-hooks': 'off', + '@eslint-react/set-state-in-effect': 'off', + '@eslint-react/set-state-in-render': 'off', + '@eslint-react/static-components': 'off', + '@eslint-react/unsupported-syntax': 'off', + '@eslint-react/use-memo': 'off', + }, + overrides: [ + { + files: ['**/__tests__/**'], + rules: { + 'typescript/no-unnecessary-condition': 'off', + }, + }, + ], +}) diff --git a/packages/react-query-no-core-pluggable/package.json b/packages/react-query-no-core-pluggable/package.json new file mode 100644 index 00000000000..16c19f5fd24 --- /dev/null +++ b/packages/react-query-no-core-pluggable/package.json @@ -0,0 +1,85 @@ +{ + "name": "@tanstack/react-query-no-core-pluggable", + "version": "5.108.4", + "description": "React Query with a standalone runtime and opt-in mutation and infinite query plugins", + "author": "tannerlinsley", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/TanStack/query.git", + "directory": "packages/react-query-no-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 ./tests", + "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 run && node ../../scripts/test-react-query-compat.mjs", + "test:lib:dev": "vitest --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__" + ], + "dependencies": { + "@tanstack/query-types": "workspace:*" + }, + "devDependencies": { + "@eslint-react/eslint-plugin": "catalog:", + "@testing-library/react": "catalog:", + "@testing-library/react-render-stream": "^2.0.2", + "@types/react": "catalog:", + "@vitejs/plugin-react": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "react": "catalog:", + "react-dom": "catalog:", + "typescript": "catalog:" + }, + "peerDependencies": { + "@types/react": "^19", + "react": "^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + }, + "nx": { + "targets": { + "test:lib": { + "inputs": [ + "default", + "^production", + "reactQueryCompatibility" + ] + } + } + } +} diff --git a/packages/react-query-no-core-pluggable/root.oxlint.config.ts b/packages/react-query-no-core-pluggable/root.oxlint.config.ts new file mode 120000 index 00000000000..56565c65534 --- /dev/null +++ b/packages/react-query-no-core-pluggable/root.oxlint.config.ts @@ -0,0 +1 @@ +../../oxlint.config.ts \ No newline at end of file diff --git a/packages/react-query-no-core-pluggable/root.tsdown.config.js b/packages/react-query-no-core-pluggable/root.tsdown.config.js new file mode 120000 index 00000000000..a997d5d337c --- /dev/null +++ b/packages/react-query-no-core-pluggable/root.tsdown.config.js @@ -0,0 +1 @@ +../../scripts/getTsdownConfig.js \ No newline at end of file diff --git a/packages/react-query-no-core-pluggable/src/HydrationBoundary.tsx b/packages/react-query-no-core-pluggable/src/HydrationBoundary.tsx new file mode 100644 index 00000000000..f51a7928983 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/HydrationBoundary.tsx @@ -0,0 +1,140 @@ +'use client' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import { hydrate } from './runtime/index' +import type { + DehydratedState, + HydrateOptions, + OmitKeyof, + QueryClient, +} from './runtime/index' + +/** + * The props accepted by `HydrationBoundary`. + */ +export interface HydrationBoundaryProps { + /** + * The state to hydrate. Pass the result of `dehydrate(queryClient)`. + */ + state: DehydratedState + /** + * Optional. Note: unlike `hydrate`, `mutations` cannot be set here. + */ + options?: OmitKeyof & { + defaultOptions?: OmitKeyof< + Exclude, + 'mutations' + > + } + /** + * The components to render — always rendered unconditionally, not gated on hydration. New queries are + * hydrated into the cache during render; for queries that already exist in the cache, only newer dehydrated + * data is hydrated, and that happens in an effect after commit, so `children` may render briefly before it + * lands. + */ + children?: React.ReactNode + /** + * Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. + */ + queryClient?: QueryClient +} + +/** + * `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by + * `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on + * update timestamp. + * + * Note: Only `queries` can be dehydrated with an `HydrationBoundary`. + * @param props - The dehydrated `state` to hydrate, the hydrate `options`, an optional custom + * `queryClient`, and the `children` to render. + * @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the + * cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect + * after commit. + * @example + * ```tsx + * import { HydrationBoundary } from '@tanstack/react-query-no-core-pluggable' + * + * function App() { + * return ... + * } + * ``` + * @example + * Server-side prefetch handed off to the client via `dehydrate`: + * ```tsx + * import { HydrationBoundary, dehydrate, noop } from '@tanstack/react-query-no-core-pluggable' + * + * async function ServerComponent() { + * const queryClient = getQueryClient() + * + * await queryClient + * .query({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * .catch(noop) + * + * return ( + * + * + * + * ) + * } + * ``` + */ +export const HydrationBoundary = ({ + children, + options = {}, + state, + queryClient, +}: HydrationBoundaryProps) => { + const client = useQueryClient(queryClient) + + const optionsRef = React.useRef(options) + React.useEffect(() => { + optionsRef.current = options + }) + + // Hydrate new queries during render so children can read their data. + // Hydrate existing queries after commit so an aborted transition cannot update them. + const hydrationQueue: DehydratedState['queries'] | undefined = + React.useMemo(() => { + const queryCache = client.getQueryCache() + + const newQueries: DehydratedState['queries'] = [] + const existingQueries: DehydratedState['queries'] = [] + for (const dehydratedQuery of state.queries) { + const existingQuery = queryCache.get(dehydratedQuery.queryHash) + + if (!existingQuery) { + newQueries.push(dehydratedQuery) + continue + } + + const hydrationIsNewer = + dehydratedQuery.state.dataUpdatedAt > + existingQuery.state.dataUpdatedAt || + (dehydratedQuery.promise && + existingQuery.state.status !== 'pending' && + existingQuery.state.fetchStatus !== 'fetching' && + dehydratedQuery.dehydratedAt > existingQuery.state.dataUpdatedAt) + + if (hydrationIsNewer) { + existingQueries.push(dehydratedQuery) + } + } + + if (newQueries.length > 0) { + // oxlint-disable-next-line react-hooks-js/refs -- new queries are hydrated during render on purpose, and 'options' is read through a ref so that a new 'options' object does not rerun this memo + hydrate(client, { queries: newQueries }, optionsRef.current) + } + return existingQueries.length > 0 ? existingQueries : undefined + }, [client, state]) + + React.useEffect(() => { + if (hydrationQueue) { + hydrate(client, { queries: hydrationQueue }, optionsRef.current) + } + }, [client, hydrationQueue]) + + return children as React.ReactElement +} diff --git a/packages/react-query-no-core-pluggable/src/IsRestoringProvider.ts b/packages/react-query-no-core-pluggable/src/IsRestoringProvider.ts new file mode 100644 index 00000000000..abb353406a6 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/IsRestoringProvider.ts @@ -0,0 +1,18 @@ +'use client' +import * as React from 'react' + +const IsRestoringContext = React.createContext(false) + +/** + * If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to + * check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid + * race conditions between the restore and mounting queries. + * @returns `true` while a persisted client is being restored, `false` otherwise. + */ +export const useIsRestoring = () => React.useContext(IsRestoringContext) + +/** + * The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently + * being restored, read by `useIsRestoring`. + */ +export const IsRestoringProvider = IsRestoringContext.Provider diff --git a/packages/react-query-no-core-pluggable/src/QueryClientProvider.tsx b/packages/react-query-no-core-pluggable/src/QueryClientProvider.tsx new file mode 100644 index 00000000000..3f93a38df1e --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/QueryClientProvider.tsx @@ -0,0 +1,84 @@ +'use client' +import * as React from 'react' +import type { QueryClient } from './runtime/index' + +/** + * The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it. + */ +export const QueryClientContext = React.createContext( + undefined, +) + +/** + * The `useQueryClient` hook returns the current `QueryClient` instance. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The current `QueryClient` instance. + * @throws {Error} If no `queryClient` argument is passed and no `QueryClientProvider` is found in the + * component tree. + */ +export const useQueryClient = (queryClient?: QueryClient) => { + const client = React.useContext(QueryClientContext) + + if (queryClient) { + return queryClient + } + + if (!client) { + throw new Error('No QueryClient set, use QueryClientProvider to set one') + } + + return client +} + +/** + * The props accepted by `QueryClientProvider`. + */ +export type QueryClientProviderProps = { + /** + * **Required** + * + * The `QueryClient` instance to provide. + */ + client: QueryClient + /** + * The components that get access to the provided `QueryClient`. + */ + children?: React.ReactNode +} + +/** + * Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also + * calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to + * focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or + * comes back online). + * @param props - The `client` to provide, and the `children` that get access to it. + * @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`. + * @example + * ```tsx + * import { QueryClient, QueryClientProvider } from '@tanstack/react-query-no-core-pluggable' + * + * const queryClient = new QueryClient() + * + * function App() { + * return ... + * } + * ``` + */ +export const QueryClientProvider = ({ + client, + children, +}: QueryClientProviderProps): React.JSX.Element => { + React.useEffect(() => { + client.mount() + return () => { + client.unmount() + } + }, [client]) + + return ( + + {children} + + ) +} diff --git a/packages/react-query-no-core-pluggable/src/QueryErrorResetBoundary.tsx b/packages/react-query-no-core-pluggable/src/QueryErrorResetBoundary.tsx new file mode 100644 index 00000000000..8c7dad91cb0 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/QueryErrorResetBoundary.tsx @@ -0,0 +1,169 @@ +'use client' +import * as React from 'react' + +// CONTEXT + +/** + * Resets any query errors within the boundary, so queries know they can try again. + */ +export type QueryErrorResetFunction = () => void + +/** + * Returns whether the boundary has been reset and not yet cleared. + */ +export type QueryErrorIsResetFunction = () => boolean + +/** + * Clears the reset state, so queries know not to try again until the boundary is reset again. + */ +export type QueryErrorClearResetFunction = () => void + +/** + * The value a `QueryErrorResetBoundary` shares through context, used to reset query errors within + * it and to check whether a reset was requested. + */ +export interface QueryErrorResetBoundaryValue { + /** + * Clears the reset state, so queries know not to try again until the boundary is reset again. + */ + clearReset: QueryErrorClearResetFunction + /** + * Returns whether the boundary has been reset and not yet cleared. + */ + isReset: QueryErrorIsResetFunction + /** + * Resets any query errors within the boundary, so queries know they can try again. + */ + reset: QueryErrorResetFunction +} + +/** + * Creates the value shared through the boundary's context, which tracks whether a reset was + * requested. + * @returns The `clearReset`, `isReset`, and `reset` functions of the boundary. + */ +function createValue(): QueryErrorResetBoundaryValue { + let isReset = false + return { + /** + * Clears the reset state, so queries know not to try again until the boundary is reset again. + */ + clearReset: () => { + isReset = false + }, + /** + * Resets any query errors within the boundary, so queries know they can try again. + */ + reset: () => { + isReset = true + }, + /** + * Returns whether the boundary has been reset and not yet cleared. + * @returns `true` if the boundary has been reset and not yet cleared. + */ + isReset: () => { + return isReset + }, + } +} + +const QueryErrorResetBoundaryContext = React.createContext(createValue()) + +// HOOK + +/** + * This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary + * defined it will reset them globally. + * @returns The boundary's {@link QueryErrorResetBoundaryValue}. + * @example + * ```tsx + * import { ErrorBoundary } from 'react-error-boundary' + * import { useQueryErrorResetBoundary } from '@tanstack/react-query-no-core-pluggable' + * + * function App({ children }: { children: React.ReactNode }) { + * const { reset } = useQueryErrorResetBoundary() + * + * return ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * {children} + *
+ * ) + * } + * ``` + */ +export const useQueryErrorResetBoundary = () => + React.useContext(QueryErrorResetBoundaryContext) + +// COMPONENT + +/** + * A render-prop function usable as `children` on `QueryErrorResetBoundary`. + * @param value - The boundary's {@link QueryErrorResetBoundaryValue}. + * @returns The children to render. + */ +export type QueryErrorResetBoundaryFunction = ( + value: QueryErrorResetBoundaryValue, +) => React.ReactNode + +/** + * The props accepted by `QueryErrorResetBoundary`. + */ +export interface QueryErrorResetBoundaryProps { + /** + * Either a plain node, or a function that receives the boundary's {@link QueryErrorResetBoundaryValue} and + * returns a node. + */ + children: QueryErrorResetBoundaryFunction | React.ReactNode +} + +/** + * When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to + * try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can + * reset any query errors within the boundaries of the component. + * @param props - The `children` to render. + * @returns The `children`, rendered as-is, or called with the boundary's {@link QueryErrorResetBoundaryValue} + * if `children` is a function. + * @example + * ```tsx + * import { ErrorBoundary } from 'react-error-boundary' + * import { QueryErrorResetBoundary } from '@tanstack/react-query-no-core-pluggable' + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * + *
+ * )} + *
+ * ) + * } + * ``` + */ +export const QueryErrorResetBoundary = ({ + children, +}: QueryErrorResetBoundaryProps) => { + const [value] = React.useState(() => createValue()) + return ( + + {typeof children === 'function' ? children(value) : children} + + ) +} diff --git a/packages/react-query-no-core-pluggable/src/__tests__/plugins.test.ts b/packages/react-query-no-core-pluggable/src/__tests__/plugins.test.ts new file mode 100644 index 00000000000..bf629c167e4 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/__tests__/plugins.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest' +import { + MutationCache, + MutationObserver, + QueryClient, + dehydrate, + hydrate, + infiniteQueryOptions, + infiniteQueryPlugin, + mutationPlugin, +} from '..' + +const pages = infiniteQueryOptions({ + queryKey: ['pages'], + initialPageParam: 1, + queryFn: ({ pageParam }) => pageParam, + getNextPageParam: (lastPage) => lastPage + 1, +}) + +describe('per-client plugins', () => { + it('fetches, hydrates, and clears query data with the default client', async () => { + const server = new QueryClient() + const client = new QueryClient() + + await server.query({ queryKey: ['answer'], queryFn: () => 42 }) + const snapshot = dehydrate(server) + expect(snapshot.mutations).toStrictEqual([]) + hydrate(client, snapshot) + expect(client.getQueryData(['answer'])).toBe(42) + expect(client.isMutating()).toBe(0) + await client.resumePausedMutations() + client.clear() + expect(client.getQueryData(['answer'])).toBeUndefined() + }) + + it('identifies missing plugins at their entry points', async () => { + const client = new QueryClient() + + expect(() => new MutationObserver(client, {})).toThrow('mutationPlugin') + await expect(client.infiniteQuery(pages)).rejects.toThrow( + 'infiniteQueryPlugin', + ) + expect(client.getQueryCache().getAll()).toHaveLength(0) + }) + + it('installs mutations on an individual client and honors a supplied cache', async () => { + const cache = new MutationCache() + const client = new QueryClient({ + plugins: [mutationPlugin], + mutationCache: cache, + }) + const other = new QueryClient({ plugins: [mutationPlugin] }) + + const observer = new MutationObserver(client, { + mutationFn: () => Promise.resolve(42), + }) + await expect(observer.mutate()).resolves.toBe(42) + expect(cache.getAll()).toHaveLength(1) + expect(other.getMutationCache().getAll()).toHaveLength(0) + const snapshot = dehydrate(client, { shouldDehydrateMutation: () => true }) + expect(() => hydrate(new QueryClient(), snapshot)).toThrow('mutationPlugin') + hydrate(other, snapshot) + expect(other.getMutationCache().getAll()[0]?.state.data).toBe(42) + await expect(client.infiniteQuery(pages)).rejects.toThrow( + 'infiniteQueryPlugin', + ) + }) + + it('fetches and restores pages independently of mutation support', async () => { + const server = new QueryClient({ plugins: [infiniteQueryPlugin] }) + const client = new QueryClient({ plugins: [infiniteQueryPlugin] }) + + const data = await server.infiniteQuery({ ...pages, pages: 2 }) + expect(data).toStrictEqual({ pages: [1, 2], pageParams: [1, 2] }) + const snapshot = dehydrate(server) + hydrate(client, snapshot) + await expect(client.infiniteQuery(pages)).resolves.toStrictEqual(data) + expect(() => client.getMutationCache()).toThrow('mutationPlugin') + }) +}) diff --git a/packages/react-query-no-core-pluggable/src/errorBoundaryUtils.ts b/packages/react-query-no-core-pluggable/src/errorBoundaryUtils.ts new file mode 100644 index 00000000000..5d927363a0b --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/errorBoundaryUtils.ts @@ -0,0 +1,103 @@ +'use client' +import * as React from 'react' +import { shouldThrowError } from './runtime/index' +import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import type { + DefaultedQueryObserverOptions, + Query, + QueryKey, + QueryObserverResult, + ThrowOnError, +} from './runtime/index' + +/** + * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`), + * unless the error boundary has been reset, so a remount doesn't retry the failed query before the + * user resets the boundary. Mutates the options. + * @param options - The defaulted query options to adjust. + * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`. + * @param query - The query, used to evaluate a `throwOnError` function against its error. + */ +export const ensurePreventErrorBoundaryRetry = < + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + options: DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + errorResetBoundary: QueryErrorResetBoundaryValue, + query: Query | undefined, +) => { + const throwOnError = + query?.state.status === 'error' && + typeof options.throwOnError === 'function' + ? shouldThrowError(options.throwOnError, [ + query.state.error as TError, + query, + ]) + : options.throwOnError + + if (options.suspense || throwOnError) { + // Prevent retrying failed query if the error boundary has not been reset yet + if (!errorResetBoundary.isReset()) { + options.retryOnMount = false + } + } +} + +/** + * Clears the reset state of the error boundary after the component mounts, so later errors are + * thrown to the boundary again. + * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`. + */ +export const useClearResetErrorBoundary = ( + errorResetBoundary: QueryErrorResetBoundaryValue, +) => { + React.useEffect(() => { + errorResetBoundary.clearReset() + }, [errorResetBoundary]) +} + +/** + * Checks whether the query error should be thrown to the nearest error boundary: the query errored + * and isn't fetching, the boundary hasn't been reset, and either `suspense` is enabled with no data + * or `throwOnError` says so. + * @param params - The observer `result`, the `errorResetBoundary`, the `throwOnError` option, the + * `query`, and the `suspense` option. + * @returns `true` if the error should be thrown. + */ +export const getHasError = < + TData, + TError, + TQueryFnData, + TQueryData, + TQueryKey extends QueryKey, +>({ + result, + errorResetBoundary, + throwOnError, + query, + suspense, +}: { + result: QueryObserverResult + errorResetBoundary: QueryErrorResetBoundaryValue + throwOnError: ThrowOnError + query: Query | undefined + suspense: boolean | undefined +}) => { + return ( + result.isError && + !errorResetBoundary.isReset() && + !result.isFetching && + query && + ((suspense && result.data === undefined) || + shouldThrowError(throwOnError, [result.error, query])) + ) +} diff --git a/packages/react-query-no-core-pluggable/src/index.ts b/packages/react-query-no-core-pluggable/src/index.ts new file mode 100644 index 00000000000..816f5f3a89e --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/index.ts @@ -0,0 +1,83 @@ +/* istanbul ignore file */ + +// Public cache and observer API +// oxlint-disable-next-line tanstack-query/no-restricted-syntax +export * from './runtime/index' + +// React Query +export type { + AnyUseBaseQueryOptions, + UseBaseQueryOptions, + UsePrefetchQueryOptions, + UsePrefetchInfiniteQueryOptions, + AnyUseQueryOptions, + UseQueryOptions, + AnyUseSuspenseQueryOptions, + UseSuspenseQueryOptions, + AnyUseInfiniteQueryOptions, + UseInfiniteQueryOptions, + AnyUseSuspenseInfiniteQueryOptions, + UseSuspenseInfiniteQueryOptions, + UseBaseQueryResult, + UseQueryResult, + UseSuspenseQueryResult, + DefinedUseQueryResult, + UseInfiniteQueryResult, + DefinedUseInfiniteQueryResult, + UseSuspenseInfiniteQueryResult, + AnyUseMutationOptions, + UseMutationOptions, + UseMutateFunction, + UseMutateAsyncFunction, + UseBaseMutationResult, + UseMutationResult, +} from './types' +export { useQueries } from './useQueries' +export type { QueriesResults, QueriesOptions } from './useQueries' +export { useQuery } from './useQuery' +export { useSuspenseQuery } from './useSuspenseQuery' +export { useSuspenseInfiniteQuery } from './useSuspenseInfiniteQuery' +export { useSuspenseQueries } from './useSuspenseQueries' +export type { + SuspenseQueriesResults, + SuspenseQueriesOptions, +} from './useSuspenseQueries' +export { usePrefetchQuery } from './usePrefetchQuery' +export { usePrefetchInfiniteQuery } from './usePrefetchInfiniteQuery' +export { queryOptions } from './queryOptions' +export type { + DefinedInitialDataOptions, + UndefinedInitialDataOptions, + UnusedSkipTokenOptions, +} from './queryOptions' +export { infiniteQueryOptions } from './infiniteQueryOptions' +export type { + DefinedInitialDataInfiniteOptions, + UndefinedInitialDataInfiniteOptions, + UnusedSkipTokenInfiniteOptions, +} from './infiniteQueryOptions' +export { + QueryClientContext, + QueryClientProvider, + useQueryClient, +} from './QueryClientProvider' +export type { QueryClientProviderProps } from './QueryClientProvider' +export type { QueryErrorResetBoundaryProps } from './QueryErrorResetBoundary' +export { HydrationBoundary } from './HydrationBoundary' +export type { HydrationBoundaryProps } from './HydrationBoundary' +export type { + QueryErrorClearResetFunction, + QueryErrorIsResetFunction, + QueryErrorResetBoundaryFunction, + QueryErrorResetFunction, +} from './QueryErrorResetBoundary' +export { + QueryErrorResetBoundary, + useQueryErrorResetBoundary, +} from './QueryErrorResetBoundary' +export { useIsFetching } from './useIsFetching' +export { useIsMutating, useMutationState } from './useMutationState' +export { useMutation } from './useMutation' +export { mutationOptions } from './mutationOptions' +export { useInfiniteQuery } from './useInfiniteQuery' +export { useIsRestoring, IsRestoringProvider } from './IsRestoringProvider' diff --git a/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts b/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts new file mode 100644 index 00000000000..d280fd34e0f --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts @@ -0,0 +1,302 @@ +import type { + DefaultError, + InfiniteData, + InitialDataFunction, + NonUndefinedGuard, + OmitKeyof, + QueryKey, + QueryKeyWithDataTag, + SkipToken, +} from './runtime/index' +import type { UseInfiniteQueryOptions } from './types' + +/** + * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is omitted, may be + * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is + * `pending`. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export type UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData?: + | undefined + | NonUndefinedGuard> + | InitialDataFunction< + NonUndefinedGuard> + > +} + +/** + * The options accepted by the `infiniteQueryOptions` overload selected when `queryFn` is not `skipToken` and + * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` — same as + * {@link UndefinedInitialDataInfiniteOptions}, but `queryFn` may not be `skipToken`. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export type UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = OmitKeyof< + UseInfiniteQueryOptions, + 'queryFn' +> & { + queryFn: Exclude< + UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >['queryFn'], + SkipToken + > +} + +/** + * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is known to be + * defined — `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export type DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData: + | NonUndefinedGuard> + | (() => NonUndefinedGuard>) +} + +/** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * `options.queryKey` is required and is the query key to generate options for. + * + * This overload is selected when `initialData` is known to be defined. + * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` known to be defined. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or + * automatically as the user scrolls. + * @see {@link useInfiniteQuery} to run an infinite query with these options. + * @example + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' + * + * export const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * initialData: { pages: [], pageParams: [] }, + * }) + * + * function Projects() { + * // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the + * // list stays visible alongside the error. + * const { data, isError, error } = useInfiniteQuery(projectsOptions) + * + * return ( + *
+ * {isError ? Error: {error.message} : null} + *
    + * {data.pages.map((page) => page.projects.map((p) =>
  • {p.name}
  • ))} + *
+ *
+ * ) + * } + * ``` + */ +export function infiniteQueryOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & + QueryKeyWithDataTag, TError> + +/** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * `options.queryKey` is required and is the query key to generate options for. + * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or + * automatically as the user scrolls. + * @see {@link useInfiniteQuery} to run an infinite query with these options. + * @example + * A parameterized factory, so the same options object can be reused per `postId`: + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' + * + * export const commentsOptions = (postId: string) => + * infiniteQueryOptions({ + * queryKey: ['post', postId, 'comments'], + * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Comments({ postId }: { postId: string }) { + * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
    + * {data.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} + *
+ * ) + * } + * ``` + */ +export function infiniteQueryOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & + QueryKeyWithDataTag, TError> + +/** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * `options.queryKey` is required and is the query key to generate options for. + * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks See {@link useInfiniteQuery} for examples that fetch further pages (from a button click or + * automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set. + * @see {@link useInfiniteQuery} to run an infinite query with these options. + * @example + * A parameterized factory, so the same options object can be reused per `postId`: + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' + * + * export const commentsOptions = (postId: string) => + * infiniteQueryOptions({ + * queryKey: ['post', postId, 'comments'], + * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Comments({ postId }: { postId: string }) { + * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
    + * {data.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} + *
+ * ) + * } + * ``` + */ +export function infiniteQueryOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & + QueryKeyWithDataTag, TError> + +export function infiniteQueryOptions(options: unknown) { + return options +} diff --git a/packages/react-query-no-core-pluggable/src/mutationOptions.ts b/packages/react-query-no-core-pluggable/src/mutationOptions.ts new file mode 100644 index 00000000000..2c0de1da87c --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/mutationOptions.ts @@ -0,0 +1,92 @@ +import type { DefaultError, WithRequired } from './runtime/index' +import type { UseMutationOptions } from './types' + +/** + * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A + * `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with + * `useMutationState`. + * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a + * required `mutationKey`. + * @returns The same options object, unchanged. + * @see {@link useMutation} to run the mutation these options describe. + * @example + * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator: + * ```tsx + * import { mutationOptions, useMutationState } from '@tanstack/react-query-no-core-pluggable' + * + * const createPostOptions = mutationOptions({ + * mutationKey: ['posts', 'create'], + * mutationFn: createPost, + * }) + * + * function SavingIndicator() { + * const isCreatingPost = useMutationState({ + * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' }, + * }).length > 0 + * + * return isCreatingPost ? Saving… : null + * } + * ``` + */ +export function mutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + options: WithRequired< + UseMutationOptions, + 'mutationKey' + >, +): WithRequired< + UseMutationOptions, + 'mutationKey' +> +/** + * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No + * `mutationKey` is required on this overload — use this when you don't need to target the mutation via a + * `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters, + * such as `status`. + * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a + * `mutationKey`. + * @returns The same options object, unchanged. + * @remarks See the other overload's example for looking a mutation up via `useMutationState`. + * @see {@link useMutation} to run the mutation these options describe. + * @example + * ```tsx + * import { mutationOptions, useMutation } from '@tanstack/react-query-no-core-pluggable' + * + * export const createPostOptions = mutationOptions({ + * mutationFn: createPost, + * }) + * + * function CreatePost() { + * const mutation = useMutation(createPostOptions) + * return + * } + * ``` + */ +export function mutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + options: Omit< + UseMutationOptions, + 'mutationKey' + >, +): Omit< + UseMutationOptions, + 'mutationKey' +> +export function mutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + options: UseMutationOptions, +): UseMutationOptions { + return options +} diff --git a/packages/react-query-no-core-pluggable/src/queryOptions.ts b/packages/react-query-no-core-pluggable/src/queryOptions.ts new file mode 100644 index 00000000000..5b83a81c36c --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/queryOptions.ts @@ -0,0 +1,242 @@ +import type { + DefaultError, + DefaultQueryFn, + InitialDataFunction, + NonUndefinedGuard, + OmitKeyof, + QueryFunction, + QueryKey, + QueryKeyWithDataTag, + SkipToken, +} from './runtime/index' +import type { UseQueryOptions } from './types' + +/** + * The options accepted by the `queryOptions` overload selected when `initialData` is omitted, may be + * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is + * `pending`. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export type UndefinedInitialDataOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = UseQueryOptions & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData?: + | undefined + | InitialDataFunction> + | NonUndefinedGuard +} + +/** + * The options accepted by the `queryOptions` overload selected when `queryFn` is not `skipToken` and + * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` — same as + * {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export type UnusedSkipTokenOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = OmitKeyof< + UseQueryOptions, + 'queryFn' +> & { + queryFn: Exclude< + UseQueryOptions['queryFn'], + SkipToken + > +} + +/** + * The options accepted by the `queryOptions` overload selected when `initialData` is known to be defined — + * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export type DefinedInitialDataOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = Omit, 'queryFn'> & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData: + | NonUndefinedGuard + | (() => NonUndefinedGuard) + queryFn: QueryFunction | DefaultQueryFn +} + +/** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * is the query key to generate options for. + * + * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never + * `undefined` (unless a `select` changes `TData` to include `undefined`). + * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-no-core-pluggable' + * + * export const postsOptions = queryOptions({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * initialData: [], + * }) + * + * function Posts() { + * // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, + * // so the list stays visible alongside the error. + * const { data, isError, error } = useQuery(postsOptions) + * + * return ( + *
+ * {isError ? Error: {error.message} : null} + *
    + * {data.map((post) =>
  • {post.title}
  • )} + *
+ *
+ * ) + * } + * ``` + */ +export function queryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: DefinedInitialDataOptions, +): DefinedInitialDataOptions & + QueryKeyWithDataTag + +/** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * is the query key to generate options for. + * @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `useQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * A parameterized factory, so the same options object can be reused per `id`: + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-no-core-pluggable' + * + * export const postOptions = (id: string) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function Post({ id }: { id: string }) { + * const { data, isPending, isError, error } = useQuery(postOptions(id)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data.title}

+ * } + * ``` + */ +export function queryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UnusedSkipTokenOptions, +): UnusedSkipTokenOptions & + QueryKeyWithDataTag + +/** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * is the query key to generate options for. + * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * A parameterized factory, so the same options object can be reused per `id`: + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-no-core-pluggable' + * + * export const postOptions = (id: string) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function Post({ id }: { id: string }) { + * const { data, isPending, isError, error } = useQuery(postOptions(id)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data.title}

+ * } + * ``` + * @example + * A factory that disables the query, type safe, until `postId` is set: + * ```tsx + * import { queryOptions, skipToken, useQuery } from '@tanstack/react-query-no-core-pluggable' + * + * export const postOptions = (postId: number | undefined) => + * queryOptions({ + * queryKey: ['post', postId], + * queryFn: postId != null ? () => fetchPost(postId) : skipToken, + * }) + * + * function Post({ postId }: { postId: number | undefined }) { + * const { data, isLoading, isError, error } = useQuery(postOptions(postId)) + * + * if (postId == null) return 'Select a post' + * if (isLoading) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data?.title}

+ * } + * ``` + */ +export function queryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UndefinedInitialDataOptions, +): UndefinedInitialDataOptions & + QueryKeyWithDataTag + +export function queryOptions(options: unknown) { + return options +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/clientFeatures.ts b/packages/react-query-no-core-pluggable/src/runtime/clientFeatures.ts new file mode 100644 index 00000000000..c2c84dc09fc --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/clientFeatures.ts @@ -0,0 +1,40 @@ +import type { infiniteQueryBehavior } from './infiniteQueryBehavior' +import type { Mutation } from './mutation' +import type { MutationCache } from './mutationCache' +import type { QueryClient } from './queryClient' +import type { QueryClientConfig } from './types' + +/** Optional implementations owned by one query client. */ +export interface QueryClientFeatures { + /** Cache and builder shared by mutation observers and hydration. */ + mutations?: { + cache: MutationCache + build: typeof Mutation.build + } + /** Creates the fetch behavior for a paginated query. */ + infiniteQueryBehavior?: typeof infiniteQueryBehavior +} + +/** Installs optional behavior for one client, including caches owned by that client. */ +export type QueryClientPlugin = ( + features: QueryClientFeatures, + config: Readonly, +) => void + +export const clientFeatures = Symbol('clientFeatures') + +/** + * Looks up the mutation implementation for an operation that requires it. + * @param client - Client receiving the operation. + * @returns The installed mutation cache and builder. + * @throws {Error} When mutation support is missing from the client. + */ +export function requireMutations(client: QueryClient) { + const mutations = client[clientFeatures].mutations + if (!mutations) { + throw new Error( + 'Add mutationPlugin to the QueryClient plugins to use mutations.', + ) + } + return mutations +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/environmentManager.ts b/packages/react-query-no-core-pluggable/src/runtime/environmentManager.ts new file mode 100644 index 00000000000..576fc540f60 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/environmentManager.ts @@ -0,0 +1,41 @@ +import type { IsServerValue } from '@tanstack/query-types/bindings' + +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/react-query-no-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 + }, +} + +export type { IsServerValue } from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core-pluggable/src/runtime/focusManager.ts b/packages/react-query-no-core-pluggable/src/runtime/focusManager.ts new file mode 100644 index 00000000000..f52a8b2d199 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/focusManager.ts @@ -0,0 +1,142 @@ +import { Subscribable } from './subscribable' +import type { + FocusManagerListener as Listener, + FocusManagerSetupFn as SetupFn, +} from '@tanstack/query-types/bindings' + +/** + * 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/react-query-no-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/react-query-no-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/react-query-no-core-pluggable/src/runtime/hydration.ts b/packages/react-query-no-core-pluggable/src/runtime/hydration.ts new file mode 100644 index 00000000000..a206200ef9d --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/hydration.ts @@ -0,0 +1,368 @@ +import { clientFeatures, requireMutations } from './clientFeatures' +import { noop } from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + DehydratedMutation, + DehydratedQuery, + DehydratedState, + TransformerFn, +} from '@tanstack/query-types/bindings' +import type { Mutation } from './mutation' +import type { Query } from './query' +import type { QueryClient } from './queryClient' +import type { QueryRuntime } from './runtimeBinding' + +/** + * 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 Promise | undefined + + // .catch can be unavailable on certain kinds of thenable's + // oxlint-disable-next-line typescript/no-unnecessary-condition + thenResult?.catch?.(noop) + + if (data !== undefined) { + return { data } + } + + return undefined +} + +export type DehydrateOptions = Shared.DehydrateOptions + +export type HydrateOptions = Shared.HydrateOptions + +// 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: mutation.options.scope }), + ...(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 queryClient.query({ + * queryKey: ['posts'], + * queryFn: getPosts, + * }) + * + * const dehydratedState = dehydrate(queryClient) + * ``` + */ +export function dehydrate( + client: QueryClient, + options: DehydrateOptions = {}, +): DehydratedState { + const filterMutation = + options.shouldDehydrateMutation ?? + client.getDefaultOptions().dehydrate?.shouldDehydrateMutation ?? + defaultShouldDehydrateMutation + + const mutations = ( + client[clientFeatures].mutations?.cache.getAll() ?? [] + ).flatMap((mutation) => + filterMutation(mutation) ? [dehydrateMutation(mutation)] : [], + ) + + const filterQuery = + options.shouldDehydrateQuery ?? + client.getDefaultOptions().dehydrate?.shouldDehydrateQuery ?? + defaultShouldDehydrateQuery + + const shouldRedactErrors = + options.shouldRedactErrors ?? + client.getDefaultOptions().dehydrate?.shouldRedactErrors + + const serializeData = + options.serializeData ?? client.getDefaultOptions().dehydrate?.serializeData + + const queries = client + .getQueryCache() + .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 { + const queryCache = client.getQueryCache() + const deserializeData = + options?.defaultOptions?.deserializeData ?? + client.getDefaultOptions().hydrate?.deserializeData + + dehydratedState.mutations?.forEach(({ state, ...mutationOptions }) => { + requireMutations(client).build( + client, + { + ...client.getDefaultOptions().hydrate?.mutations, + ...options?.defaultOptions?.mutations, + ...mutationOptions, + }, + state, + ) + }) + + dehydratedState.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, + { + ...client.getDefaultOptions().hydrate?.queries, + ...options?.defaultOptions?.queries, + queryKey, + queryHash, + meta, + _type: queryType, + }, + // 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) + } + }, + ) +} + +export type { DehydratedState } from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core-pluggable/src/runtime/index.ts b/packages/react-query-no-core-pluggable/src/runtime/index.ts new file mode 100644 index 00000000000..dc08eafed78 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/index.ts @@ -0,0 +1,169 @@ +/* istanbul ignore file */ + +export { mutationPlugin, infiniteQueryPlugin } from './plugins' +export type { QueryClientFeatures, QueryClientPlugin } from './clientFeatures' +export { focusManager } from './focusManager' +export type { FocusManager } from './focusManager' +export { environmentManager } from './environmentManager' +export { + defaultShouldDehydrateMutation, + defaultShouldDehydrateQuery, + dehydrate, + dehydrateQuery, + hydrate, +} from './hydration' +export { InfiniteQueryObserver } from './infiniteQueryObserver' +export { MutationCache } from './mutationCache' +export type { MutationCacheNotifyEvent } from './mutationCache' +export { MutationObserver } from './mutationObserver' +export { defaultScheduler, notifyManager } from './notifyManager' +export { onlineManager } from './onlineManager' +export type { OnlineManager } from './onlineManager' +export { QueriesObserver } from './queriesObserver' +export { QueryCache } from './queryCache' +export type { QueryCacheNotifyEvent } from './queryCache' +export { QueryClient } from './queryClient' +export { QueryObserver } from './queryObserver' +export type { QueryObserverResultReader } from './queryObserver' +export { CancelledError } from './retryer' +export { + timeoutManager, + type ManagedTimerId, + type TimeoutCallback, + type TimeoutManager, + type TimeoutProvider, +} from './timeoutManager' +export { + hashKey, + keepPreviousData, + matchMutation, + matchQuery, + noop, + partialMatchKey, + replaceEqualDeep, + shouldThrowError, + defaultQueryFn, + skipToken, +} from './utils' +export type { + DefaultQueryFn, + MutationFilters, + QueryFilters, + SkipToken, + Updater, +} from './utils' + +export { streamedQuery } from './streamedQuery' + +// Types +export type { + DehydratedState, + DehydrateOptions, + HydrateOptions, +} from './hydration' +export { Mutation } from './mutation' +export type { MutationState } from './mutation' +export type { MutationCacheConfig } from './mutationCache' +export type { + QueriesObserverOptions, + QueriesObserverResultReader, +} from './queriesObserver' +export { Query } from './query' +export type { QueryState } from './query' +export type { QueryCacheConfig } from './queryCache' +export { dataTagSymbol, dataTagErrorSymbol, unsetMarker } from './types' +export type { + NonUndefinedGuard, + DistributiveOmit, + OmitKeyof, + Override, + Register, + DefaultError, + QueryKey, + UnsetMarker, + AnyDataTag, + DataTag, + QueryKeyWithDataTag, + InferDataFromTag, + InferErrorFromTag, + QueryFunction, + StaleTime, + StaleTimeFunction, + QueryBooleanOption, + QueryPersister, + QueryFunctionContext, + InitialDataFunction, + PlaceholderDataFunction, + QueriesPlaceholderDataFunction, + EqualityFn, + CacheKeyHashFunction, + CacheKeyConfig, + GetPreviousPageParamFunction, + GetNextPageParamFunction, + InfiniteData, + QueryMeta, + NetworkMode, + NotifyOnChangeProps, + QueryOptions, + InitialPageParam, + InfiniteQueryPageParamsOptions, + ThrowOnError, + QueryObserverOptions, + WithRequired, + DefaultedQueryObserverOptions, + InfiniteQueryObserverOptions, + DefaultedInfiniteQueryObserverOptions, + QueryExecuteOptions, + InfiniteQueryExecuteOptions, + ResultOptions, + RefetchOptions, + InvalidateQueryFilters, + RefetchQueryFilters, + InvalidateOptions, + ResetOptions, + FetchNextPageOptions, + FetchPreviousPageOptions, + QueryStatus, + FetchStatus, + QueryObserverBaseResult, + QueryObserverPendingResult, + QueryObserverLoadingResult, + QueryObserverLoadingErrorResult, + QueryObserverRefetchErrorResult, + QueryObserverSuccessResult, + QueryObserverPlaceholderResult, + DefinedQueryObserverResult, + QueryObserverResult, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverPendingResult, + InfiniteQueryObserverLoadingResult, + InfiniteQueryObserverLoadingErrorResult, + InfiniteQueryObserverRefetchErrorResult, + InfiniteQueryObserverSuccessResult, + InfiniteQueryObserverPlaceholderResult, + DefinedInfiniteQueryObserverResult, + InfiniteQueryObserverResult, + MutationKey, + MutationStatus, + MutationScope, + MutationMeta, + MutationFunctionContext, + MutationFunction, + MutationOptions, + MutationObserverOptions, + MutateOptions, + MutateFunctionRest, + MutateFunction, + MutationObserverBaseResult, + MutationObserverIdleResult, + MutationObserverLoadingResult, + MutationObserverErrorResult, + MutationObserverSuccessResult, + MutationObserverResult, + QueryClientConfig, + DefaultOptions, + CancelOptions, + SetDataOptions, + NotifyEventType, + NotifyEvent, +} from './types' diff --git a/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryBehavior.ts b/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryBehavior.ts new file mode 100644 index 00000000000..ce7137c31b7 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryBehavior.ts @@ -0,0 +1,187 @@ +import { + addConsumeAwareSignal, + addToArray, + ensureQueryFn, + fetchSignal, +} from './utils' +import type { QueryBehavior } from './query' +import type { InfiniteData, InfiniteQueryPageParamsOptions } from './types' +import type { FetchSignalContext } from './utils' + +/** + * Creates the behavior that fetches the pages of an infinite query: the next or previous page for + * `fetchNextPage`/`fetchPreviousPage`, or all pages again from the start on a refetch. + * @param pages - The number of pages to fetch from the start when all pages are fetched again, + * e.g. from the `pages` option of `queryClient.infiniteQuery`. Defaults to the number of cached + * pages. + * @returns The query behavior to set on an infinite query. + */ +export function infiniteQueryBehavior( + pages?: number, +): QueryBehavior> { + return { + onFetch: (context, query) => { + const options = context.options as InfiniteQueryPageParamsOptions + 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 = 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) { + context.fetchFn = () => { + return context.options.persister?.( + fetchFn as any, + { + client: context.client, + queryKey: context.queryKey, + meta: context.options.meta, + signal: context.signal, + }, + query, + ) + } + } else { + context.fetchFn = 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 +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryObserver.ts b/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryObserver.ts new file mode 100644 index 00000000000..8fbd5546791 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryObserver.ts @@ -0,0 +1,277 @@ +import { hasNextPage, hasPreviousPage } from './infiniteQueryBehavior' +import { QueryObserver } from './queryObserver' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + InfiniteQueryObserverListener, + ReplaceReturnType, +} from '@tanstack/query-types/bindings' +import type { Query } from './query' +import type { QueryClient } from './queryClient' +import type { + QueryObserverResultContext, + QueryObserverResultReader, +} from './queryObserver' +import type { QueryRuntime } from './runtimeBinding' +import type { Subscribable } from './subscribable' +import type { + DefaultError, + DefaultedInfiniteQueryObserverOptions, + FetchNextPageOptions, + FetchPreviousPageOptions, + InfiniteData, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverResult, + QueryKey, + QueryObserverResult, +} from './types' + +type InfiniteObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, + TPageParam, +> = Shared.InfiniteObserverOptionsInput< + QueryRuntime, + 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`, and is the primitive that framework adapters (e.g. + * `useInfiniteQuery`) build their hooks on top of. + * @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 { + options._type = 'infinite' + super.setOptions(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({ + ...options, + _type: 'infinite', + }) 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' }, + }, + }) + } + + protected 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 { isFetching, isRefetching, isError, isRefetchError } = parentResult + const fetchDirection = state.fetchMeta?.fetchMore?.direction + + const isFetchNextPageError = isError && fetchDirection === 'forward' + const isFetchingNextPage = isFetching && fetchDirection === 'forward' + + const isFetchPreviousPageError = isError && fetchDirection === 'backward' + const isFetchingPreviousPage = isFetching && fetchDirection === 'backward' + + const result: InfiniteQueryObserverBaseResult = { + ...parentResult, + fetchNextPage: this.fetchNextPage, + fetchPreviousPage: this.fetchPreviousPage, + hasNextPage: hasNextPage(options, state.data), + hasPreviousPage: hasPreviousPage(options, state.data), + isFetchNextPageError, + isFetchingNextPage, + isFetchPreviousPageError, + isFetchingPreviousPage, + isRefetchError: + isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError, + isRefetching: + isRefetching && !isFetchingNextPage && !isFetchingPreviousPage, + } + + return result as InfiniteQueryObserverResult + } +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/mutation.ts b/packages/react-query-no-core-pluggable/src/runtime/mutation.ts new file mode 100644 index 00000000000..79a3c27bf95 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/mutation.ts @@ -0,0 +1,503 @@ +import { notifyManager } from './notifyManager' +import { Removable } from './removable' +import { createRetryer } from './retryer' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + MutationAction as Action, + MutationState, +} from '@tanstack/query-types/bindings' +import type { MutationCache } from './mutationCache' +import type { MutationObserver } from './mutationObserver' +import type { QueryClient } from './queryClient' +import type { Retryer } from './retryer' +import type { QueryRuntime } from './runtimeBinding' +import type { + DefaultError, + MutationFunctionContext, + MutationMeta, + MutationOptions, +} from './types' + +type MutationConfig = + Shared.MutationConfig< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult + > + +// 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 = queryClient.getMutationCache() + * + * 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 = client.getMutationCache() + return cache.register( + (mutationId) => + new Mutation({ + client, + mutationCache: cache, + mutationId, + options: client.defaultMutationOptions(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.setOptions(config.options) + this.scheduleGc() + } + + /** + * Replaces the mutation's options and applies their `gcTime`. + * @internal + * @param options - The new mutation options. + */ + setOptions( + options: MutationOptions, + ): void { + this.options = options + + this.updateGcTime(this.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. queryClient.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, + } +} + +export type { + MutationState, + MutationAction as Action, +} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts b/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts new file mode 100644 index 00000000000..5ebdcc079d7 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts @@ -0,0 +1,270 @@ +import { notifyManager } from './notifyManager' +import { Subscribable } from './subscribable' +import { matchMutation, noop } from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { Mutation } from './mutation' +import type { QueryRuntime } from './runtimeBinding' +import type { DefaultError } from './types' +import type { MutationFilters } from './utils' + +export type MutationCacheConfig = Shared.MutationCacheConfig + +export type MutationCacheNotifyEvent = + Shared.MutationCacheNotifyEvent + +type MutationCacheListener = Shared.MutationCacheListener + +// CLASS + +/** + * The `MutationCache` is the storage for mutations. + * + * Normally, you will not interact with the `MutationCache` directly and instead use a + * `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of + * safe/known updates to the cache, such as mutations being added, removed, or updated. + * @example + * ```ts + * const unsubscribe = mutationCache.subscribe((event) => { + * console.log(event.type, event.mutation) + * }) + * ``` + */ +export class MutationCache extends Subscribable { + #mutations: Set> + #scopes: Map>> + #mutationId: number + + constructor(public config: MutationCacheConfig = {}) { + super() + this.#mutations = new Set() + this.#scopes = new Map() + 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) + const scope = scopeFor(mutation) + if (typeof scope === 'string') { + const scopedMutations = this.#scopes.get(scope) + if (scopedMutations) { + scopedMutations.push(mutation) + } else { + this.#scopes.set(scope, [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() + const scope = scopeFor(mutation) + const scopedMutations = this.#scopes.get(scope) + if (scopedMutations) { + const index = scopedMutations.indexOf(mutation) + if (index !== -1) { + scopedMutations.splice(index, 1) + if (!scopedMutations.length) { + this.#scopes.delete(scope) + } + } + } + } + + // 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 { + const firstPendingMutation = this.#scopes + .get(scopeFor(mutation)) + ?.find((candidate) => candidate.state.status === 'pending') + return !firstPendingMutation || firstPendingMutation === mutation + } + + /** + * 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 { + const next = this.#scopes + .get(scopeFor(mutation)) + ?.find((entry) => entry !== mutation && entry.state.isPaused) + + return next?.continue() ?? Promise.resolve() + } + + /** + * Removes all mutations and clears their garbage collection timers. + * Mutations that are already running continue to execute. + * @example + * ```ts + * const mutationCache = queryClient.getMutationCache() + * + * mutationCache.clear() + * ``` + */ + clear(): void { + notifyManager.batch(() => { + const mutations = this.getAll() + this.#mutations.clear() + this.#scopes.clear() + mutations.forEach((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 = queryClient.getMutationCache() + * + * 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 = queryClient.getMutationCache() + * + * 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 = queryClient.getMutationCache() + * + * 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)), + ), + ) + } +} + +/** + * Returns the scope id of a mutation, used to run mutations with the same scope one after another. + * @param mutation - The mutation to read the scope of. + * @returns The mutation's `scope.id`, or `undefined` if it has no scope. + */ +function scopeFor(mutation: Mutation) { + return mutation.options.scope?.id +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/mutationObserver.ts b/packages/react-query-no-core-pluggable/src/runtime/mutationObserver.ts new file mode 100644 index 00000000000..a27291779f6 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/mutationObserver.ts @@ -0,0 +1,335 @@ +import { requireMutations } from './clientFeatures' +import { getDefaultState } from './mutation' +import { notifyManager } from './notifyManager' +import { Subscribable } from './subscribable' +import { hashKeyByOptions, shallowEqualObjects } from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { Action, Mutation } from './mutation' +import type { QueryClient } from './queryClient' +import type { QueryRuntime } from './runtimeBinding' +import type { + DefaultError, + MutateOptions, + MutationFunctionContext, + MutationObserverOptions, + MutationObserverResult, +} from './types' + +type MutationObserverListener = + Shared.MutationObserverListener< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult + > + +// 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 + * QueryClient#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 = this.#client.defaultMutationOptions(options) + if (!shallowEqualObjects(this.options, prevOptions)) { + this.#client.getMutationCache().notify({ + type: 'observerOptionsUpdated', + mutation: this.#currentMutation, + observer: this, + }) + } + + if ( + prevOptions?.mutationKey && + this.options.mutationKey && + hashKeyByOptions( + prevOptions.mutationKey, + this.#client.getMutationCache().config.mutationKey, + ) !== + hashKeyByOptions( + this.options.mutationKey, + this.#client.getMutationCache().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 = requireMutations(this.#client).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/react-query-no-core-pluggable/src/runtime/notifyManager.ts b/packages/react-query-no-core-pluggable/src/runtime/notifyManager.ts new file mode 100644 index 00000000000..aaac1276c0d --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/notifyManager.ts @@ -0,0 +1,148 @@ +import type { + BatchCallsCallback, + BatchNotifyFunction, + NotifyCallback, + NotifyFunction, + ScheduleFunction, +} from '@tanstack/query-types/bindings' + +/** + * 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 batchNotifyFn: BatchNotifyFunction = (callback: () => void) => { + 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(() => { + batchNotifyFn(() => { + 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 + }, + /** + * Use this method to set a custom function to batch notifications together into a single tick. + * Framework adapters use this to plug in their own batching primitive, so that a single query + * update only triggers one re-render instead of one per subscriber. + * @param fn - Receives a function that runs a batch of notifications and must call it. + * @example + * ```ts + * import { notifyManager } from '@tanstack/react-query-no-core-pluggable' + * import { batch } from 'solid-js' + * + * notifyManager.setBatchNotifyFunction(batch) + * ``` + */ + setBatchNotifyFunction: (fn: BatchNotifyFunction) => { + batchNotifyFn = 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/react-query-no-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/react-query-no-core-pluggable/src/runtime/onlineManager.ts b/packages/react-query-no-core-pluggable/src/runtime/onlineManager.ts new file mode 100644 index 00000000000..aaa6b7ec96f --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/onlineManager.ts @@ -0,0 +1,120 @@ +import { Subscribable } from './subscribable' +import type { + OnlineManagerListener as Listener, + OnlineManagerSetupFn as SetupFn, +} from '@tanstack/query-types/bindings' + +/** + * 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/react-query-no-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/react-query-no-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/react-query-no-core-pluggable/src/runtime/plugins.ts b/packages/react-query-no-core-pluggable/src/runtime/plugins.ts new file mode 100644 index 00000000000..05a8f7ee7cd --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/plugins.ts @@ -0,0 +1,24 @@ +import { infiniteQueryBehavior } from './infiniteQueryBehavior' +import { Mutation } from './mutation' +import { MutationCache } from './mutationCache' +import type { QueryClientPlugin } from './clientFeatures' + +/** + * Enables mutation observers, caching and hydration on one client. + * @param features - The features being configured for this client. + * @param config - Client options, including any supplied mutation cache. + */ +export const mutationPlugin: QueryClientPlugin = (features, config) => { + features.mutations = { + cache: config.mutationCache ?? new MutationCache(), + build: Mutation.build, + } +} + +/** + * Enables page fetching for infinite queries on one client. + * @param features - The features being configured for this client. + */ +export const infiniteQueryPlugin: QueryClientPlugin = (features) => { + features.infiniteQueryBehavior = infiniteQueryBehavior +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/queriesObserver.ts b/packages/react-query-no-core-pluggable/src/runtime/queriesObserver.ts new file mode 100644 index 00000000000..1a9392c5ca5 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/queriesObserver.ts @@ -0,0 +1,468 @@ +import { notifyManager } from './notifyManager' +import { QueryObserver } from './queryObserver' +import { Subscribable } from './subscribable' +import { + replaceEqualDeep, + shallowEqualObjects, + shouldThrowError, +} from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + CombineContext, + CombineFn, + QueriesObserverListener, + QueriesObserverOptions, + QueriesObserverResultReader, +} from '@tanstack/query-types/bindings' +import type { QueryClient } from './queryClient' +import type { ObserverOptionsInput } from './queryObserver' +import type { QueryRuntime } from './runtimeBinding' +import type { QueryObserverResult } from './types' + +/** + * 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 `Query` instances currently being observed, in + * the same order as the queries passed to the constructor or `setQueries`. + * @returns The observed queries. + */ + getQueries() { + return this.#observers.map((observer) => observer.getCurrentQuery()) + } + + /** + * 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, + ): QueriesObserverResultReader { + const matches = this.#findMatchingObservers(queries).map((match) => ({ + ...match, + reader: match.observer.createResultReader(match.defaultedQueryOptions), + })) + const queryHashes = matches.map( + (match) => match.defaultedQueryOptions.queryHash, + ) + const combine = options?.combine + const context = { ...this.#combineContext } + let result = this.#result + + const getSnapshot = () => { + const nextResult = matches.map((match) => match.reader.getSnapshot()) + if (!shallowEqualObjects(nextResult, result)) { + result = nextResult + } + return result + } + + return { + getSnapshot, + combineResult: (input) => { + // Notifications may have already combined these results. + const committed = this.#combineContext + if ( + committed.combine === combine && + equalResults(input, committed.result) && + shallowEqualObjects(queryHashes, committed.queryHashes) + ) { + Object.assign(context, committed) + } + return this.#combineResult( + this.#trackResult(input, matches), + combine, + queryHashes, + context, + input, + ) + }, + commit: () => { + this.#combineContext = { ...context } + this.#setQueries(matches, { combine }) + if ( + this.#options?.combine === combine && + equalResults(this.#result, context.result) + ) { + this.#combinedResult = context.value + } + }, + } + } + + #trackResult( + result: Array, + matches: Array, + ) { + const trackedProps = new Set() + + return matches.map((match, index) => { + const observerResult = result[index]! + return !match.defaultedQueryOptions.notifyOnChangeProps + ? match.observer.trackResult(observerResult, (accessedProp) => { + // track property on all observers to ensure proper (synchronized) tracking (#7000) + if (!trackedProps.has(accessedProp)) { + trackedProps.add(accessedProp) + matches.forEach((m) => { + m.observer.trackProp(accessedProp) + }) + } + }) + : observerResult + }) + } + + #combineResult( + input: Array, + combine: CombineFn | undefined, + queryHashes?: Array, + context = this.#combineContext, + result = this.#result, + ): TCombinedResult { + if (combine) { + const queryHashesChanged = + queryHashes !== undefined && + context.queryHashes !== undefined && + !shallowEqualObjects(queryHashes, context.queryHashes) + + if ( + !equalResults(result, context.result) || + queryHashesChanged || + combine !== context.combine + ) { + context.value = replaceEqualDeep(context.value, combine(input)) + context.combine = combine + context.result = result + if (queryHashes !== undefined) { + context.queryHashes = queryHashes + } + } + + return context.value as TCombinedResult + } + return input as any + } + + #shouldSkipCombine(): boolean { + return ( + !this.#options?.combine || + this.#observers.some((observer, index) => { + const result = this.#result[index] + return ( + (observer.options.suspense && result?.data === undefined) || + (!!result?.isError && + !result.isFetching && + shouldThrowError(observer.options.throwOnError, [ + result.error, + observer.getCurrentQuery(), + ])) + ) + }) + ) + } + + #findMatchingObservers( + queries: Array, + ): Array { + const prevObserversMap = new Map>() + + this.#observers.forEach((observer) => { + const key = observer.options.queryHash + if (!key) return + + const previousObservers = prevObserversMap.get(key) + + if (previousObservers) { + previousObservers.push(observer) + } else { + prevObserversMap.set(key, [observer]) + } + }) + + const observers: Array = [] + + queries.forEach((options) => { + const defaultedOptions = this.#client.defaultQueryOptions(options) + const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift() + const observer = + match ?? new QueryObserver(this.#client, defaultedOptions) + + observers.push({ + defaultedQueryOptions: defaultedOptions, + observer, + }) + }) + + return observers + } + + #subscribeTo(observer: QueryObserver): void { + // Create the listener here, not in `setQueries`: a listener created there + // keeps the previous observers, and their queries, alive (#12656) + observer.subscribe((result) => { + this.#onUpdate(observer, result) + }) + } + + #onUpdate(observer: QueryObserver, result: QueryObserverResult): void { + if (this.#updatingQueries) return + + const index = this.#observers.indexOf(observer) + if (index !== -1) { + this.#result = this.#result.slice() + this.#result[index] = result + this.#notify() + } + } + + #notify(): void { + if (this.hasListeners()) { + const shouldSkipCombine = this.#shouldSkipCombine() + const previousResult = this.#combinedResult + const newResult = shouldSkipCombine + ? previousResult + : this.#combineResult( + this.#trackResult(this.#result, this.#observerMatches), + this.#options?.combine, + this.#observerMatches.map( + (match) => match.defaultedQueryOptions.queryHash, + ), + ) + + this.#combinedResult = newResult + if (shouldSkipCombine || previousResult !== newResult) { + notifyManager.batch(() => { + this.listeners.forEach((listener) => { + listener(this.#result) + }) + }) + } + } + } +} + +type QueryObserverMatch = Shared.QueryObserverMatch + +export type { + QueriesObserverResultReader, + QueriesObserverOptions, +} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core-pluggable/src/runtime/query.ts b/packages/react-query-no-core-pluggable/src/runtime/query.ts new file mode 100644 index 00000000000..279f2679e3d --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/query.ts @@ -0,0 +1,878 @@ +import { clientFeatures } from './clientFeatures' +import { notifyManager } from './notifyManager' +import { Removable } from './removable' +import { CancelledError, canFetch, createRetryer } from './retryer' +import { + ensureQueryFn, + fetchSignal, + noop, + replaceData, + resolveQueryValue, + skipToken, + timeUntilStale, +} from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + FetchOptions, + QueryAction as Action, + QueryState, +} from '@tanstack/query-types/bindings' +import type { QueryClientFeatures } from './clientFeatures' +import type { QueryCache } from './queryCache' +import type { QueryClient } from './queryClient' +import type { QueryObserver } from './queryObserver' +import type { Retryer } from './retryer' +import type { QueryRuntime } from './runtimeBinding' +import type { + CancelOptions, + DefaultError, + InitialDataFunction, + QueryKey, + QueryMeta, + QueryOptions, + SetDataOptions, + StaleTime, +} from './types' + +type QueryConfig< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey = QueryKey, +> = Shared.QueryConfig + +export type FetchContext< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey = QueryKey, +> = Shared.FetchContext + +export type QueryBehavior< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = Shared.QueryBehavior + +// CLASS + +/** + * Represents a single cached query. A `Query` holds the query's key, options, + * state (data/error/status), and the observers currently subscribed to it. + * + * Instances are created and managed internally by `QueryCache`; application + * code typically interacts with queries indirectly through `QueryClient` or + * a framework hook like `useQuery`. Direct access to a `Query` instance is + * possible via `queryCache.find()`/`findAll()` for inspecting cache state. + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * const query = queryCache.find({ queryKey: ['posts'] }) + * + * if (query) { + * console.log(query.state.dataUpdatedAt) + * } + * ``` + */ +export class Query< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends Removable { + queryKey: TQueryKey + queryHash: string + options!: QueryOptions + state: QueryState + #infiniteQueryBehavior?: QueryClientFeatures['infiniteQueryBehavior'] + + #initialState: QueryState + #revertState?: QueryState + #cache: QueryCache + #client: QueryClient + #retryer?: Retryer + #fetchPromise?: Promise + observers: Array> + #defaultOptions?: QueryOptions + #abortSignalConsumed: boolean + + constructor(config: QueryConfig) { + super() + + this.#abortSignalConsumed = false + this.#defaultOptions = config.defaultOptions + this.#client = config.client + this.setOptions(config.options) + this.observers = [] + this.#cache = this.#client.getQueryCache() + this.queryKey = config.queryKey + this.queryHash = config.queryHash + this.#initialState = getDefaultState(this.options) + this.state = config.state ?? this.#initialState + this.scheduleGc() + } + /** + * The `meta` object passed in the query's options, if any. + * @returns The query's `meta`, or `undefined` if none was set. + */ + get meta(): QueryMeta | undefined { + return this.options.meta + } + + /** + * `'infinite'` for an infinite query, otherwise `undefined`. + * @internal + * @returns The type of the query, set from the `_type` option (e.g. `'infinite'`). + */ + get queryType(): 'infinite' | undefined { + return this.#infiniteQueryBehavior ? 'infinite' : undefined + } + + /** + * The promise for the currently in-flight fetch, if the query is fetching. + * `undefined` when the query is not fetching. + * @returns The promise of the in-flight fetch, or `undefined`. + */ + get promise(): Promise | undefined { + return this.#retryer?.promise + } + + /** + * Replaces the query's options and applies their `gcTime`. If the query has no data yet, it gets + * the `initialData` from the new options, if any. + * @internal + * @param options - The new query options, merged on top of the query's default options. + * @throws {Error} When an infinite query is used without `infiniteQueryPlugin`. + */ + setOptions( + options?: QueryOptions, + ): void { + if (options?._type === 'infinite') { + const behavior = this.#client[clientFeatures].infiniteQueryBehavior + if (!behavior) { + throw new Error( + 'Add infiniteQueryPlugin to the QueryClient plugins to use infinite queries.', + ) + } + this.#infiniteQueryBehavior = behavior + } + this.options = { ...this.#defaultOptions, ...options } + + this.updateGcTime(this.options.gcTime) + + // oxlint-disable-next-line typescript/no-unnecessary-condition -- the constructor calls 'setOptions' before it assigns 'state' + if (this.state && this.state.data === undefined) { + const defaultState = getDefaultState(this.options) + if (defaultState.data !== undefined) { + this.setState( + successState(defaultState.data, defaultState.dataUpdatedAt), + ) + this.#initialState = defaultState + } + } + } + + protected override optionalRemove() { + if (!this.observers.length && this.state.fetchStatus === 'idle') { + this.#cache.remove(this) + } + } + + /** + * Writes new data to the query and marks it as successfully fetched. + * @internal + * @param newData - The data to write. Structural sharing with the current data is applied. + * @param options - Set `updatedAt` to override the timestamp, and `manual` to mark the write as + * manual (e.g. from `queryClient.setQueryData`). + * @returns The data that was written. + */ + setData( + newData: TData, + options?: SetDataOptions & { manual: boolean }, + ): TData { + const data = replaceData(this.state.data, newData, this.options) + + const manual = options?.manual + const dataUpdatedAt = options?.updatedAt + this.state = { + ...this.state, + ...successState(data, dataUpdatedAt), + dataUpdateCount: this.state.dataUpdateCount + 1, + ...(!manual && { + fetchStatus: 'idle' as const, + fetchFailureCount: 0, + fetchFailureReason: null, + }), + } + // A manual write becomes the snapshot to restore if a fetch is cancelled. + this.#revertState = manual ? this.state : undefined + this.#notify({ type: 'success', data, dataUpdatedAt, manual }) + + return data + } + + /** + * Merges the given partial state directly into this query's state, notifying observers. Used + * by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a + * user manually trigger a loading/error state or edit the cached data. + * @param state - The partial state to merge into the query's state. + */ + setState(state: Partial>): void { + this.#update(state, { type: 'setState', state }) + } + + /** + * Cancels the query's currently in-flight fetch, if any. + * - Returns a promise that resolves once the cancellation has settled. + * - If no fetch is in progress, resolves immediately. + * @param options - Set `revert` to restore the state from before the fetch started, and `silent` + * to suppress the cancellation error when a new fetch replaces the cancelled one. + * @returns A promise that resolves once the cancellation has settled. + * @example + * ```ts + * await query.cancel() + * ``` + */ + cancel(options?: CancelOptions): Promise { + const promise = this.#retryer?.promise + this.#retryer?.cancel(options) + return promise ? promise.then(noop, noop) : Promise.resolve() + } + + /** + * Silently cancels any in-flight fetch, then clears the query's garbage + * collection timeout. Called by `QueryCache` when the query is removed from + * the cache. + * @see {@link Query#cancel} + */ + override destroy(): void { + this.cancel({ silent: true }) + // An abort listener can unsubscribe and schedule GC during cancellation. + super.destroy() + } + + /** + * The state the query was created with. + * @internal + * @returns The state the query had when it was first created, used by {@link Query#reset}. + */ + get resetState(): QueryState { + return this.#initialState + } + + /** + * Resets the query back to its initial state (the state it had when it was + * first created, e.g. any `initialData`), destroying it first to cancel any + * in-flight fetch. + */ + reset(): void { + this.destroy() + this.setState(this.resetState) + } + + /** + * Returns `true` if the query has at least one observer for which `enabled` + * does not resolve to `false`. + * @returns `true` if the query has an enabled observer. + */ + isActive(): boolean { + return this.observers.some( + (observer) => resolveQueryValue(observer.options.enabled, this) !== false, + ) + } + + /** + * Returns `true` if the query is disabled, meaning it will not fetch + * automatically. + * - If the query has observers, it is disabled when none of them are active + * (see `isActive`). + * - If the query has no observers, it is disabled when its `queryFn` is + * `skipToken` or it has never been fetched. + * @returns `true` if the query is disabled. + */ + isDisabled(): boolean { + if (this.getObserversCount() > 0) { + return !this.isActive() + } + // if a query has no observers, it should still be considered disabled if it never attempted a fetch + return this.options.queryFn === skipToken || !this.isFetched() + } + + /** + * Returns `true` if the query has been fetched, i.e. it has resolved with + * either data or an error at least once. + * @returns `true` if the query has been fetched. + */ + isFetched() { + return this.state.dataUpdateCount + this.state.errorUpdateCount > 0 + } + + /** + * Returns `true` if the query has data and at least one observer configured with + * `staleTime: 'static'`, meaning it is treated as never stale. + * @returns `true` if the query is static. + */ + isStatic(): boolean { + if (this.state.data === undefined) { + return false + } + + if (this.getObserversCount() > 0) { + return this.observers.some( + (observer) => + resolveQueryValue(observer.options.staleTime, this) === 'static', + ) + } + + return false + } + + /** + * Returns `true` if the query is stale. + * - If the query has observers, defers to whether any observer's current + * result reports `isStale` (which accounts for each observer's own + * `staleTime` and `enabled` state). + * - If the query has no observers, it is considered stale when it has no + * data or has been invalidated. + * @returns `true` if the query is stale. + * @see {@link Query#isStaleByTime} + * @example + * ```ts + * if (query.isStale()) { + * // refetch or otherwise treat the cached data as outdated + * } + * ``` + */ + isStale(): boolean { + // check observers first, their `isStale` has the source of truth + // calculated with `isStaleByTime` and it takes `enabled` into account + if (this.getObserversCount() > 0) { + return this.observers.some( + (observer) => observer.getCurrentResult().isStale, + ) + } + + return this.state.data === undefined || this.state.isInvalidated + } + + /** + * Returns `true` if the query's data is stale relative to the given + * `staleTime` (defaults to `0`). + * - A query with no data is always stale. + * - `staleTime: 'static'` is never stale. + * - An invalidated query is always stale. + * - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`. + * @param staleTime - The time, in milliseconds, after which data is considered stale, or + * `'static'` to never treat existing data as stale. A query without data is stale either way. + * @returns `true` if the query's data is stale. + * @see {@link Query#isStale} + * @example + * ```ts + * const isStale = query.isStaleByTime(60 * 1000) + * ``` + */ + isStaleByTime(staleTime: StaleTime = 0): boolean { + // no data is always stale + if (this.state.data === undefined) { + return true + } + // static is never stale + if (staleTime === 'static') { + return false + } + // if the query is invalidated, it is stale + if (this.state.isInvalidated) { + return true + } + + return !timeUntilStale(this.state.dataUpdatedAt, staleTime) + } + + /** + * Refetches the query when the window regains focus, if an observer wants that, and continues a + * paused fetch. + * @internal + */ + onFocus(): void { + const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus()) + + observer?.refetch({ cancelRefetch: false }) + + // Continue fetch if currently paused + this.#retryer?.continue() + } + + /** + * Refetches the query when the app reconnects, if an observer wants that, and continues a paused + * fetch. + * @internal + */ + onOnline(): void { + const observer = this.observers.find((x) => x.shouldFetchOnReconnect()) + + observer?.refetch({ cancelRefetch: false }) + + // Continue fetch if currently paused + this.#retryer?.continue() + } + + /** + * Subscribes an observer to the query and stops its garbage collection. + * @internal + * @param observer - The observer to add. Adding an observer that is already subscribed does + * nothing. + */ + addObserver(observer: QueryObserver): void { + if (!this.observers.includes(observer)) { + this.observers.push(observer) + + // Stop the query from being garbage collected + this.clearGcTimeout() + + this.#cache.notify({ type: 'observerAdded', query: this, observer }) + } + } + + /** + * Unsubscribes an observer from the query. + * @internal + * @param observer - The observer to remove. When the last observer is removed, the in-flight + * fetch is cancelled if its abort signal was consumed (otherwise only its retries are stopped), + * and garbage collection is scheduled if the query is still in the cache. + */ + removeObserver(observer: QueryObserver): void { + const index = this.observers.indexOf(observer) + if (index !== -1) { + this.observers.splice(index, 1) + + if (!this.observers.length) { + // If the transport layer does not support cancellation + // we'll let the query continue so the result can be cached + if (this.#retryer) { + if ( + this.#abortSignalConsumed || + (this.state.fetchStatus === 'paused' && + this.state.status === 'pending') + ) { + this.#retryer.cancel({ revert: true }) + } else { + this.#retryer.cancelRetry() + } + } + + this.#scheduleGcIfCached() + } + + this.#cache.notify({ type: 'observerRemoved', query: this, observer }) + } + } + + /** + * Returns the number of observers currently subscribed to this query. + * @returns The number of observers. + * @example + * ```ts + * if (query.getObserversCount() === 0) { + * // no component is currently watching this query + * } + * ``` + */ + getObserversCount(): number { + return this.observers.length + } + + /** + * Marks the query as invalidated, unless it is already invalidated. This + * updates `state.isInvalidated` and notifies observers, but does not by + * itself trigger a refetch. + * @example + * ```ts + * query.invalidate() + * ``` + */ + invalidate(): void { + if (!this.state.isInvalidated) { + this.#update({ isInvalidated: true }, { type: 'invalidate' }) + } + } + + /** + * Fetches the query, i.e. runs its `queryFn` (through any configured + * retryer/behavior) and updates the query's state with the result. + * - If a fetch is already in flight, returns its promise instead of + * starting a new one, unless `fetchOptions.cancelRefetch` is set and the + * query already has data, in which case the current fetch is silently + * cancelled first. + * - If `options` is passed, it replaces the query's current options + * before fetching. + * @param options - Query options that replace the query's current options before fetching. They + * are not applied when an in-flight fetch is reused. + * @param fetchOptions - Set `cancelRefetch` to cancel an in-flight fetch first (only if the query + * already has data), and `meta` to pass extra information to the query's behavior. + * @returns A promise that resolves with the fetched data, or rejects with the fetch error. If the + * fetch is cancelled with `revert` while the query has data, it resolves with the restored data + * instead. + */ + async fetch( + options?: QueryOptions, + fetchOptions?: FetchOptions, + ): Promise { + if ( + this.state.fetchStatus !== 'idle' && + // If the promise in the retryer is already rejected, we have to definitely + // re-start the fetch; there is a chance that the query is still in a + // pending state when that happens + this.#retryer?.status() !== 'rejected' + ) { + if (this.state.data !== undefined && fetchOptions?.cancelRefetch) { + // Silently cancel current fetch if the user wants to cancel refetch + this.cancel({ silent: true }) + } else if (this.#retryer && this.#fetchPromise) { + // make sure that retries that were potentially cancelled due to unmounts can continue + this.#retryer.continueRetry() + // Return current promise if we are already fetching + return this.#fetchPromise + } + } + + // Update config if passed, otherwise the config from the last execution is used + if (options) { + this.setOptions(options) + } + + // Use the options from the first observer with a query function if no function is found. + // This can happen when the query is hydrated or created with setQueryData. + if (!this.options.queryFn) { + const observer = this.observers.find((x) => x.options.queryFn) + if (observer) { + this.setOptions(observer.options) + } + } + + if (process.env.NODE_ENV !== 'production') { + if (!Array.isArray(this.options.queryKey)) { + console.error( + `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`, + ) + } + } + + const abortController = new AbortController() + + const addSignalProperty: ( + object: object, + ) => asserts object is { signal: AbortSignal } = (object) => { + Object.defineProperties(object, { + [fetchSignal]: { value: abortController.signal, enumerable: true }, + signal: { + enumerable: true, + get: () => { + this.#abortSignalConsumed = true + return abortController.signal + }, + }, + }) + } + + // Create fetch function + const fetchFn = () => { + const queryFn = ensureQueryFn(this.options, fetchOptions) + + const queryFnContext = { + client: this.#client, + queryKey: this.queryKey, + meta: this.meta, + } + addSignalProperty(queryFnContext) + + this.#abortSignalConsumed = false + if (this.options.persister) { + return this.options.persister( + queryFn, + queryFnContext, + this as unknown as Query, + ) + } + + return queryFn(queryFnContext) + } + + // Trigger behavior hook + const context = { + fetchOptions, + options: this.options, + queryKey: this.queryKey, + client: this.#client, + state: this.state, + fetchFn, + } + if (this.#infiniteQueryBehavior) { + addSignalProperty(context) + const behavior = this.#infiniteQueryBehavior( + (this.options as { pages?: number }).pages, + ) as QueryBehavior + behavior.onFetch(context, this as unknown as Query) + } + + // Store state in case the current fetch needs to be reverted + this.#revertState = this.state + + // Set to fetching state if not already in it + if ( + this.state.fetchStatus === 'idle' || + this.state.fetchMeta !== context.fetchOptions?.meta + ) { + const meta = context.fetchOptions?.meta + this.#update( + { + ...fetchState(this.state.data, this.options), + fetchMeta: meta ?? null, + }, + { type: 'fetch', meta }, + ) + } + + // Try to fetch the data + const retryer = (this.#retryer = createRetryer({ + initialPromise: fetchOptions?.initialPromise as + | Promise + | undefined, + fn: context.fetchFn as () => Promise, + onCancel: (error) => { + if (error instanceof CancelledError && error.revert) { + this.setState({ + ...this.#revertState, + fetchStatus: 'idle' as const, + }) + } + abortController.abort() + }, + onFail: (failureCount, error) => { + this.#update( + { fetchFailureCount: failureCount, fetchFailureReason: error }, + { type: 'failed', failureCount, error }, + ) + }, + onPause: () => { + this.#update({ fetchStatus: 'paused' }, { type: 'pause' }) + }, + onContinue: () => { + this.#update({ fetchStatus: 'fetching' }, { type: 'continue' }) + }, + retry: context.options.retry, + retryDelay: context.options.retryDelay, + networkMode: context.options.networkMode, + canRun: () => true, + })) + + const fetchPromise = (async () => { + try { + const data = await retryer.promise + // this is more of a runtime guard + if (data === undefined) { + if (process.env.NODE_ENV !== 'production') { + console.error( + `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`, + ) + } + throw new Error(`${this.queryHash} data is undefined`) + } + + this.setData(data) + + // Notify cache callback + this.#cache.config.onSuccess?.(data, this as Query) + this.#cache.config.onSettled?.( + data, + this.state.error as any, + this as Query, + ) + return data + } catch (error) { + if (error instanceof CancelledError) { + if (error.silent) { + if (this.#retryer !== retryer && this.#fetchPromise) { + // A new fetch replaced the silently cancelled one, + // so we piggyback onto that promise. + return this.#fetchPromise + } + throw error + } else if (error.revert) { + // transform error into reverted state data + // if the initial fetch was cancelled, we have no data, so we have + // to get reject with a CancelledError + if (this.state.data === undefined) { + throw error + } + return this.state.data + } + } + const fetchError = error as TError + this.#update( + { + error: fetchError, + errorUpdatedAt: Date.now(), + errorUpdateCount: this.state.errorUpdateCount + 1, + fetchFailureCount: this.state.fetchFailureCount + 1, + fetchFailureReason: fetchError, + fetchStatus: 'idle', + status: 'error', + isInvalidated: true, + }, + { type: 'error', error: fetchError }, + ) + + // Notify cache callback + this.#cache.config.onError?.( + error as any, + this as Query, + ) + this.#cache.config.onSettled?.( + this.state.data, + error as any, + this as Query, + ) + + throw error // rethrow the error for further handling + } finally { + // The settled retryer's promise would otherwise pin this fetch's raw + // result (a second copy after structural sharing) for the query's lifetime + if (this.#retryer === retryer) { + this.#retryer = undefined + this.#fetchPromise = undefined + } + this.#scheduleGcIfCached() + } + })() + this.#fetchPromise = fetchPromise + retryer.start() + return fetchPromise + } + + #scheduleGcIfCached(): void { + if ( + this.#cache.get( + this.queryHash, + ) === this + ) { + this.scheduleGc() + } + } + + #update( + state: Partial>, + action: Action, + ): void { + this.state = { ...this.state, ...state } + this.#notify(action) + } + + #notify(action: Action): void { + notifyManager.batch(() => { + // Keep the current iteration stable if an observer unsubscribes + // synchronously while it is being notified. + this.observers.slice().forEach((observer) => { + observer.onQueryUpdate() + }) + + this.#cache.notify({ query: this, type: 'updated', action }) + }) + } +} + +/** + * Returns the state changes applied when a query starts fetching. + * @param data - The query's current data. If it is `undefined`, the query is also reset to + * `'pending'` with no error. + * @param options - The query options, whose `networkMode` decides whether the query is `'fetching'` + * or `'paused'`. + * @returns The partial query state for a starting fetch. + */ +export function fetchState< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, +>( + data: TData | undefined, + options: QueryOptions, +) { + return { + fetchFailureCount: 0, + fetchFailureReason: null, + fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused', + ...(data === undefined && + ({ + error: null, + status: 'pending', + } as const)), + } as const +} + +/** + * Returns the state changes applied when a query receives data. + * @param data - The new data. + * @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to the current time. + * @returns The partial query state for a successful update. + */ +function successState(data: TData | undefined, dataUpdatedAt?: number) { + return { + data, + dataUpdatedAt: dataUpdatedAt ?? Date.now(), + error: null, + isInvalidated: false, + status: 'success' as const, + } +} + +/** + * Returns the initial state of a query, based on its `initialData` and `initialDataUpdatedAt` + * options. + * @param options - The query options. + * @returns The initial query state: `'success'` if `initialData` is set, otherwise `'pending'`. + */ +function getDefaultState< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, +>( + options: QueryOptions, +): QueryState { + const data = + typeof options.initialData === 'function' + ? (options.initialData as InitialDataFunction)() + : options.initialData + + const hasData = data !== undefined + + const initialDataUpdatedAt = hasData + ? typeof options.initialDataUpdatedAt === 'function' + ? options.initialDataUpdatedAt() + : options.initialDataUpdatedAt + : 0 + + return { + data, + dataUpdateCount: 0, + dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0, + error: null, + errorUpdateCount: 0, + errorUpdatedAt: 0, + fetchFailureCount: 0, + fetchFailureReason: null, + fetchMeta: null, + isInvalidated: false, + status: hasData ? 'success' : 'pending', + fetchStatus: 'idle', + } +} + +export type { + QueryState, + FetchDirection, + FetchMeta, + FetchOptions, + QueryAction as Action, +} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core-pluggable/src/runtime/queryCache.ts b/packages/react-query-no-core-pluggable/src/runtime/queryCache.ts new file mode 100644 index 00000000000..834a79a6eec --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/queryCache.ts @@ -0,0 +1,298 @@ +import { notifyManager } from './notifyManager' +import { Query } from './query' +import { Subscribable } from './subscribable' +import { hashKeyByOptions, matchQuery } from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { QueryState } from './query' +import type { QueryClient } from './queryClient' +import type { QueryRuntime } from './runtimeBinding' +import type { + DefaultError, + QueryKey, + QueryOptions, + WithRequired, +} from './types' +import type { QueryFilters } from './utils' + +export type QueryCacheConfig = Shared.QueryCacheConfig + +export type QueryCacheNotifyEvent = Shared.QueryCacheNotifyEvent + +type QueryCacheListener = Shared.QueryCacheListener + +export type QueryStore = Shared.QueryStore + +// CLASS + +/** + * The `QueryCache` is the storage mechanism for TanStack Query. It stores all the data, meta + * information, and state of the queries it contains. + * + * Normally, you will not interact with the `QueryCache` directly and instead use a `QueryClient` + * for a specific cache. You can subscribe to it (inherited from `Subscribable`) to be informed of + * safe/known updates to the cache, such as queries being added, removed, or updated — updates made + * outside of the cache's own tracked mechanisms (e.g. mutating a query's state object directly) do + * not notify subscribers. + * @example + * ```ts + * const unsubscribe = queryCache.subscribe((event) => { + * console.log(event.type, event.query) + * }) + * ``` + */ +export class QueryCache extends Subscribable { + #queries: QueryStore + + constructor(public config: QueryCacheConfig = {}) { + super() + this.#queries = new Map() + } + + /** + * Returns the existing `Query` instance for the given options' `queryKey`/`queryHash`, or + * builds and adds a new one to the cache if none exists yet. Used by framework adapters and + * plugins (e.g. broadcast/persistence) that need to get-or-create a `Query` directly, bypassing + * the reactive `QueryObserver` machinery. + * @param client - The client the query belongs to, used to default its options. + * @param options - The query options, including the `queryKey`. A new query is created with the + * options defaulted by {@link QueryClient#defaultQueryOptions}. + * @param state - The initial state of a newly created query, e.g. when hydrating. Ignored if the + * query already exists. + * @returns The existing or newly created query. + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * + * const query = queryCache.build(queryClient, { + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * ``` + */ + build< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + client: QueryClient, + options: WithRequired< + QueryOptions, + 'queryKey' + >, + state?: QueryState, + ): Query { + const queryKey = options.queryKey + const queryHash = + options.queryHash ?? hashKeyByOptions(queryKey, this.config.queryKey) + let query = this.get(queryHash) + + if (!query) { + query = new Query({ + client, + queryKey, + queryHash, + options: client.defaultQueryOptions(options), + state, + defaultOptions: client.getQueryDefaults(queryKey), + }) + this.add(query) + } + + return query + } + + /** + * Adds a query to the cache. + * @internal + * @param query - The query to add. If a query with the same hash is already cached, nothing + * happens. + */ + add(query: Query): void { + if (!this.#queries.has(query.queryHash)) { + this.#queries.set(query.queryHash, query) + + this.notify({ + type: 'added', + query, + }) + } + } + + /** + * Destroys the given `Query` and removes it from the cache, notifying subscribers with a + * `'removed'` event. A no-op if the query is no longer the one currently stored under its hash + * (e.g. it was already replaced). Used by plugins (e.g. the broadcast client) that mirror + * removals across `QueryCache` instances. + * @param query - The query to remove. + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * const query = queryCache.find({ queryKey: ['posts'] }) + * + * if (query) { + * queryCache.remove(query) + * } + * ``` + */ + remove(query: Query): void { + const queryInMap = this.#queries.get(query.queryHash) + + if (queryInMap === query) { + query.destroy() + this.#queries.delete(query.queryHash) + this.notify({ type: 'removed', query }) + } + } + + /** + * Removes all queries from the cache. + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * + * queryCache.clear() + * ``` + */ + clear(): void { + notifyManager.batch(() => { + this.getAll().forEach((query) => { + this.remove(query) + }) + }) + } + + /** + * Returns the `Query` instance stored under the given `queryHash`, or `undefined` if none + * exists. Unlike {@link QueryCache#find}, this looks up by the already-computed hash rather + * than by `QueryFilters`. Used by plugins (e.g. broadcast/hydration) that already have a hash + * to look up directly. + * @param queryHash - The hash of the query to look up. + * @returns The query stored under the hash, or `undefined`. + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * const queryHash = hashKey(['posts']) + * + * const query = queryCache.get(queryHash) + * ``` + */ + get< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + queryHash: string, + ): Query | undefined { + return this.#queries.get(queryHash) as + | Query + | undefined + } + + /** + * Returns all queries within the cache. + * @returns Every query in the cache. + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * + * const queries = queryCache.getAll() + * ``` + */ + getAll(): Array { + return [...this.#queries.values()] + } + + /** + * A slightly more advanced method that can be used to get an existing query instance from the + * cache. This instance not only contains all the state for the query, but all of the instances, + * and underlying guts of the query as well. If the query 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 query in rare scenarios (e.g. looking at `query.state.dataUpdatedAt` to + * decide whether a query is fresh enough to be used as an initial value). + * @param filters - The filters to match, including the required `queryKey`. `exact` defaults to + * `true`. + * @returns The first matching query, or `undefined`. + * @see {@link QueryCache#findAll} + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * + * const query = queryCache.find({ queryKey: ['posts'] }) + * ``` + */ + find( + filters: WithRequired, + ): Query | undefined { + const defaultedFilters = { exact: true, ...filters } + + return this.getAll().find((query) => + matchQuery(defaultedFilters, query, this.config.queryKey), + ) as Query | undefined + } + + /** + * An even more advanced method that can be used to get existing query instances from the cache + * that partially match a query key. If no queries match, an empty array is returned. + * + * This is not typically needed for most applications, but can come in handy when needing more + * information about queries in rare scenarios. + * @param filters - The filters to match. Without filters, every query is returned. + * @returns The matching queries. + * @see {@link QueryCache#find} + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * + * const queries = queryCache.findAll({ queryKey: ['posts'] }) + * ``` + */ + findAll(filters: QueryFilters = {}): Array { + const queries = this.getAll() + return Object.keys(filters).length > 0 + ? queries.filter((query) => + matchQuery(filters, query, this.config.queryKey), + ) + : queries + } + + /** + * Notifies every cache listener of an event, in one batch. + * @internal + * @param event - The event passed to every listener. + */ + notify(event: QueryCacheNotifyEvent): void { + notifyManager.batch(() => { + this.listeners.forEach((listener) => { + listener(event) + }) + }) + } + + /** + * Calls {@link Query#onFocus} on every cached query, in one batch. + * @internal + */ + onFocus(): void { + notifyManager.batch(() => { + this.getAll().forEach((query) => { + query.onFocus() + }) + }) + } + + /** + * Calls {@link Query#onOnline} on every cached query, in one batch. + * @internal + */ + onOnline(): void { + notifyManager.batch(() => { + this.getAll().forEach((query) => { + query.onOnline() + }) + }) + } +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts b/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts new file mode 100644 index 00000000000..8027eb4dca5 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts @@ -0,0 +1,1088 @@ +import { clientFeatures, requireMutations } from './clientFeatures' +import { focusManager } from './focusManager' +import { notifyManager } from './notifyManager' +import { onlineManager } from './onlineManager' +import { QueryCache } from './queryCache' +import { + defaultQueryFn, + functionalUpdate, + hashKeyByOptions, + noop, + partialMatchKey, + resolveQueryValue, + skipToken, +} from './utils' +import type { WithoutSkipToken } from '@tanstack/query-types/bindings' +import type { QueryClientFeatures } from './clientFeatures' +import type { MutationCache } from './mutationCache' +import type { QueryState } from './query' +import type { + CacheKeyConfig, + CancelOptions, + DefaultError, + DefaultOptions, + DefaultedQueryObserverOptions, + InferDataFromTag, + InferErrorFromTag, + InfiniteData, + InfiniteQueryExecuteOptions, + InvalidateOptions, + InvalidateQueryFilters, + MutationKey, + MutationObserverOptions, + MutationOptions, + OmitKeyof, + QueryClientConfig, + QueryExecuteOptions, + QueryKey, + QueryObserverOptionsBase, + QueryOptions, + RefetchOptions, + RefetchQueryFilters, + ResetOptions, + SetDataOptions, +} from './types' +import type { MutationFilters, QueryFilters, Updater } from './utils' + +type QueryDefaults = OmitKeyof, 'queryKey'> +type MutationDefaults = MutationOptions + +class KeyDefaults< + TKey extends ReadonlyArray, + TOptions extends object, +> { + #entries = new Map() + + set(key: TKey, options: TOptions, config?: CacheKeyConfig): void { + this.#entries.set(hashKeyByOptions(key, config), { key, options }) + } + + get(key: TKey, config?: CacheKeyConfig): Partial { + const result: Partial = {} + for (const entry of this.#entries.values()) { + if (partialMatchKey(key, entry.key, config?.equalityFn)) { + Object.assign(result, entry.options) + } + } + return result + } +} + +// CLASS + +/** + * `QueryClient` is used to interact with a cache of queries and mutations. It owns a + * `QueryCache` and, with `mutationPlugin`, a `MutationCache`. It holds + * the default options that are applied to queries and mutations created through it. + * @example + * ```ts + * const queryClient = new QueryClient({ + * defaultOptions: { + * queries: { + * staleTime: Infinity, + * }, + * }, + * }) + * + * await queryClient.query({ queryKey: ['posts'], queryFn: fetchPosts }) + * ``` + */ +export class QueryClient { + #queryCache: QueryCache + readonly [clientFeatures]: QueryClientFeatures = {} + #defaultOptions: DefaultOptions + #queryDefaults = new KeyDefaults() + #mutationDefaults?: KeyDefaults + #mountCount: number + #unsubscribeFocus?: () => void + #unsubscribeOnline?: () => void + + constructor(config: QueryClientConfig = {}) { + this.#queryCache = config.queryCache || new QueryCache() + for (const plugin of config.plugins ?? []) { + plugin(this[clientFeatures], config) + } + if (config.mutationCache) requireMutations(this) + this.#defaultOptions = config.defaultOptions || {} + this.#mountCount = 0 + } + + /** + * Called by a framework adapter's `QueryClientProvider`-equivalent when it mounts, to start + * listening for focus/online events and resume paused mutations. Ref-counted via an internal + * mount count, so nested or multiple providers sharing the same `QueryClient` don't tear down + * the shared listeners until the last one unmounts. + */ + mount(): void { + this.#mountCount++ + if (this.#mountCount !== 1) return + + this.#unsubscribeFocus = focusManager.subscribe(async (focused) => { + if (focused) { + await this.resumePausedMutations() + this.#queryCache.onFocus() + } + }) + this.#unsubscribeOnline = onlineManager.subscribe(async (online) => { + if (online) { + await this.resumePausedMutations() + this.#queryCache.onOnline() + } + }) + } + + /** + * The inverse of {@link QueryClient#mount} — called by a framework adapter's + * `QueryClientProvider`-equivalent when it unmounts. Only tears down the focus/online + * listeners once the mount count returns to `0`. + */ + unmount(): void { + this.#mountCount-- + if (this.#mountCount !== 0) return + + this.#unsubscribeFocus?.() + this.#unsubscribeFocus = undefined + + this.#unsubscribeOnline?.() + this.#unsubscribeOnline = undefined + } + + /** + * Returns the number of queries in the cache that are currently fetching, optionally + * matching a set of filters. This includes background-fetching, loading new pages, and + * loading more infinite query results. + * @param filters - Narrows down which fetching queries are counted. Without filters, every + * fetching query is counted. + * @returns The number of matching queries whose `fetchStatus` is `'fetching'`. + * @example + * ```ts + * if (queryClient.isFetching()) { + * console.log('At least one query is fetching!') + * } + * ``` + */ + isFetching(filters?: Omit): number { + return this.#queryCache.findAll({ ...filters, fetchStatus: 'fetching' }) + .length + } + + /** + * Returns the number of mutations in the cache that are currently pending, optionally + * matching a set of filters. + * @param filters - Narrows down which pending mutations are counted. Without filters, every + * pending mutation is counted. + * @returns The number of matching mutations whose `status` is `'pending'`. + * @example + * ```ts + * if (queryClient.isMutating()) { + * console.log('At least one mutation is pending!') + * } + * ``` + */ + isMutating< + TMutationFilters extends MutationFilters = MutationFilters< + any, + any + >, + >(filters?: NoInfer>): number { + return ( + this[clientFeatures].mutations?.cache.findAll({ + ...filters, + status: 'pending', + }).length ?? 0 + ) + } + + /** + * Imperative (non-reactive) way to retrieve data for a QueryKey. + * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates. + * + * Hint: Do not use this function inside a component, because it won't receive updates. + * Use `useQuery` to create a `QueryObserver` that subscribes to changes. + * @param queryKey - The query key of the query to read. + * @returns The cached data for the query, or `undefined` if no query with this key has been observed yet. + * @see {@link QueryClient#getQueriesData} + */ + getQueryData< + TQueryFnData = unknown, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, + >(queryKey: TTaggedQueryKey): TInferredQueryFnData | undefined { + const options = this.defaultQueryOptions({ queryKey }) + + return this.#queryCache.get(options.queryHash)?.state + .data + } + + /** + * 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 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 QueryClient#getQueryData} + * @example + * ```ts + * const data = queryClient.getQueriesData({ queryKey: ['posts'] }) + * ``` + */ + getQueriesData< + TQueryFnData = unknown, + TQueryFilters extends QueryFilters = QueryFilters, + >(filters: TQueryFilters): Array<[QueryKey, TQueryFnData | undefined]> { + return this.#queryCache.findAll(filters).map(({ queryKey, state }) => { + const data = state.data as TQueryFnData | undefined + return [queryKey, data] + }) + } + + /** + * Synchronous way to immediately update a query's cached data. If the updater (or the value + * passed) resolves to `undefined`, the cache is left untouched and no query is created; + * otherwise, if the query does not exist yet, it will be created. To update multiple queries + * at once by partially matching query keys, use {@link QueryClient#setQueriesData} instead. + * + * Updates must be performed immutably: do not mutate `oldData`, or data previously retrieved + * via {@link QueryClient#getQueryData}, in place. + * @param queryKey - The query key to set data for. + * @param updater - Either the new data, or a function that receives the 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 The data that was written, or `undefined` if the updater returned `undefined` — in that case + * the write is skipped and the cache is left unchanged. + * @example + * ```ts + * queryClient.setQueryData(['posts'], newPosts) + * + * // Or, using an updater function that receives the current data: + * queryClient.setQueryData(['posts'], (oldPosts) => [...oldPosts, newPost]) + * ``` + */ + setQueryData< + TQueryFnData = unknown, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, + >( + queryKey: TTaggedQueryKey, + updater: Updater< + InferDataFromTag, TTaggedQueryKey> | undefined, + NoInfer | undefined + >, + options?: SetDataOptions, + ): NoInfer | undefined { + const defaultedOptions = this.defaultQueryOptions< + any, + any, + unknown, + any, + QueryKey + >({ queryKey }) + + const query = this.#queryCache.get< + InferDataFromTag, TTaggedQueryKey> + >(defaultedOptions.queryHash) + const prevData = query?.state.data + const data = functionalUpdate(updater, prevData) + + if (data === undefined) { + return undefined + } + + return this.#queryCache + .build(this, defaultedOptions) + .setData(data, { ...options, manual: true }) + } + + /** + * 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 QueryClient#setQueryData} for each matching query. + * @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 QueryClient#setQueryData}. + * @example + * ```ts + * queryClient.setQueriesData({ queryKey: ['posts'] }, (oldPosts) => + * oldPosts ? oldPosts.filter((post) => post.id !== deletedId) : oldPosts, + * ) + * ``` + */ + setQueriesData< + TQueryFnData, + TQueryFilters extends QueryFilters = QueryFilters, + >( + filters: TQueryFilters, + updater: Updater< + NoInfer | undefined, + NoInfer | undefined + >, + options?: SetDataOptions, + ): Array<[QueryKey, TQueryFnData | undefined]> { + return notifyManager.batch(() => + this.#queryCache + .findAll(filters) + .map(({ queryKey }) => [ + queryKey, + this.setQueryData(queryKey, updater, options), + ]), + ) + } + + /** + * Imperative (non-reactive) way to retrieve an existing query's state. If the query does not + * exist, `undefined` is returned. + * @param queryKey - The query key of the query to read. + * @returns The query's state, or `undefined` if no query with this key exists. + * @example + * ```ts + * const state = queryClient.getQueryState(['posts']) + * console.log(state?.dataUpdatedAt) + * ``` + */ + getQueryState< + TQueryFnData = unknown, + TError = DefaultError, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, + TInferredError = InferErrorFromTag, + >( + queryKey: TTaggedQueryKey, + ): QueryState | undefined { + const options = this.defaultQueryOptions({ queryKey }) + return this.#queryCache.get( + options.queryHash, + )?.state + } + + /** + * Removes queries from the cache that match the given filters. Unlike + * {@link QueryClient#invalidateQueries} or {@link QueryClient#refetchQueries}, this removes + * matching queries from the cache instead of refetching them. Without filters, every query in + * the cache is removed. + * @param filters - The filters that select which queries to remove. Without filters, every query + * is removed. + * @example + * ```ts + * queryClient.removeQueries({ queryKey: ['posts'], exact: true }) + * ``` + */ + removeQueries( + filters?: QueryFilters, + ): void { + const queryCache = this.#queryCache + notifyManager.batch(() => { + queryCache.findAll(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 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 queryClient.resetQueries({ queryKey: ['posts'], exact: true }) + * ``` + */ + resetQueries( + filters?: QueryFilters, + options?: ResetOptions, + ): Promise { + const queryCache = this.#queryCache + + return notifyManager.batch(() => { + const matched = queryCache.findAll(filters) + const queriesToRefetch = new Set(matched) + matched.forEach((query) => { + query.reset() + }) + return this.refetchQueries( + { + 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 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 queryClient.cancelQueries({ queryKey: ['posts'], exact: true }) + * ``` + */ + cancelQueries( + filters?: QueryFilters, + cancelOptions: CancelOptions = {}, + ): Promise { + const defaultedCancelOptions = { revert: true, ...cancelOptions } + + const promises = notifyManager.batch(() => + this.#queryCache + .findAll(filters) + .map((query) => query.cancel(defaultedCancelOptions)), + ) + + return Promise.all(promises).then(noop, noop) + } + + /** + * Marks queries matching the given filters as invalidated. Unlike + * {@link QueryClient#removeQueries}, invalidated queries stay in the cache. + * + * Unless `filters.refetchType` is `'none'`, matching queries are then refetched via + * {@link QueryClient#refetchQueries}, using `filters.refetchType` if set, otherwise + * `filters.type`, otherwise `'active'`. + * @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 QueryClient#refetchQueries}, e.g. `cancelRefetch` and + * `throwOnError`. + * @returns A promise that resolves once the refetch settles, or immediately if `refetchType` is + * `'none'`. + * @example + * ```ts + * await queryClient.invalidateQueries({ queryKey: ['posts'], refetchType: 'active' }) + * ``` + */ + invalidateQueries( + filters?: InvalidateQueryFilters, + options: InvalidateOptions = {}, + ): Promise { + return notifyManager.batch(() => { + this.#queryCache.findAll(filters).forEach((query) => { + query.invalidate() + }) + + if (filters?.refetchType === 'none') { + return Promise.resolve() + } + return this.refetchQueries( + { + ...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 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 queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' }) + * ``` + */ + refetchQueries( + filters?: RefetchQueryFilters, + options: RefetchOptions = {}, + ): Promise { + const fetchOptions = { + ...options, + cancelRefetch: options.cancelRefetch ?? true, + } + const promises = notifyManager.batch(() => + this.#queryCache + .findAll(filters) + .filter((query) => !query.isDisabled() && !query.isStatic()) + .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) + } + + /** + * Asynchronous method to fetch and cache a query, resolving with the data or throwing with + * the error. + * + * If the query already exists in the cache and its data is not stale (per the given + * `staleTime`), the cached data is returned without fetching. Otherwise, the query is fetched + * and the promise resolves once the fetch settles. If a `select` function is provided, it is + * applied to the data in both cases (cached or freshly fetched) before it is returned. + * + * Unlike a reactive observer, retries are disabled by default here (`retry: false`) unless + * explicitly configured, since there is no component to catch a thrown error and retry through + * re-render. + * + * The accepted options are `QueryObserverOptions` minus the fields that only make sense for a + * reactive observer — `enabled`, `refetchInterval`, `refetchIntervalInBackground`, + * `refetchOnWindowFocus`, `refetchOnReconnect`, `refetchOnMount`, `retryOnMount`, + * `notifyOnChangeProps`, `throwOnError`, `suspense`, and `placeholderData` are not part of this + * method's options. + * Shared query options can contain `skipToken` as their `queryFn`. If the supplied options contain + * the token, the call skips fetching and resolves with existing data regardless of freshness. + * It applies `select` when data exists and resolves to `undefined` on a cache miss. + * Use {@link QueryClient#getQueryData} to read the cache directly. + * @param options - The query options, including the `queryKey` and the `queryFn` used if the + * query needs to fetch. + * @returns A promise that resolves to the data, 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 queryClient.query({ queryKey, queryFn, staleTime: 10000 }) + * } catch (error) { + * console.log(error) + * } + * ``` + */ + query< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, + >( + options: WithoutSkipToken< + QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > + >, + ): Promise + query< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, + >( + options: QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + ): Promise + async query< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, + >( + options: QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + ): Promise { + const defaultedOptions = this.defaultQueryOptions(options) + let queryData: TQueryData + + if (options.queryFn === skipToken) { + const cachedData = this.#queryCache.get< + TQueryFnData, + TError, + TQueryData, + TQueryKey + >(defaultedOptions.queryHash)?.state.data + if (cachedData === undefined) return undefined + queryData = cachedData + } else { + // https://github.com/tannerlinsley/react-query/issues/652 + if (defaultedOptions.retry === undefined) { + defaultedOptions.retry = false + } + + const query = this.#queryCache.build(this, defaultedOptions) + + const isStale = query.isStaleByTime( + resolveQueryValue(defaultedOptions.staleTime, query), + ) + + queryData = isStale + ? await query.fetch(defaultedOptions) + : (query.state.data as TQueryData) + } + + const select = defaultedOptions.select + + if (select) { + return select(queryData) + } + + return queryData as unknown as TData + } + + /** + * 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 QueryClient#getQueryData} + * to read the cache directly. + * @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 queryClient.infiniteQuery({ + * queryKey, + * queryFn, + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextCursor, + * }) + * console.log(data.pages) + * } catch (error) { + * console.log(error) + * } + * ``` + */ + infiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: WithoutSkipToken< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + >, + ): Promise< + Array extends Array> + ? InfiniteData + : TData + > + infiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): Promise< + | undefined + | (Array extends Array> + ? InfiniteData + : TData) + > + infiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): Promise< + | undefined + | (Array extends Array> + ? InfiniteData + : TData) + > { + return this.query({ ...options, _type: 'infinite' } as any) + } + + /** + * Resumes mutations that were paused because there was no network connection. Does nothing + * (resolving immediately) if the client is currently offline. + * @returns A promise that resolves once the resumed mutations have settled. + * @example + * ```ts + * import { QueryClient } from '@tanstack/react-query-no-core-pluggable' + * + * const queryClient = new QueryClient() + * await queryClient.resumePausedMutations() + * ``` + */ + resumePausedMutations(): Promise { + const mutations = this[clientFeatures].mutations + if (mutations && onlineManager.isOnline()) { + return mutations.cache.resumePausedMutations() + } + return Promise.resolve() + } + + /** + * Returns the query cache this client is connected to. + * @returns The {@link QueryCache} instance. + * @example + * ```ts + * import { QueryClient } from '@tanstack/react-query-no-core-pluggable' + * + * const queryClient = new QueryClient() + * const queryCache = queryClient.getQueryCache() + * const queries = queryCache.findAll({ queryKey: ['posts'] }) + * ``` + */ + getQueryCache(): QueryCache { + return this.#queryCache + } + + /** + * Returns the mutation cache this client is connected to. + * @returns The {@link MutationCache} instance. + * @example + * ```ts + * import { QueryClient, mutationPlugin } from '@tanstack/react-query-no-core-pluggable' + * + * const queryClient = new QueryClient({ plugins: [mutationPlugin] }) + * const mutationCache = queryClient.getMutationCache() + * const mutations = mutationCache.findAll({ status: 'pending' }) + * ``` + */ + getMutationCache(): MutationCache { + return requireMutations(this).cache + } + + /** + * Returns the default options that were set when creating the client, or via + * {@link QueryClient#setDefaultOptions}. + * @returns The client's current default options. + * @example + * ```ts + * import { QueryClient } from '@tanstack/react-query-no-core-pluggable' + * + * const queryClient = new QueryClient() + * const defaultOptions = queryClient.getDefaultOptions() + * ``` + */ + getDefaultOptions(): DefaultOptions { + return this.#defaultOptions + } + + /** + * Dynamically sets the default options for this client, overwriting any previously defined + * default options. + * @param options - The new default options for queries and mutations. + * @see {@link QueryClient#getDefaultOptions} + * @example + * ```ts + * import { QueryClient } from '@tanstack/react-query-no-core-pluggable' + * + * const queryClient = new QueryClient() + * queryClient.setDefaultOptions({ + * queries: { + * staleTime: Infinity, + * }, + * }) + * ``` + */ + setDefaultOptions(options: DefaultOptions): void { + this.#defaultOptions = options + } + + /** + * Sets default options for queries whose query key partially matches the given `queryKey`. + * + * If several registered query defaults match a given query key, they are merged together in + * registration order by {@link QueryClient#getQueryDefaults}, so register defaults from the + * most generic key to the least generic one — more specific defaults should be registered + * after more generic ones so they take precedence. + * @param queryKey - The query key that query keys are partially matched against. + * @param options - The default options applied to matching queries. + * @example + * ```ts + * queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts }) + * + * await queryClient.query({ queryKey: ['posts'] }) + * ``` + */ + setQueryDefaults< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + >( + queryKey: QueryKey, + options: Partial< + OmitKeyof< + QueryObserverOptionsBase, + 'queryKey' + > + >, + ): void { + this.#queryDefaults.set(queryKey, options, this.#queryCache.config.queryKey) + } + + /** + * Returns the default options registered for queries whose query key partially matches the + * given `queryKey`, via {@link QueryClient#setQueryDefaults}. If multiple registered defaults + * match, they are merged together in registration order. + * @param queryKey - The query key to look up registered defaults for. + * @returns The merged default options of every registration that matches, or an empty object if + * none match. + * @example + * ```ts + * const defaultOptions = queryClient.getQueryDefaults(['posts']) + * ``` + */ + getQueryDefaults( + queryKey: QueryKey, + ): OmitKeyof, 'queryKey'> { + return this.#queryDefaults.get(queryKey, this.#queryCache.config.queryKey) + } + + /** + * Sets default options for mutations whose mutation key partially matches the given + * `mutationKey`. As with {@link QueryClient#setQueryDefaults}, the order of registration + * matters when several registered defaults match the same mutation key. + * @param mutationKey - The mutation key that mutation keys are partially matched against. + * @param options - The default options applied to matching mutations. + * @see {@link QueryClient#getMutationDefaults} + * @example + * ```ts + * queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost }) + * ``` + */ + setMutationDefaults< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, + >( + mutationKey: MutationKey, + options: OmitKeyof< + MutationObserverOptions, + 'mutationKey' + >, + ): void { + const config = this.getMutationCache().config.mutationKey + this.#mutationDefaults ??= new KeyDefaults() + this.#mutationDefaults.set(mutationKey, options, config) + } + + /** + * Returns the default options registered for mutations whose mutation key partially matches + * the given `mutationKey`, via {@link QueryClient#setMutationDefaults}. If multiple registered + * defaults match, they are merged together in registration order. + * @param mutationKey - The mutation key to look up registered defaults for. + * @returns The merged default options of every registration that matches, or an empty object if + * none match. + * @example + * ```ts + * const defaultOptions = queryClient.getMutationDefaults(['addPost']) + * ``` + */ + getMutationDefaults( + mutationKey: MutationKey, + ): OmitKeyof, 'mutationKey'> { + return ( + this.#mutationDefaults?.get( + mutationKey, + this.getMutationCache().config.mutationKey, + ) ?? {} + ) + } + + /** + * Called by framework adapters (e.g. inside `useQuery`) to resolve the options passed by the + * caller into their final, defaulted form: merging the client's own `defaultOptions.queries`, + * then `queryClient.setQueryDefaults` for the given `queryKey`, then the caller's options on + * top. A no-op if the options are already defaulted (`_defaulted: true`). + * @param options - The query options passed by the caller. + * @returns The defaulted options, with `queryHash` and dependent defaults (e.g. + * `refetchOnReconnect`) filled in. + */ + defaultQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, + >( + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + ): DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > { + if (options._defaulted) { + return options as DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > + } + + const queryDefaults = this.getQueryDefaults(options.queryKey) + const defaultedOptions = { + ...this.#defaultOptions.queries, + ...queryDefaults, + ...options, + _defaulted: true, + } + + if (defaultedOptions.queryFn === defaultQueryFn) { + defaultedOptions.queryFn = + 'queryFn' in queryDefaults + ? queryDefaults.queryFn + : this.#defaultOptions.queries?.queryFn + } + + if (!defaultedOptions.queryHash) { + defaultedOptions.queryHash = hashKeyByOptions( + defaultedOptions.queryKey, + this.#queryCache.config.queryKey, + ) + } + + // dependent default values + if (defaultedOptions.refetchOnReconnect === undefined) { + defaultedOptions.refetchOnReconnect = + defaultedOptions.networkMode !== 'always' + } + if (defaultedOptions.throwOnError === undefined) { + defaultedOptions.throwOnError = !!defaultedOptions.suspense + } + + if (!defaultedOptions.networkMode && defaultedOptions.persister) { + defaultedOptions.networkMode = 'offlineFirst' + } + + if (defaultedOptions.queryFn === skipToken) { + defaultedOptions.enabled = false + } + + return defaultedOptions as DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > + } + + /** + * The mutation counterpart of {@link QueryClient#defaultQueryOptions}. Called by framework + * adapters (e.g. inside `useMutation`) to merge the client's `defaultOptions.mutations`, then + * `queryClient.setMutationDefaults` for the given `mutationKey`, then the caller's options on + * top. A no-op if the options are already defaulted (`_defaulted: true`). + * @param options - The mutation options passed by the caller. + * @returns The defaulted options. + */ + defaultMutationOptions>( + options?: T, + ): T { + if (options?._defaulted) { + return options + } + return { + ...this.#defaultOptions.mutations, + ...(options?.mutationKey && + this.getMutationDefaults(options.mutationKey)), + ...options, + _defaulted: true, + } as T + } + + /** + * Clears both the query cache and the mutation cache this client is connected to. + * This clears their garbage collection timers and cancels in-flight query fetches. + * Running mutations continue to execute. + * @example + * ```ts + * import { QueryClient } from '@tanstack/react-query-no-core-pluggable' + * + * const queryClient = new QueryClient() + * queryClient.clear() + * ``` + */ + clear(): void { + this.#queryCache.clear() + this[clientFeatures].mutations?.cache.clear() + } +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts b/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts new file mode 100644 index 00000000000..0f3861f4112 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts @@ -0,0 +1,1034 @@ +import { isServer as isServerEnvironment } from './environmentManager' +import { focusManager } from './focusManager' +import { notifyManager } from './notifyManager' +import { fetchState } from './query' +import { Subscribable } from './subscribable' +import { timeoutManager } from './timeoutManager' +import { + isValidTimeout, + noop, + replaceData, + resolveQueryValue, + shallowEqualObjects, + timeUntilStale, +} from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + ObserverFetchOptions, + ProjectionFailure, + QueryObserverListener, + QueryObserverResultReader, +} from '@tanstack/query-types/bindings' +import type { Query, QueryState } from './query' +import type { QueryClient } from './queryClient' +import type { QueryRuntime } from './runtimeBinding' +import type { ManagedTimerId } from './timeoutManager' +import type { + DefaultError, + DefaultedQueryObserverOptions, + PlaceholderDataFunction, + QueryKey, + QueryObserverBaseResult, + QueryObserverOptionsBase, + QueryObserverResult, + RefetchOptions, +} from './types' + +export type QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +> = Shared.QueryObserverResultContext< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +> + +export type ObserverOptionsInput< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = Shared.ObserverOptionsInput< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +> + +/** + * A `QueryObserver` watches a single query in the `QueryCache` and computes a + * `QueryObserverResult` from its state, recomputing and notifying subscribers + * whenever the underlying query (or the observer's options) changes. It is + * the primitive that framework adapters (e.g. `useQuery`) build their hooks + * on top of, but it can also be used directly to observe and switch between + * queries outside of any framework. + * @example + * ```ts + * const observer = new QueryObserver(queryClient, { + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * const unsubscribe = observer.subscribe((result) => { + * console.log(result.data) + * }) + * ``` + */ +export class QueryObserver< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends Subscribable> { + #client: QueryClient + #currentQuery: Query = undefined! + #currentQueryInitialState: QueryState = undefined! + #currentResult: QueryObserverResult = undefined! + #resultContext: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + > = {} + // This property keeps track of the last query with defined data. + // It will be used to pass the previous data and query to the placeholder function between renders. + #lastQueryWithDefinedData?: Query + #staleTimeoutId?: ManagedTimerId + #refetchIntervalId?: ManagedTimerId + #currentRefetchInterval?: number | false + #trackedProps = new Set() + + constructor( + client: QueryClient, + public options: ObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ) { + super() + + this.#client = client + + this.bindMethods() + this.setOptions(options) + } + + /** + * Binds the methods of the result (`refetch`) to the observer, so they keep working when destructured + * from it. Subclasses override it to bind their own result methods as well. + */ + protected bindMethods(): void { + this.refetch = this.refetch.bind(this) + } + + protected override onSubscribe(): void { + if (this.listeners.size === 1) { + this.#currentQuery.addObserver(this) + + if (shouldFetchOnMount(this.#currentQuery, this.options)) { + this.#executeFetch() + } else { + this.updateResult() + } + + this.#updateTimers() + } + } + + protected override onUnsubscribe(): void { + if (!this.hasListeners()) { + this.destroy() + } + } + + /** + * Returns whether the observed query is currently stale and configured + * (via the `refetchOnReconnect` option) to refetch when the network + * reconnects. + * @returns `true` if the observer should refetch the query on reconnect. + */ + shouldFetchOnReconnect(): boolean { + return shouldFetchOn( + this.#currentQuery, + this.options, + this.options.refetchOnReconnect, + ) + } + + /** + * Returns whether the observed query is currently stale and configured + * (via the `refetchOnWindowFocus` option) to refetch when the window + * regains focus. + * @returns `true` if the observer should refetch the query on window focus. + */ + shouldFetchOnWindowFocus(): boolean { + return shouldFetchOn( + this.#currentQuery, + this.options, + this.options.refetchOnWindowFocus, + ) + } + + /** + * Stops observing the current query: clears all listeners, cancels the + * stale and refetch-interval timers, and removes this observer from the + * query it was observing. + */ + destroy(): void { + this.listeners = new Set() + this.#clearStaleTimeout() + this.#clearRefetchInterval() + this.#currentQuery.removeObserver(this) + } + + /** + * Updates the observer's options. This will re-resolve the query being + * observed (switching to a different query if the `queryKey` changed), + * trigger a fetch if the new options require one and the observer has + * subscribers, recompute the current result, and reschedule the stale and + * refetch-interval timers as needed. + * @param options - The new observer options. They are defaulted with {@link + * QueryClient#defaultQueryOptions} before being applied. + * @throws {Error} If `enabled` is neither a boolean nor a function. + * @example + * ```ts + * observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) }) + * // later: switch to a different query, reusing the same observer + * observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) }) + * ``` + */ + setOptions( + options: ObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ): void { + const prevOptions = this.options + const prevQuery = this.#currentQuery + + this.options = this.#client.defaultQueryOptions(options) + + if ( + this.options.enabled !== undefined && + typeof this.options.enabled !== 'boolean' && + typeof this.options.enabled !== 'function' && + typeof resolveQueryValue(this.options.enabled, this.#currentQuery) !== + 'boolean' + ) { + throw new Error( + 'Expected enabled to be a boolean or a callback that returns a boolean', + ) + } + + this.#updateQuery() + this.#currentQuery.setOptions(this.options) + + if ( + prevOptions._defaulted && + !shallowEqualObjects(this.options, prevOptions) + ) { + this.#client.getQueryCache().notify({ + type: 'observerOptionsUpdated', + query: this.#currentQuery, + observer: this, + }) + } + + const mounted = this.hasListeners() + + // Fetch if there are subscribers + if ( + mounted && + shouldFetchOptionally( + this.#currentQuery, + prevQuery, + this.options, + prevOptions, + ) + ) { + this.#executeFetch() + } + + // Update result + this.updateResult() + + // Update stale interval if needed + if ( + mounted && + (this.#currentQuery !== prevQuery || + resolveQueryValue(this.options.enabled, this.#currentQuery) !== + resolveQueryValue(prevOptions.enabled, this.#currentQuery) || + resolveQueryValue(this.options.staleTime, this.#currentQuery) !== + resolveQueryValue(prevOptions.staleTime, this.#currentQuery)) + ) { + this.#updateStaleTimeout() + } + + const nextRefetchInterval = this.#computeRefetchInterval() + + // Update refetch interval if needed + if ( + mounted && + (this.#currentQuery !== prevQuery || + resolveQueryValue(this.options.enabled, this.#currentQuery) !== + resolveQueryValue(prevOptions.enabled, this.#currentQuery) || + nextRefetchInterval !== this.#currentRefetchInterval) + ) { + this.#updateRefetchInterval(nextRefetchInterval) + } + } + + /** + * Creates a result reader that captures the supplied query options. + * Reads cache the complete result locally and retain its reference while its + * fields are unchanged. They do not update this observer's committed result, + * options, or selection state. Missing queries are built in the query cache. + * Call `commit` after the render commits to apply the options and reuse the + * reader's computation. An abandoned reader needs no cleanup. + * @param options - The defaulted options used to read and commit the query result. + * @returns A reader with local snapshot and computation caches. + */ + createResultReader( + options: DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ): QueryObserverResultReader> { + const readerOptions = { ...options } + const { select, structuralSharing } = readerOptions + const context = { ...this.#resultContext } + let result = this.#currentResult + + const getSnapshot = () => { + const query = this.#client + .getQueryCache() + .build(this.#client, readerOptions) + const { selection, selected } = this.#resultContext + const input = query.state.data + + // A query update may already have selected this data. + if ( + input !== undefined && + select && + shallowEqualObjects( + { input, select, structuralSharing }, + selection?.key, + ) + ) { + context.selection = selection + context.selected = selected + } + + const nextResult = this.createResult( + query, + readerOptions, + context, + result, + ) + if (!shallowEqualObjects(nextResult, result)) { + result = nextResult + } + return result + } + + return { + getSnapshot, + commit: () => { + // Reuse selections computed since the last read. + getSnapshot() + this.#resultContext = { ...context } + this.setOptions(readerOptions) + }, + } + } + + /** + * Returns the most recently computed `QueryObserverResult` for the + * observed query. This is a point-in-time read; to be notified of updates + * as they happen, subscribe to the observer instead (its inherited + * `subscribe` method). + * @returns The observer's latest result. + * @example + * ```ts + * const result = observer.getCurrentResult() + * console.log(result.status, result.data) + * ``` + */ + getCurrentResult(): QueryObserverResult { + return this.#currentResult + } + + /** + * Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via + * {@link QueryObserver#trackProp} (and an optional `onPropTracked` callback). Used by framework + * adapters when `notifyOnChangeProps` is not set, to implement its default "only re-render on + * properties you actually read" behavior. + * @param result - The result to wrap. + * @param onPropTracked - Called with the name of each property that is read. + * @returns A proxy of `result` that tracks property reads. + */ + trackResult( + result: QueryObserverResult, + onPropTracked?: (key: keyof QueryObserverResult) => void, + ): QueryObserverResult { + return new Proxy(result, { + get: (target, key) => { + this.trackProp(key as keyof QueryObserverResult) + onPropTracked?.(key as keyof QueryObserverResult) + return Reflect.get(target, key) + }, + }) + } + + /** + * Records that the given `QueryObserverResult` property was read, so a subsequent update only + * notifies this observer if a tracked property actually changed. Normally called indirectly via + * {@link QueryObserver#trackResult}'s proxy; exposed directly for adapters that track property + * access themselves (e.g. through their own reactivity system) instead of via the proxy. + * @param key - The name of the property that was read. + */ + trackProp(key: keyof QueryObserverResult) { + this.#trackedProps.add(key) + } + + /** + * Returns the `Query` instance this observer is currently observing. + * @returns The observed query. + */ + getCurrentQuery(): Query { + return this.#currentQuery + } + + /** + * Refetches the observed query and returns a promise that resolves with + * the resulting `QueryObserverResult`. + * @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling + * it, and `throwOnError` to `true` to reject when the refetch fails. + * @returns A promise that resolves with the result after the refetch. + * @example + * ```ts + * const result = await observer.refetch({ cancelRefetch: false }) + * console.log(result.data) + * ``` + */ + refetch( + options: RefetchOptions = {}, + ): Promise> { + return this.fetch(options) + } + + /** + * 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 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 observer.fetchOptimistic({ + * queryKey: ['posts', 2], + * queryFn: () => fetchPost(2), + * }) + * console.log(result.data) + * ``` + */ + fetchOptimistic( + options: ObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ): Promise> { + const defaultedOptions = this.#client.defaultQueryOptions(options) + + const query = this.#client + .getQueryCache() + .build(this.#client, defaultedOptions) + + const cached = Promise.withResolvers>() + const unsubscribe = this.#client.getQueryCache().subscribe((event) => { + if ( + event.type === 'updated' && + event.query.queryHash === query.queryHash && + query.state.data !== undefined + ) { + unsubscribe() + cached.resolve(this.createResult(query, defaultedOptions)) + } + }) + + return Promise.race([ + query + .fetch(defaultedOptions) + .then(() => { + const result = this.createResult(query, defaultedOptions) + // Resolve the cache wait when the fetch succeeds. + cached.resolve(result) + return result + }) + .finally(unsubscribe), + cached.promise, + ]) + } + + /** + * Fetches the observed query and updates the result once the fetch settles. Used by `refetch` and, + * in `InfiniteQueryObserver`, to fetch more pages. + * @param fetchOptions - Options for this fetch. `cancelRefetch` defaults to `true`. + * @returns A promise that resolves with the updated result. + */ + protected fetch( + fetchOptions: ObserverFetchOptions, + ): Promise> { + return this.#executeFetch({ + ...fetchOptions, + cancelRefetch: fetchOptions.cancelRefetch ?? true, + }).then(() => { + this.updateResult() + return this.#currentResult + }) + } + + #executeFetch( + fetchOptions?: Omit, + ): Promise { + // Make sure we reference the latest query as the current one might have been removed + this.#updateQuery() + + // Fetch + let promise: Promise = this.#currentQuery.fetch( + this.options, + fetchOptions, + ) + + if (!fetchOptions?.throwOnError) { + promise = promise.catch(noop) + } + + return promise + } + + #shouldScheduleTimer(timeout: unknown): timeout is number { + return ( + !isServerEnvironment() && + resolveQueryValue(this.options.enabled, this.#currentQuery) !== false && + isValidTimeout(timeout) + ) + } + + #updateStaleTimeout(): void { + this.#clearStaleTimeout() + const staleTime = resolveQueryValue( + this.options.staleTime, + this.#currentQuery, + ) + + if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) { + return + } + + const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime) + + // The timeout is sometimes triggered 1 ms before the stale time expiration. + // To mitigate this issue we always add 1 ms to the timeout. + const timeout = time + 1 + + this.#staleTimeoutId = timeoutManager.setTimeout(() => { + if (!this.#currentResult.isStale) { + this.updateResult() + } + }, timeout) + } + + #computeRefetchInterval() { + return ( + resolveQueryValue(this.options.refetchInterval, this.#currentQuery) ?? + false + ) + } + + #updateRefetchInterval(nextInterval: number | false): void { + this.#clearRefetchInterval() + + this.#currentRefetchInterval = nextInterval + + if ( + this.#currentRefetchInterval === 0 || + !this.#shouldScheduleTimer(this.#currentRefetchInterval) + ) { + return + } + + this.#refetchIntervalId = timeoutManager.setInterval(() => { + if ( + this.options.refetchIntervalInBackground || + focusManager.isFocused() + ) { + this.#executeFetch() + } + }, this.#currentRefetchInterval) + } + + #updateTimers(): void { + this.#updateStaleTimeout() + this.#updateRefetchInterval(this.#computeRefetchInterval()) + } + + #clearStaleTimeout(): void { + if (this.#staleTimeoutId !== undefined) { + timeoutManager.clearTimeout(this.#staleTimeoutId) + this.#staleTimeoutId = undefined + } + } + + #clearRefetchInterval(): void { + if (this.#refetchIntervalId !== undefined) { + timeoutManager.clearInterval(this.#refetchIntervalId) + this.#refetchIntervalId = undefined + } + } + + #resolvePlaceholder( + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + previousResultData: TData | undefined, + context = this.#resultContext, + ) { + const { placeholderData, structuralSharing } = options + const memo = context.placeholder + const previousQuery = this.#lastQueryWithDefinedData + const previousState = previousQuery?.state + const key = { + placeholderData, + structuralSharing, + previousQuery, + previousState, + previousOptions: previousQuery?.options, + } + if (shallowEqualObjects(key, memo?.key)) { + return memo + } + + let failure: ProjectionFailure | undefined + let input: TQueryData | undefined + let sourceQuery: typeof previousQuery + if (typeof placeholderData === 'function') { + try { + input = ( + placeholderData as unknown as PlaceholderDataFunction< + TQueryFnData, + TError, + TQueryData, + TQueryKey + > + )(previousState?.data, previousQuery) + } catch (error) { + failure = { error: error as TError, errorUpdatedAt: Date.now() } + } + if (previousState?.data !== undefined) { + sourceQuery = previousQuery + } + } else { + input = placeholderData + } + + if (input !== undefined) { + input = replaceData( + previousResultData, + input as unknown, + options, + ) as TQueryData + } + return input !== undefined || failure + ? { key, input, sourceQuery, failure } + : undefined + } + + /** + * Computes the result for a query and options from the query's state, applying `select`, + * `placeholderData`, and the derived flags. Subclasses override it to add their own fields. + * @param query - The query to compute the result for. + * @param options - The observer options to compute the result with. + * @param context - The selection and placeholder state reused between computations. + * @param prevResult - The previous result used for structural sharing. + * @returns The computed result. + */ + protected createResult( + query: Query, + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + context = this.#resultContext, + prevResult = this.#currentResult as + | QueryObserverResult + | undefined, + ): QueryObserverResult { + const prevQuery = this.#currentQuery + const prevOptions = this.options + const queryChange = query !== prevQuery + const queryInitialState = queryChange + ? query.state + : this.#currentQueryInitialState + + const { state } = query + const fetchOptimistically = + options._optimisticResults && + (this.hasListeners() + ? shouldFetchOptionally(query, prevQuery, options, prevOptions) + : shouldFetchOnMount(query, options)) + const newState = fetchOptimistically + ? { ...state, ...fetchState(state.data, query.options) } + : state + const fetchStatus = + options._optimisticResults === 'isRestoring' + ? 'idle' + : newState.fetchStatus + const selectedQuery = context.selected?.query + if (selectedQuery && selectedQuery.state.data === undefined) { + context.selected = undefined + // Keep a cached error stable, but a successful selection needs its data. + if (!context.selection?.failure) { + context.selection = undefined + } + } + + const { placeholderData, select, structuralSharing } = options + if ( + newState.data === undefined && + newState.status === 'pending' && + placeholderData !== undefined + ) { + context.placeholder = this.#resolvePlaceholder( + options, + prevResult?.data, + context, + ) + } else { + context.placeholder = undefined + } + + const placeholder = context.placeholder + const input = placeholder ? placeholder.input : newState.data + if (!select || input === undefined) { + context.selection = undefined + } else { + const key = { input, select, structuralSharing } + if (!shallowEqualObjects(key, context.selection?.key)) { + try { + const data = replaceData(prevResult?.data, select(input), options) + context.selected = { + data, + query: placeholder ? placeholder.sourceQuery : query, + } + context.selection = { key } + } catch (error) { + context.selection = { + key, + failure: { + error: error as TError, + errorUpdatedAt: Date.now(), + }, + } + } + } + } + + const failure = placeholder?.failure ?? context.selection?.failure + const data = context.selection + ? context.selected?.data + : (input as unknown as TData | undefined) + const isPlaceholderData = + placeholder !== undefined && input !== undefined && !failure + const { error, errorUpdatedAt } = failure ?? newState + const status = failure + ? 'error' + : isPlaceholderData + ? 'success' + : newState.status + const isFetching = fetchStatus === 'fetching' + const isPending = status === 'pending' + const isError = status === 'error' + + const isLoading = isPending && isFetching + const hasData = data !== undefined + + const result: QueryObserverBaseResult = { + status, + fetchStatus, + isPending, + isSuccess: status === 'success', + isError, + isLoading, + data, + dataUpdatedAt: newState.dataUpdatedAt, + error, + errorUpdatedAt, + failureCount: newState.fetchFailureCount, + failureReason: newState.fetchFailureReason, + errorUpdateCount: newState.errorUpdateCount, + isFetched: query.isFetched(), + isFetchedAfterMount: + newState.dataUpdateCount > queryInitialState.dataUpdateCount || + newState.errorUpdateCount > queryInitialState.errorUpdateCount, + isFetching, + isRefetching: isFetching && !isPending, + isLoadingError: isError && !hasData, + isPaused: fetchStatus === 'paused', + isPlaceholderData, + isRefetchError: isError && hasData, + isStale: isStale(query, options), + refetch: this.refetch, + isEnabled: resolveQueryValue(options.enabled, query) !== false, + } + + const nextResult = result as QueryObserverResult + + return nextResult + } + + /** + * Recomputes and stores the current result from the current query/options, notifying listeners + * if it changed. Framework adapters call this right after subscribing to make sure no query + * update was missed in the gap between creating the observer and subscribing to it. + */ + updateResult(): void { + const prevResult = this.#currentResult as + | QueryObserverResult + | undefined + + const nextResult = this.createResult(this.#currentQuery, this.options) + + if (this.#currentQuery.state.data !== undefined) { + this.#lastQueryWithDefinedData = this.#currentQuery + } + + // Only notify and update result if something has changed + if (shallowEqualObjects(nextResult, prevResult)) { + return + } + + this.#currentResult = nextResult + + const shouldNotifyListeners = (): boolean => { + if (!prevResult) { + return true + } + + const { notifyOnChangeProps } = this.options + + if ( + notifyOnChangeProps === 'all' || + (notifyOnChangeProps !== 'none' && !this.#trackedProps.size) + ) { + return true + } + + if ( + this.options.throwOnError && + this.#currentResult.error !== prevResult.error + ) { + return true + } + + if (notifyOnChangeProps === 'none') { + return false + } + + for (const key of this.#trackedProps) { + if (this.#currentResult[key] !== prevResult[key]) { + return true + } + } + return false + } + + const notifyListeners = shouldNotifyListeners() + + notifyManager.batch(() => { + // First, trigger the listeners + if (notifyListeners) { + this.listeners.forEach((listener) => { + listener(this.#currentResult) + }) + } + + // Then the cache listeners + this.#client.getQueryCache().notify({ + query: this.#currentQuery, + type: 'observerResultsUpdated', + }) + }) + } + + #updateQuery(): void { + const query = this.#client.getQueryCache().build(this.#client, this.options) + + if (query === this.#currentQuery) { + return + } + + const prevQuery = this.#currentQuery as + | Query + | undefined + this.#currentQuery = query + this.#currentQueryInitialState = query.state + + if (this.hasListeners()) { + prevQuery?.removeObserver(this) + query.addObserver(this) + } + } + + /** + * Updates the observer's result when the observed query changes, and reschedules its timers if it + * has listeners. + * @internal + */ + onQueryUpdate(): void { + this.updateResult() + + if (this.hasListeners()) { + this.#updateTimers() + } + } +} + +/** + * Checks whether a query has no data yet and should do its initial load when an observer mounts. + * @param query - The query to check. + * @param options - The observer options. + * @returns `true` if the query is enabled, has no data, and isn't in an error state with + * `retryOnMount: false`. + */ +function shouldLoadOnMount( + query: Query, + options: QueryObserverOptionsBase, +): boolean { + return ( + resolveQueryValue(options.enabled, query) !== false && + query.state.data === undefined && + !( + query.state.status === 'error' && + resolveQueryValue(options.retryOnMount, query) === false + ) + ) +} + +/** + * Checks whether a query should fetch when an observer mounts: either for its initial load, or + * because it has data and `refetchOnMount` asks for a refetch. + * @param query - The query to check. + * @param options - The observer options. + * @returns `true` if the query should fetch on mount. + */ +function shouldFetchOnMount( + query: Query, + options: QueryObserverOptionsBase, +): boolean { + return ( + shouldLoadOnMount(query, options) || + (query.state.data !== undefined && + shouldFetchOn(query, options, options.refetchOnMount)) + ) +} + +/** + * Checks whether a query should fetch for a `refetchOnMount`, `refetchOnWindowFocus`, or + * `refetchOnReconnect` option. + * @param query - The query to check. + * @param options - The observer options. + * @param field - The value of the option to check. + * @returns `true` if the query is enabled, not static, and the option is `'always'`, or is not + * `false` and the query is stale. + */ +function shouldFetchOn( + query: Query, + options: QueryObserverOptionsBase, + field: (typeof options)['refetchOnMount'] & + (typeof options)['refetchOnWindowFocus'] & + (typeof options)['refetchOnReconnect'], +) { + if ( + resolveQueryValue(options.enabled, query) !== false && + resolveQueryValue(options.staleTime, query) !== 'static' + ) { + const value = resolveQueryValue(field, query) + + return value === 'always' || (value !== false && isStale(query, options)) + } + return false +} + +/** + * Checks whether a query should fetch after the observer's options change. + * @param query - The query observed with the new options. + * @param prevQuery - The query observed with the previous options. + * @param options - The new observer options. + * @param prevOptions - The previous observer options. + * @returns `true` if the query changed or was disabled before, it isn't a suspense query in an + * error state, and it is stale. + */ +function shouldFetchOptionally( + query: Query, + prevQuery: Query, + options: QueryObserverOptionsBase, + prevOptions: QueryObserverOptionsBase, +): boolean { + return ( + (query !== prevQuery || + resolveQueryValue(prevOptions.enabled, query) === false) && + (!options.suspense || query.state.status !== 'error') && + isStale(query, options) + ) +} + +/** + * Checks whether a query is stale for the given observer options. + * @param query - The query to check. + * @param options - The observer options, whose `enabled` and `staleTime` are used. + * @returns `true` if the query is enabled and its data is stale for `staleTime`. + */ +function isStale( + query: Query, + options: QueryObserverOptionsBase, +): boolean { + return ( + resolveQueryValue(options.enabled, query) !== false && + query.isStaleByTime(resolveQueryValue(options.staleTime, query)) + ) +} + +export type { QueryObserverResultReader } from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core-pluggable/src/runtime/removable.ts b/packages/react-query-no-core-pluggable/src/runtime/removable.ts new file mode 100644 index 00000000000..d6356c73845 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/removable.ts @@ -0,0 +1,65 @@ +import { isServer as isServerEnvironment } from './environmentManager' +import { timeoutManager } from './timeoutManager' +import { isValidTimeout } from './utils' +import type { ManagedTimerId } from './timeoutManager' + +/** + * The base class for cache entries that are garbage collected once nothing is using them — + * `Query` and `Mutation` both extend it. `gcTime` controls how long an unused entry is kept. + */ +export abstract class Removable { + gcTime!: number + #gcTimeout?: ManagedTimerId + + /** + * Clears the pending garbage collection timeout, so the entry is no longer scheduled for removal. + * A subclass may override this to release what it holds on to as well — `Query` also cancels any + * in-flight fetch. + */ + destroy(): void { + this.clearGcTimeout() + } + + /** + * Schedules the entry to be removed from its cache after `gcTime`, replacing any timeout scheduled + * before. Nothing is scheduled if `gcTime` is `Infinity`. + */ + protected scheduleGc(): void { + this.clearGcTimeout() + + if (isValidTimeout(this.gcTime)) { + this.#gcTimeout = timeoutManager.setTimeout(() => { + this.optionalRemove() + }, this.gcTime) + } + } + + /** + * Updates `gcTime`, keeping the longest one seen so far. Without a value, it defaults to 5 minutes + * on the client and `Infinity` on the server. + * @param newGcTime - The `gcTime` from the latest options, if any. + */ + protected updateGcTime(newGcTime: number | undefined): void { + // Default to 5 minutes (Infinity for server-side) if no gcTime is set + this.gcTime = Math.max( + this.gcTime || 0, + newGcTime ?? (isServerEnvironment() ? Infinity : 5 * 60 * 1000), + ) + } + + /** + * Cancels the scheduled removal, if there is one. + */ + protected clearGcTimeout() { + if (this.#gcTimeout !== undefined) { + timeoutManager.clearTimeout(this.#gcTimeout) + this.#gcTimeout = undefined + } + } + + /** + * Called when the garbage collection timeout fires. Subclasses remove the entry from its cache + * unless it is still in use, e.g. because it has observers. + */ + protected abstract optionalRemove(): void +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/retryer.ts b/packages/react-query-no-core-pluggable/src/runtime/retryer.ts new file mode 100644 index 00000000000..5ac6a5eece1 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/retryer.ts @@ -0,0 +1,241 @@ +import { isServer as isServerEnvironment } from './environmentManager' +import { focusManager } from './focusManager' +import { onlineManager } from './onlineManager' +import { noop, sleep } from './utils' +import type { + Retryer, + RetryerConfig, + RetryerStatus, +} from '@tanstack/query-types/bindings' +import type { CancelOptions, DefaultError, NetworkMode } from './types' + +/** + * Applies exponential backoff with jitter. The base delay starts at 1 second + * and doubles for each retry, up to 30 seconds. + * @param failureCount - The number of previous failures. Starts at 0 for the first retry. + * @returns A random delay from 80% to 100% of the base delay, in milliseconds. + */ +function defaultRetryDelay(failureCount: number) { + const baseDelay = Math.min(1000 * 2 ** failureCount, 30000) + const maxJitter = baseDelay * 0.2 + return baseDelay - Math.floor(Math.random() * (maxJitter + 1)) +} + +/** + * Checks whether a fetch can run for the given network mode. + * @param networkMode - The `networkMode` option. Defaults to `'online'`. + * @returns `true` if the network mode is not `'online'`, or if it is and the client is online. + */ +export function canFetch(networkMode: NetworkMode | undefined): boolean { + return (networkMode ?? 'online') === 'online' + ? onlineManager.isOnline() + : true +} + +/** + * The error thrown by a `Retryer` (and surfaced to `query.promise`/`mutation`) when a fetch is cancelled, e.g. via + * `query.cancel()`. `revert`, if `true`, tells the caller to restore the state the query was in before the fetch + * started instead of surfacing the error. `silent`, if `true`, tells the caller to suppress this error and instead + * resolve with the promise of the fetch that triggered the cancellation. + * @example + * ```ts + * query.cancel() + * + * try { + * await query.promise + * } catch (error) { + * if (error instanceof CancelledError) { + * // the fetch was cancelled, e.g. via `query.cancel()` + * } + * } + * ``` + */ +export class CancelledError extends Error { + revert?: boolean + silent?: boolean + constructor(options?: CancelOptions) { + super('CancelledError') + this.revert = options?.revert + this.silent = options?.silent + } +} + +/** + * Creates a retryer, which runs a function and retries it on failure according to the `retry` and + * `retryDelay` options. It pauses while the network mode doesn't allow fetching or `canRun` returns + * `false`, and can be cancelled. Queries and mutations use it to run their `queryFn` and + * `mutationFn`. + * @param config - The function to run, the retry options, and the callbacks for failures, pausing, + * continuing, and cancellation. + * @returns The retryer, whose `promise` settles with the result of the function. + */ +export function createRetryer( + config: RetryerConfig, +): Retryer { + let isRetryCancelled = false + let failureCount = 0 + let continueFn: ((value?: unknown) => void) | undefined + let status: RetryerStatus = 'pending' + const { + promise, + resolve: promiseResolve, + reject: promiseReject, + } = Promise.withResolvers() + promise.catch(noop) + + const isResolved = () => status !== 'pending' + + const cancel = (cancelOptions?: CancelOptions): void => { + if (!isResolved()) { + const error = new CancelledError(cancelOptions) as TError + reject(error) + + config.onCancel?.(error) + } + } + const cancelRetry = () => { + isRetryCancelled = true + } + + const continueRetry = () => { + isRetryCancelled = false + } + + const canContinue = () => + focusManager.isFocused() && + (config.networkMode === 'always' || onlineManager.isOnline()) && + config.canRun() + + const canStart = () => canFetch(config.networkMode) && config.canRun() + + const resolve = (value: any) => { + if (!isResolved()) { + continueFn?.() + status = 'resolved' + promiseResolve(value) + } + } + + const reject = (value: any) => { + if (!isResolved()) { + continueFn?.() + status = 'rejected' + promiseReject(value) + } + } + + const pause = (canResume: () => boolean) => { + return new Promise((continueResolve) => { + continueFn = (value) => { + if (isResolved() || canResume()) { + continueResolve(value) + } + } + config.onPause?.() + }).then(() => { + continueFn = undefined + if (!isResolved()) { + config.onContinue?.() + } + }) + } + + // Create loop function + const run = () => { + // Do nothing if already resolved + if (isResolved()) { + return + } + + let promiseOrValue: any + + // we can re-use config.initialPromise on the first call of run() + const initialPromise = + failureCount === 0 ? config.initialPromise : undefined + + // Execute query + try { + promiseOrValue = initialPromise ?? config.fn() + } catch (error) { + promiseOrValue = Promise.reject(error) + } + + Promise.resolve(promiseOrValue) + .then(resolve) + .catch((error) => { + // Stop if the fetch is already resolved + if (isResolved()) { + return + } + + // Do we need to retry the request? + const retry = config.retry ?? (isServerEnvironment() ? 0 : 3) + const retryDelay = config.retryDelay ?? defaultRetryDelay + const delay = + typeof retryDelay === 'function' + ? retryDelay(failureCount, error) + : retryDelay + const shouldRetry = + retry === true || + (typeof retry === 'number' && failureCount < retry) || + (typeof retry === 'function' && retry(failureCount, error)) + + if (isRetryCancelled || !shouldRetry) { + // We are done if the query does not need to be retried + reject(error) + return + } + + failureCount++ + + // Notify on fail + config.onFail?.(failureCount, error) + + // Delay + sleep(delay) + // Pause if the document is not visible or when the device is offline + .then(() => { + return isResolved() || canContinue() + ? undefined + : pause(canContinue) + }) + .then(() => { + if (isRetryCancelled) { + reject(error) + } else { + run() + } + }) + }) + } + + return { + promise, + status: () => status, + cancel, + continue: () => { + continueFn?.() + return promise + }, + cancelRetry, + continueRetry, + canStart, + start: () => { + // Start loop + if (canStart()) { + run() + } else { + // Waiting to start (e.g. queued behind a scope) does not depend on focus, + // only on the same conditions that allow starting in the first place + pause(canStart).then(run) + } + return promise + }, + } +} + +export type { + Retryer, + RetryValue, + RetryDelayValue, +} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts b/packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts new file mode 100644 index 00000000000..26f50dded36 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts @@ -0,0 +1,49 @@ +import type { RuntimeBinding } from '@tanstack/query-types/bindings' +import type { Mutation } from './mutation' +import type { MutationCache } from './mutationCache' +import type { MutationObserver } from './mutationObserver' +import type { Query } from './query' +import type { QueryCache } from './queryCache' +import type { QueryClient } from './queryClient' +import type { QueryObserver } from './queryObserver' +import type { QueryKey } from './types' + +/** Binds shared option and callback types to the concrete classes in this runtime. */ +export interface QueryRuntime extends RuntimeBinding { + QueryClient: QueryClient + QueryCache: QueryCache + MutationCache: MutationCache + Query: this['args'] extends [ + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryKey extends QueryKey, + ] + ? Query + : never + Mutation: this['args'] extends [ + infer TData, + infer TError, + infer TVariables, + infer TOnMutateResult, + ] + ? Mutation + : never + QueryObserver: this['args'] extends [ + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryData, + infer TQueryKey extends QueryKey, + ] + ? QueryObserver + : never + MutationObserver: this['args'] extends [ + infer TData, + infer TError, + infer TVariables, + infer TOnMutateResult, + ] + ? MutationObserver + : never +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/streamedQuery.ts b/packages/react-query-no-core-pluggable/src/runtime/streamedQuery.ts new file mode 100644 index 00000000000..6efb1dbfcdd --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/streamedQuery.ts @@ -0,0 +1,112 @@ +import { addConsumeAwareSignal, fetchSignal } from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { QueryRuntime } from './runtimeBinding' +import type { OmitKeyof, QueryFunction, QueryKey } from './types' +import type { FetchSignalContext } from './utils' + +type StreamedQueryParams< + TQueryFnData, + TData, + TQueryKey extends QueryKey, +> = Shared.StreamedQueryParams + +/** + * Creates a query function that streams data from an `AsyncIterable`. + * By default, the query collects chunks into an array in the order they arrive. + * If there is no cached data, the first chunk moves the query from `pending` to `success`. + * If the stream ends without producing any chunks, the query uses the cached data or + * the initial value. With a `'replace'` refetch, it uses the initial value. + * The query's `fetchStatus` stays `fetching` while the stream is active. + * Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`. + * If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes. + * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional + * `refetchMode`, `reducer`, and `initialValue` options. + * @returns A query function to pass as `queryFn`. + * @example + * ```ts + * await queryClient.query({ + * queryKey: ['data'], + * queryFn: streamedQuery({ + * streamFn: fetchDataInChunks, + * }), + * }) + * ``` + */ +export function streamedQuery< + TQueryFnData = unknown, + TData = Array, + TQueryKey extends QueryKey = QueryKey, +>({ + streamFn, + refetchMode = 'reset', + reducer = (items, chunk) => + [...(items as Array), chunk] as TData, + initialValue = [] as TData, +}: StreamedQueryParams): QueryFunction< + TData, + TQueryKey +> { + return async (context) => { + const signalContext: FetchSignalContext = context + const signal = signalContext[fetchSignal] + if (signal?.aborted) { + return initialValue + } + + const query = context.client + .getQueryCache() + .find({ queryKey: context.queryKey, exact: true }) + const isRefetch = !!query && query.isFetched() + if (isRefetch && refetchMode === 'reset') { + query.setState({ + ...query.resetState, + fetchStatus: 'fetching', + }) + } + + let result = initialValue + + let cancelled = false as boolean + const streamFnContext = addConsumeAwareSignal< + OmitKeyof + >( + { + client: context.client, + meta: context.meta, + queryKey: context.queryKey, + pageParam: context.pageParam, + }, + () => context.signal, + () => (cancelled = true), + signal, + ) + + const isStreamInactive = () => cancelled || signal?.aborted === true + const stream = await streamFn(streamFnContext) + + const isReplaceRefetch = isRefetch && refetchMode === 'replace' + + for await (const chunk of stream) { + if (isStreamInactive()) { + break + } + + if (isReplaceRefetch) { + // don't append to the cache directly when replace-refetching + result = reducer(result, chunk) + } else { + context.client.setQueryData(context.queryKey, (prev) => + reducer(prev === undefined ? initialValue : prev, chunk), + ) + } + } + + // finalize result: replace-refetching needs to write to the cache + if (isReplaceRefetch && !isStreamInactive()) { + context.client.setQueryData(context.queryKey, result) + } + + const data = context.client.getQueryData(context.queryKey) + return data === undefined ? initialValue : data + } +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/subscribable.ts b/packages/react-query-no-core-pluggable/src/runtime/subscribable.ts new file mode 100644 index 00000000000..8b40e3ce868 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/subscribable.ts @@ -0,0 +1,65 @@ +/** + * The base class behind everything in Query that you can subscribe to: `QueryCache`, `MutationCache`, + * the observers, and the `FocusManager`/`OnlineManager` behind `focusManager` and `onlineManager`. + * Subclasses decide what a listener receives and when it is called. + */ +export class Subscribable< + // oxlint-disable-next-line typescript/no-unsafe-function-type -- also accepts construct signatures and functions with extra properties, which a call signature would reject + TListener extends Function, +> { + protected listeners = new Set() + + constructor() { + this.subscribe = this.subscribe.bind(this) + } + + /** + * Registers a listener to be called on every update this object notifies about. Returns a function + * that removes the listener again — call it to stop listening. The base class never drops a listener + * on its own, though some subclasses clear all of theirs in `destroy()`. + * @param listener - Called on each update, with whatever the subclass passes to its subscribers. + * @returns A function that removes the listener. + * @example + * ```ts + * const unsubscribe = subscribable.subscribe(() => { + * // react to the update + * }) + * + * unsubscribe() + * ``` + */ + subscribe(listener: TListener): () => void { + this.listeners.add(listener) + + this.onSubscribe() + + return () => { + this.listeners.delete(listener) + this.onUnsubscribe() + } + } + + /** + * Returns `true` while at least one listener is registered, `false` once they have all unsubscribed. + * @returns `true` if at least one listener is registered. + */ + hasListeners(): boolean { + return this.listeners.size > 0 + } + + /** + * Called after a listener is added. Does nothing here; subclasses override it, e.g. to start + * tracking what they observe once the first listener subscribes. + */ + protected onSubscribe(): void { + // Do nothing + } + + /** + * Called after a listener is removed. Does nothing here; subclasses override it, e.g. to clean up + * once the last listener unsubscribes. + */ + protected onUnsubscribe(): void { + // Do nothing + } +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts b/packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts new file mode 100644 index 00000000000..898b8f3bda5 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts @@ -0,0 +1,223 @@ +import type { + ManagedTimerId, + SystemTimerId, + TimeoutCallback, + TimeoutProvider, +} from '@tanstack/query-types/bindings' + +export const defaultTimeoutProvider: TimeoutProvider = { + // We need the wrapper function syntax below instead of direct references to + // global setTimeout etc. + // + // BAD: `setTimeout: setTimeout` + // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)` + // + // If we use direct references here, then anything that wants to spy on or + // replace the global setTimeout (like tests) won't work since we'll already + // have a hard reference to the original implementation at the time when this + // file was imported. + setTimeout: (callback, delay) => setTimeout(callback, delay), + clearTimeout: (timeoutId) => + clearTimeout(timeoutId as SystemTimerId | undefined), + + setInterval: (callback, delay) => setInterval(callback, delay), + clearInterval: (intervalId) => + clearInterval(intervalId as SystemTimerId | undefined), +} + +/** + * Allows customization of how timeouts are created. + * + * The query runtime uses timeouts to implement `staleTime` + * and `gcTime`. The default TimeoutManager provider uses the platform's global + * `setTimeout` implementation, which is known to have scalability issues with + * thousands of timeouts on the event loop. + * + * If you hit this limitation, consider providing a custom TimeoutProvider that + * coalesces timeouts. + */ +export class TimeoutManager implements Omit { + // We cannot have TimeoutManager as we must instantiate it with a concrete + // type at app boot; and if we leave that type, then any new timer provider + // would need to support the default provider's concrete timer ID, which is + // infeasible across environments. + // + // We settle for type safety for the TimeoutProvider type, and accept that + // this class is unsafe internally to allow for extension. + #provider: TimeoutProvider = defaultTimeoutProvider + #providerCalled = false + + /** + * `setTimeoutProvider` can be used to set a custom implementation of the + * `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval` functions, + * called a `TimeoutProvider`. + * + * This may be useful if you notice event loop performance issues with + * thousands of queries. A custom TimeoutProvider could also support timer + * delays longer than the global `setTimeout` maximum delay value of about + * 24 days. + * + * It is important to call `setTimeoutProvider` before creating a + * QueryClient or queries, so that the same provider is used consistently + * for all timers in the application, since different TimeoutProviders + * cannot cancel each others' timers. + * @param provider - The `TimeoutProvider` to use for all timers from now on. + * @example + * ```ts + * import { timeoutManager, QueryClient } from '@tanstack/react-query-no-core-pluggable' + * import { CustomTimeoutProvider } from './CustomTimeoutProvider' + * + * timeoutManager.setTimeoutProvider(new CustomTimeoutProvider()) + * + * export const queryClient = new QueryClient() + * ``` + */ + setTimeoutProvider( + provider: TimeoutProvider, + ): void { + if (process.env.NODE_ENV !== 'production') { + if (this.#providerCalled && provider !== this.#provider) { + // After changing providers, `clearTimeout` will not work as expected for + // timeouts from the previous provider. + // + // Since they may allocate the same timeout ID, clearTimeout may cancel an + // arbitrary different timeout, or unexpected no-op. + // + // We could protect against this by mixing the timeout ID bits + // deterministically with some per-provider bits. + // + // We could internally queue `setTimeout` calls to `TimeoutManager` until + // some API call to set the initial provider. + console.error( + `[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`, + { previous: this.#provider, provider }, + ) + } + } + + this.#provider = provider + if (process.env.NODE_ENV !== 'production') { + this.#providerCalled = false + } + } + + /** + * `setTimeout` schedules a callback to run after approximately `delay` + * milliseconds, like the global `setTimeout` function. The callback can be + * canceled with `clearTimeout`. + * + * It returns a timer ID, which may be a number or an object that can be + * coerced to a number via `Symbol.toPrimitive`. + * @param callback - The function to call when the timeout elapses. + * @param delay - The time to wait before calling `callback`, in milliseconds. + * @returns The timer ID, to pass to {@link TimeoutManager#clearTimeout}. + * @example + * ```ts + * import { timeoutManager } from '@tanstack/react-query-no-core-pluggable' + * + * const timeoutId = timeoutManager.setTimeout( + * () => console.log('ran at:', new Date()), + * 1000, + * ) + * + * const timeoutIdNumber: number = Number(timeoutId) + * ``` + */ + setTimeout(callback: TimeoutCallback, delay: number): ManagedTimerId { + if (process.env.NODE_ENV !== 'production') { + this.#providerCalled = true + } + return this.#provider.setTimeout(callback, delay) + } + + /** + * `clearTimeout` cancels a timeout callback scheduled with `setTimeout`, + * like the global `clearTimeout` function. It should be called with a + * timer ID returned by `setTimeout`. + * @param timeoutId - The timer ID returned by `setTimeout`, or `undefined`. + * @example + * ```ts + * import { timeoutManager } from '@tanstack/react-query-no-core-pluggable' + * + * const timeoutId = timeoutManager.setTimeout( + * () => console.log('ran at:', new Date()), + * 1000, + * ) + * + * timeoutManager.clearTimeout(timeoutId) + * ``` + */ + clearTimeout(timeoutId: ManagedTimerId | undefined): void { + this.#provider.clearTimeout(timeoutId) + } + + /** + * `setInterval` schedules a callback to be called approximately every + * `delay` milliseconds, like the global `setInterval` function. + * + * Like `setTimeout`, it returns a timer ID, which may be a number or an + * object that can be coerced to a number via `Symbol.toPrimitive`. + * @param callback - The function to call on every interval. + * @param delay - The time between calls, in milliseconds. + * @returns The timer ID, to pass to {@link TimeoutManager#clearInterval}. + * @example + * ```ts + * import { timeoutManager } from '@tanstack/react-query-no-core-pluggable' + * + * const intervalId = timeoutManager.setInterval( + * () => console.log('ran at:', new Date()), + * 1000, + * ) + * ``` + */ + setInterval(callback: TimeoutCallback, delay: number): ManagedTimerId { + if (process.env.NODE_ENV !== 'production') { + this.#providerCalled = true + } + return this.#provider.setInterval(callback, delay) + } + + /** + * `clearInterval` can be used to cancel an interval, like the global + * `clearInterval` function. It should be called with an interval ID + * returned by `setInterval`. + * @param intervalId - The timer ID returned by `setInterval`, or `undefined`. + * @example + * ```ts + * import { timeoutManager } from '@tanstack/react-query-no-core-pluggable' + * + * const intervalId = timeoutManager.setInterval( + * () => console.log('ran at:', new Date()), + * 1000, + * ) + * + * timeoutManager.clearInterval(intervalId) + * ``` + */ + clearInterval(intervalId: ManagedTimerId | undefined): void { + this.#provider.clearInterval(intervalId) + } +} + +/** + * Singleton instance of {@link TimeoutManager}, used throughout TanStack Query to schedule and cancel timers. + */ +export const timeoutManager = new TimeoutManager() + +/** + * In many cases code wants to delay to the next event loop tick; this is not + * mediated by {@link timeoutManager}. + * + * This function is provided to make auditing the query runtime for + * incorrect use of system `setTimeout` easier. + * @param callback - The function to call on the next event loop tick. + */ +export function systemSetTimeoutZero(callback: TimeoutCallback): void { + setTimeout(callback, 0) +} + +export type { + TimeoutCallback, + ManagedTimerId, + TimeoutProvider, +} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core-pluggable/src/runtime/types.ts b/packages/react-query-no-core-pluggable/src/runtime/types.ts new file mode 100644 index 00000000000..b4bcad20394 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/types.ts @@ -0,0 +1,459 @@ +import type * as Shared from '@tanstack/query-types/bindings' +import type { + DefaultError, + InfiniteData, + QueryKey, + UnsetMarker as unsetMarkerType, + dataTagErrorSymbol as dataTagErrorSymbolType, + dataTagSymbol as dataTagSymbolType, +} from '@tanstack/query-types/bindings' +import type { QueryClientPlugin } from './clientFeatures' +import type { QueryRuntime } from './runtimeBinding' + +export const dataTagSymbol: dataTagSymbolType = Symbol.for( + '@tanstack/query/dataTagSymbol', +) as dataTagSymbolType +/** + * The type of the `dataTagSymbol` key, under which a {@link DataTag} stores its data type. + */ +export type dataTagSymbol = typeof dataTagSymbol +export const dataTagErrorSymbol: dataTagErrorSymbolType = Symbol.for( + '@tanstack/query/dataTagErrorSymbol', +) as dataTagErrorSymbolType +/** + * The type of the `dataTagErrorSymbol` key, under which a {@link DataTag} stores its error type. + */ +export type dataTagErrorSymbol = typeof dataTagErrorSymbol +export const unsetMarker: unsetMarkerType = Symbol.for( + '@tanstack/query/unsetMarker', +) as unsetMarkerType + +export type QueryFunction< + T = unknown, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.QueryFunction + +export type StaleTimeFunction< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = Shared.StaleTimeFunction< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey +> + +export type QueryBooleanOption< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = Shared.QueryBooleanOption< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey +> + +export type QueryPersister< + T = unknown, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.QueryPersister + +export type QueryFunctionContext< + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.QueryFunctionContext + +// oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes every function-like value, including constructors, from the value branch + +export type PlaceholderDataFunction< + TQueryFnData = unknown, + TError = DefaultError, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = Shared.PlaceholderDataFunction< + QueryRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey +> + +export type QueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.QueryOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> + +export type ThrowOnError< + TQueryFnData, + TError, + TQueryData, + TQueryKey extends QueryKey, +> = Shared.ThrowOnError< + QueryRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey +> + +export type QueryObserverOptionsBase< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.QueryObserverOptionsBase< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> + +export type QueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.QueryObserverOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> + +export type DefaultedQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.DefaultedQueryObserverOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> + +export type InfiniteQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = Shared.InfiniteQueryObserverOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> + +export type DefaultedInfiniteQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = Shared.DefaultedInfiniteQueryObserverOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> + +export type QueryExecuteOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.QueryExecuteOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> + +export type InfiniteQueryExecuteOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = Shared.InfiniteQueryExecuteOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> + +export type InvalidateQueryFilters = + Shared.InvalidateQueryFilters + +export type RefetchQueryFilters = + Shared.RefetchQueryFilters + +export type MutationFunctionContext = + Shared.MutationFunctionContext + +export type MutationFunction< + TData = unknown, + TVariables = unknown, +> = Shared.MutationFunction + +export type MutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationOptions< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutationObserverOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationObserverOptions< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutateOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutateOptions< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutateFunctionRest< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutateFunctionRest< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutateFunction< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutateFunction< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutationObserverBaseResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationObserverBaseResult< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutationObserverIdleResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationObserverIdleResult< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutationObserverLoadingResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationObserverLoadingResult< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutationObserverErrorResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationObserverErrorResult< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutationObserverSuccessResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationObserverSuccessResult< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutationObserverResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationObserverResult< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type QueryClientConfig = Shared.QueryClientConfig & { + plugins?: ReadonlyArray +} + +export type DefaultOptions = Shared.DefaultOptions< + QueryRuntime, + TError +> + +export type { + NonUndefinedGuard, + DistributiveOmit, + OmitKeyof, + Override, + Register, + DefaultError, + QueryKey, + 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, + QueryObserverResult, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverPendingResult, + InfiniteQueryObserverLoadingResult, + InfiniteQueryObserverLoadingErrorResult, + InfiniteQueryObserverRefetchErrorResult, + InfiniteQueryObserverSuccessResult, + InfiniteQueryObserverPlaceholderResult, + DefinedInfiniteQueryObserverResult, + InfiniteQueryObserverResult, + MutationKey, + MutationStatus, + MutationScope, + MutationMeta, + CancelOptions, + SetDataOptions, + NotifyEventType, + NotifyEvent, +} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core-pluggable/src/runtime/utils.ts b/packages/react-query-no-core-pluggable/src/runtime/utils.ts new file mode 100644 index 00000000000..2ffd6135e6a --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/utils.ts @@ -0,0 +1,748 @@ +import { timeoutManager } from './timeoutManager' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + DefaultQueryFn, + DefaultQueryFn as defaultQueryFnType, + FetchSignal as fetchSignalType, + SkipToken, + SkipToken as skipTokenType, + Updater, +} from '@tanstack/query-types/bindings' +import type { Mutation } from './mutation' +import type { FetchOptions, Query } from './query' +import type { QueryRuntime } from './runtimeBinding' +import type { + CacheKeyConfig, + DefaultError, + EqualityFn, + MutationKey, + QueryFunction, + QueryKey, + QueryOptions, +} from './types' + +export type QueryFilters = + Shared.QueryFilters + +export type MutationFilters< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> = Shared.MutationFilters< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +// UTILS + +/** + * A function that does nothing. + */ +export function noop(): void +export function noop(): undefined +export function noop() {} + +/** + * Resolves an {@link Updater}: calls it with `input` if it is a function, otherwise returns it as + * is. + * @param updater - The new value, or a function that receives `input` and returns the new value. + * @param input - The current value, passed to `updater` if it is a function. + * @returns The new value. + */ +export function functionalUpdate( + updater: Updater, + input: TInput, +): TOutput { + return typeof updater === 'function' + ? (updater as (_: TInput) => TOutput)(input) + : updater +} + +/** + * Checks whether a value can be used as a timeout: a non-negative, finite number. + * @param value - The value to check. + * @returns `true` if `value` is a number that is `>= 0` and not `Infinity`. + */ +export function isValidTimeout(value: unknown): value is number { + return typeof value === 'number' && value >= 0 && value !== Infinity +} + +/** + * Calculates how long until data updated at `updatedAt` becomes stale. + * @param updatedAt - The timestamp, in milliseconds, at which the data was last updated. + * @param staleTime - The time, in milliseconds, after which data is considered stale. Defaults to + * `0`. + * @returns The remaining time in milliseconds, or `0` if the data is already stale. + */ +export function timeUntilStale(updatedAt: number, staleTime?: number): number { + return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0) +} + +/** + * Resolves an option that can be given either as a value or as a function of the query, such as + * `staleTime`. + * @param value - The option value, or a function that receives `query` and returns the value. + * @param query - The query passed to `value` if it is a function. + * @returns The resolved value, or `undefined` if `value` is `undefined`. + */ +export function resolveQueryValue< + TValue, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + value: + | undefined + | TValue + | ((query: Query) => TValue), + query: Query, +): TValue | undefined { + return typeof value === 'function' + ? ( + value as ( + query: Query, + ) => TValue + )(query) + : value +} + +/** + * Checks whether a query matches the given {@link QueryFilters}. + * Every filter that is specified must match; filters that are left unspecified are ignored. + * @param filters - The filters to check the query against. + * @param query - The query to check. + * @param keyConfig - The cache configuration for key comparison and hashing. + * @returns `true` if the query matches every specified filter. + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * + * const matchingQueries = queryCache + * .getAll() + * .filter((query) => matchQuery({ queryKey: ['posts'] }, query)) + * ``` + */ +export function matchQuery( + filters: QueryFilters, + query: Query, + keyConfig?: CacheKeyConfig, +): boolean { + const { + type = 'all', + exact, + fetchStatus, + predicate, + queryKey, + stale, + } = filters + + if (queryKey) { + if (exact) { + if (query.queryHash !== hashKeyByOptions(queryKey, keyConfig)) { + return false + } + } else if ( + !partialMatchKey(query.queryKey, queryKey, keyConfig?.equalityFn) + ) { + return false + } + } + + if (type !== 'all') { + const isActive = query.isActive() + if (type === 'active' && !isActive) { + return false + } + if (type === 'inactive' && isActive) { + return false + } + } + + if (typeof stale === 'boolean' && query.isStale() !== stale) { + return false + } + + if (fetchStatus && fetchStatus !== query.state.fetchStatus) { + return false + } + + if (predicate && !predicate(query)) { + return false + } + + return true +} + +/** + * Checks whether a mutation matches the given {@link MutationFilters}. + * Every filter that is specified must match; filters that are left unspecified are ignored. + * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match. + * @param filters - The filters to check the mutation against. + * @param mutation - The mutation to check. + * @param keyConfig - The cache configuration for key comparison and hashing. + * @returns `true` if the mutation matches every specified filter. + * @example + * ```ts + * const mutationCache = queryClient.getMutationCache() + * + * const matchingMutations = mutationCache + * .getAll() + * .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation)) + * ``` + */ +export function matchMutation( + filters: MutationFilters, + mutation: Mutation, + keyConfig?: CacheKeyConfig, +): boolean { + const { exact, status, predicate, mutationKey } = filters + if (mutationKey) { + if (!mutation.options.mutationKey) { + return false + } + if (exact) { + if ( + hashKeyByOptions(mutation.options.mutationKey, keyConfig) !== + hashKeyByOptions(mutationKey, keyConfig) + ) { + return false + } + } else if ( + !partialMatchKey( + mutation.options.mutationKey, + mutationKey, + keyConfig?.equalityFn, + ) + ) { + return false + } + } + + if (status && mutation.state.status !== status) { + return false + } + + if (predicate && !predicate(mutation)) { + return false + } + + return true +} + +/** + * Hashes a cache key with the cache's `hashFn`, falling back to {@link hashKey}. + * @param cacheKey - The query or mutation key to hash. + * @param keyConfig - The cache configuration that may provide a custom `hashFn`. + * @returns The hash, a string that identifies the key in the cache. + */ +export function hashKeyByOptions< + TCacheKey extends ReadonlyArray = ReadonlyArray, +>( + cacheKey: TCacheKey, + keyConfig: CacheKeyConfig | undefined, +): string { + const hashFn = keyConfig?.hashFn ?? hashKey + return hashFn(cacheKey) +} + +/** + * Default query & mutation keys hash function. + * Hashes the value into a stable hash. + * @param queryKey - The query or mutation key to hash. + * @returns The stable hash of the key, as a JSON string. + * @example + * ```ts + * // Object keys are sorted, so key order doesn't affect the hash: + * hashKey(['todos', { page: 1, filter: 'done' }]) // === '["todos",{"filter":"done","page":1}]' + * ``` + */ +export function hashKey(queryKey: QueryKey | MutationKey): string { + return JSON.stringify(queryKey, (_, val) => + isPlainObject(val) + ? Object.keys(val) + .sort() + .reduce((result, key) => { + result[key] = val[key] + return result + }, {} as any) + : val, + ) +} + +const defaultEqualityFn: EqualityFn = (a, b) => a === b + +/** + * Checks if key `b` partially matches with key `a`. + * @param a - The key to check, e.g. a query's own key. + * @param b - The (partial) key to match against `a`. + * @param equalityFn - Compares individual key values. Defaults to strict equality. + * @returns `true` if every array element or object property in `b` matches the one at the same + * position in `a`. + */ +export function partialMatchKey( + a: QueryKey, + b: QueryKey, + equalityFn?: EqualityFn, +): boolean +export function partialMatchKey( + a: unknown, + b: unknown, + equalityFn?: EqualityFn, +): boolean +export function partialMatchKey( + a: any, + b: any, + equalityFn: EqualityFn = defaultEqualityFn, +): boolean { + if (equalityFn(a, b)) { + return true + } + + if (typeof a !== typeof b) { + return false + } + + if (isPlainArray(a) && isPlainArray(b)) { + if (b.length > a.length) return false + for (let i = 0; i < b.length; i++) { + if (!partialMatchKey(a[i], b[i], equalityFn)) { + return false + } + } + return true + } + + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b) + for (const key of bKeys) { + if (!partialMatchKey(a[key], b[key], equalityFn)) { + return false + } + } + return true + } + + return false +} + +/** + * This function returns `a` if `b` is deeply equal. + * If not, it will replace any deeply equal children of `b` with those of `a`. + * This can be used for structural sharing between JSON values for example. + * An optional equality function can be used for custom value types. + * @param a - The previous value, whose deeply equal parts are reused. + * @param b - The new value. + * @param equalityFn - Compares values for structural sharing. Defaults to strict equality. + * @returns `a` if `b` is deeply equal to it, otherwise `b` with its deeply equal parts replaced by + * those of `a`. + */ +export function replaceEqualDeep( + a: unknown, + b: T, + equalityFn?: EqualityFn, +): T +export function replaceEqualDeep( + a: any, + b: any, + equalityFn: EqualityFn = defaultEqualityFn, +): any { + return replaceEqualDeepInternal(a, b, equalityFn, 0) +} + +/** + * Reuses deeply equal values while limiting recursion to 500 levels. + * @param a - The previous value. + * @param b - The new value. + * @param equalityFn - Compares values for structural sharing. + * @param depth - The current recursion depth. + * @returns The new value with deeply equal parts of the previous value reused. + */ +function replaceEqualDeepInternal( + a: any, + b: any, + equalityFn: EqualityFn, + depth: number, +): any { + if (equalityFn(a, b)) { + return a + } + + if (depth > 500) return b + + const array = isPlainArray(a) && isPlainArray(b) + + if (!array && !(isPlainObject(a) && isPlainObject(b))) return b + + const aItems = array ? a : Object.keys(a) + const aSize = aItems.length + const bItems = array ? b : Object.keys(b) + const bSize = bItems.length + const copy: any = array ? new Array(bSize) : {} + + let equalItems = 0 + + for (let i = 0; i < bSize; i++) { + const key: any = array ? i : bItems[i] + const aItem = a[key] + const bItem = b[key] + + if (equalityFn(aItem, bItem)) { + copy[key] = aItem + if (array ? i < aSize : Object.hasOwn(a, key)) equalItems++ + continue + } + + if ( + aItem === null || + bItem === null || + typeof aItem !== 'object' || + typeof bItem !== 'object' + ) { + copy[key] = bItem + continue + } + + const v = replaceEqualDeepInternal(aItem, bItem, equalityFn, depth + 1) + copy[key] = v + if (v === aItem) equalItems++ + } + + return aSize === bSize && equalItems === aSize ? a : copy +} + +/** + * Shallow compare objects. + * @param a - The first object. + * @param b - The second object, or `undefined`. + * @returns `true` if both objects have the same keys, with strictly equal values for each key. + */ +export function shallowEqualObjects>( + a: T, + b: T | undefined, +): boolean { + if (!b || Object.keys(a).length !== Object.keys(b).length) { + return false + } + + for (const key of Object.keys(a)) { + if (!Object.hasOwn(b, key) || a[key] !== b[key]) { + return false + } + } + + return true +} + +/** + * Checks whether a value is an array with no holes and no extra properties. + * @param value - The value to check. + * @returns `true` if `value` is an array whose number of own keys equals its `length`. + */ +export function isPlainArray(value: unknown): value is Array { + return Array.isArray(value) && value.length === Object.keys(value).length +} + +// Copied from: https://github.com/jonschlinkert/is-plain-object +/** + * Checks whether a value is a plain object, e.g. created with an object literal or + * `Object.create(null)`. + * @param o - The value to check. + * @returns `true` if `o` is a plain object. + */ +export function isPlainObject(o: any): o is Record { + if (!hasObjectPrototype(o)) { + return false + } + + // If has no constructor + const objectPrototype = Object.getPrototypeOf(o) + const ctor = objectPrototype?.constructor + if (ctor === undefined) { + return true + } + + if (typeof ctor !== 'function') { + return false + } + + // If has modified prototype + const prot = ctor.prototype + if (!hasObjectPrototype(prot)) { + return false + } + + // If constructor does not have an Object-specific method + if (!prot.hasOwnProperty('isPrototypeOf')) { + return false + } + + // Handles Objects created by Object.create() + if (objectPrototype !== Object.prototype) { + return false + } + + // Most likely a plain Object + return true +} + +/** + * Checks whether a value's `Object.prototype.toString` tag is `[object Object]`. + * @param o - The value to check. + * @returns `true` if the tag is `[object Object]`. + */ +function hasObjectPrototype(o: any): boolean { + return Object.prototype.toString.call(o) === '[object Object]' +} + +/** + * Waits for the given time, using the configured {@link timeoutManager}. + * @param timeout - The time to wait, in milliseconds. + * @returns A promise that resolves after `timeout` milliseconds. + */ +export function sleep(timeout: number): Promise { + return new Promise((resolve) => { + timeoutManager.setTimeout(resolve, timeout) + }) +} + +/** + * Applies a query's `structuralSharing` option when writing new data. + * @param prevData - The previously cached data. + * @param data - The new data. + * @param options - The query options, whose `structuralSharing` decides how the data is merged. + * @returns The result of a custom `structuralSharing` function, `data` with its unchanged parts + * replaced by those of `prevData` by default, or `data` as is if `structuralSharing` is `false`. + * @throws {Error} The error from the default structural sharing, e.g. when the data is not JSON serializable. + * Outside production, it is also logged to the console. + */ +export function replaceData< + TData, + TOptions extends QueryOptions, +>(prevData: TData | undefined, data: TData, options: TOptions): TData { + if (typeof options.structuralSharing === 'function') { + return options.structuralSharing(prevData, data) as TData + } else if (options.structuralSharing !== false) { + if (process.env.NODE_ENV !== 'production') { + try { + return replaceEqualDeep(prevData, data) + } catch (error) { + console.error( + `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`, + ) + + // Prevent the replaceEqualDeep from being called again down below. + throw error + } + } + // Structurally share data between prev and new data if needed + return replaceEqualDeep(prevData, data) + } + return data +} + +/** + * Intended to be passed as a query's `placeholderData` option, for example + * `placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new + * query key is fetching, it keeps displaying the previously fetched data until the new data arrives. + * @param previousData - The data of the previous query key, passed by the observer. + * @returns The previous data, unchanged. + * @example + * ```ts + * new QueryObserver(queryClient, { + * queryKey: ['posts', page], + * queryFn: () => fetchPosts(page), + * placeholderData: keepPreviousData, + * }) + * ``` + */ +export function keepPreviousData( + previousData: T | undefined, +): T | undefined { + return previousData +} + +/** + * Adds an item to one end of a new array. If the result exceeds `max`, removes + * excess items from the opposite end. + * @param items - The current items. + * @param item - The value to add. + * @param max - The maximum number of items to keep. Omit it or use `0` for no limit. + * @param prepend - Pass `true` to add at the start. The default is to add at the end. + * @returns A new array with `item` added. + */ +export function addToArray( + items: Array, + item: T, + max?: number, + prepend?: boolean, +): Array { + const newItems = prepend ? [item, ...items] : [...items, item] + if (max && newItems.length > max) { + return prepend ? newItems.slice(0, max) : newItems.slice(-max) + } + return newItems +} + +/** + * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent + * to `enabled: false`) while preserving full type inference for the query's data. Unlike `enabled: false`, + * a query disabled via `skipToken` cannot be triggered with `refetch`. + * @example + * ```ts + * new QueryObserver(queryClient, { + * queryKey: ['post', postId], + * queryFn: postId != null ? () => fetchPost(postId) : skipToken, + * }) + * ``` + */ +export const skipToken: skipTokenType = Symbol.for( + '@tanstack/query/skipToken', +) as skipTokenType + +/** + * Pass this as `queryFn` to use the query function configured on the client. + * The defaults for the query key take precedence over the client's global query defaults. + * If no query function is configured, a fetch fails with a `Missing queryFn` error. + */ +export const defaultQueryFn: defaultQueryFnType = Symbol.for( + '@tanstack/query/defaultQueryFn', +) as defaultQueryFnType + +/** + * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from + * an `initialPromise`, that promise is returned instead. If there is no usable `queryFn`, the returned + * function rejects with a `Missing queryFn` error. + * @param options - The query options with the `queryFn`, and the `queryHash` used in error messages. + * @param fetchOptions - The fetch options, which may carry an `initialPromise`. + * @returns The function to call for the fetch. + */ +export function ensureQueryFn< + TQueryFnData = unknown, + TQueryKey extends QueryKey = QueryKey, +>( + options: { + queryFn?: + | QueryFunction + | SkipToken + | DefaultQueryFn + queryHash?: string + }, + fetchOptions?: FetchOptions, +): QueryFunction { + if (process.env.NODE_ENV !== 'production') { + if (options.queryFn === skipToken) { + console.error( + `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`, + ) + } + } + + // if we attempt to retry a fetch that was triggered from an initialPromise + // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise + // if an observer has already mounted, we will be able to retry with that queryFn + if (!options.queryFn && fetchOptions?.initialPromise) { + return () => fetchOptions.initialPromise! + } + + if ( + !options.queryFn || + options.queryFn === skipToken || + options.queryFn === defaultQueryFn + ) { + return () => + Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`)) + } + + return options.queryFn +} + +/** + * Resolves a `throwOnError` option to a boolean. + * If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller, + * additional context such as the query or mutation) and its result is returned, allowing the throwing + * behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined` + * resolves to `false`). + * @param throwOnError - The `throwOnError` option: a boolean, a function that decides per error, or + * `undefined`. + * @param params - The arguments passed to `throwOnError` if it is a function. + * @returns Whether the error should be thrown. + * @example + * ```ts + * const throwOnError = + * query.state.error && typeof options.throwOnError === 'function' + * ? shouldThrowError(options.throwOnError, [query.state.error, query]) + * : options.throwOnError + * ``` + */ +export function shouldThrowError) => boolean>( + throwOnError: boolean | T | undefined, + params: Parameters, +): boolean { + // Allow throwOnError function to override throwing behavior on a per-error basis + if (typeof throwOnError === 'function') { + return throwOnError(...params) + } + + return !!throwOnError +} + +export const fetchSignal: fetchSignalType = Symbol.for( + '@tanstack/query/fetchSignal', +) as fetchSignalType + +/** + * Adds a lazy `signal` getter to an object, such as a query function context. The first time + * `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right + * away if it is already aborted), so cancellation is only tracked when the signal is actually used. + * @param object - The object to add the `signal` property to. + * @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read. + * @param onCancelled - Called when the signal is aborted, if `signal` was read. + * @param internalSignal - The fetch signal to forward without consuming the getter. + * @returns The same object, with the `signal` property added. + */ +export function addConsumeAwareSignal( + object: T, + getSignal: () => AbortSignal, + onCancelled: () => void, + internalSignal?: AbortSignal, +): T & { signal: AbortSignal } { + let consumed = false + let signal: AbortSignal | undefined + + Object.defineProperties(object, { + [fetchSignal]: { value: internalSignal }, + signal: { + enumerable: true, + get: () => { + signal ??= getSignal() + if (consumed) { + return signal + } + + consumed = true + if (signal.aborted) { + onCancelled() + } else { + signal.addEventListener('abort', onCancelled, { once: true }) + } + + return signal + }, + }, + }) + + return object as T & { signal: AbortSignal } +} + +export type { + Updater, + QueryTypeFilter, + SkipToken, + DefaultQueryFn, + FetchSignalContext, +} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core-pluggable/src/suspense.ts b/packages/react-query-no-core-pluggable/src/suspense.ts new file mode 100644 index 00000000000..4c1cb60de54 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/suspense.ts @@ -0,0 +1,214 @@ +import { use } from 'react' +import { QueryObserver } from './runtime/index' +import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import type { + DefaultError, + DefaultedQueryObserverOptions, + Query, + QueryClient, + QueryKey, + QueryObserverResult, +} from './runtime/index' + +type SuspensePromiseEntry = { + fetchPromise: Promise + promise: Promise + settled: boolean +} + +const suspensePromiseCache = new WeakMap< + Query, + SuspensePromiseEntry +>() + +/** + * Uses the nearest error boundary when the query has no data to show. + * @param _error - The query error. + * @param query - The query that failed. + * @returns Whether the query has no data. + */ +export const defaultThrowOnError = < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + _error: TError, + query: Query, +) => query.state.data === undefined + +/** + * Raises `staleTime` and a numeric `gcTime` to at least 1000ms when `suspense` is enabled, so a + * component that remounts after suspending doesn't refetch right away or find the query garbage + * collected. A `'static'` `staleTime` is kept as is. Mutates the options. + * @param defaultedOptions - The defaulted query options to adjust. + */ +export const ensureSuspenseTimers = ( + defaultedOptions: DefaultedQueryObserverOptions, +) => { + if (defaultedOptions.suspense) { + // Handle staleTime to ensure minimum 1000ms in Suspense mode + // This prevents unnecessary refetching when components remount after suspending + const MIN_SUSPENSE_TIME_MS = 1000 + + const clamp = (value: number | 'static' | undefined) => + value === 'static' + ? value + : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS) + + const originalStaleTime = defaultedOptions.staleTime + defaultedOptions.staleTime = + typeof originalStaleTime === 'function' + ? (...args) => clamp(originalStaleTime(...args)) + : clamp(originalStaleTime) + + if (typeof defaultedOptions.gcTime === 'number') { + defaultedOptions.gcTime = Math.max( + defaultedOptions.gcTime, + MIN_SUSPENSE_TIME_MS, + ) + } + } +} + +/** + * Decides whether a Suspense query needs to fetch during render. + * @param result - The result for this render. + * @param errorResetBoundary - The nearest query error reset boundary. + * @param query - The query to fetch. + * @returns `undefined` to skip the fetch, `false` to fetch in the background, or `true` to suspend. + */ +const shouldSuspend = ( + result: QueryObserverResult, + errorResetBoundary: QueryErrorResetBoundaryValue, + query: Query, +): boolean | undefined => { + if ( + result.isPending || + (query.state.status === 'error' && errorResetBoundary.isReset()) + ) { + return true + } + + if (result.isFetching && result.isPlaceholderData) { + return false + } + + return undefined +} + +/** + * Starts a fetch during render or reuses a promise for an existing fetch. + * @param defaultedOptions - The options of the query. + * @param observer - The observer that starts the fetch. + * @param errorResetBoundary - The nearest query error reset boundary. + * @param query - The query used to key the promise cache. + * @returns A promise that resolves when the fetch settles. + */ +export function getSuspensePromise( + defaultedOptions: DefaultedQueryObserverOptions, + observer: QueryObserver, + errorResetBoundary: QueryErrorResetBoundaryValue, + query: Query, +): Promise { + let entry = suspensePromiseCache.get(query) + if (!entry || entry.settled) { + const fetchPromise = observer.fetchOptimistic(defaultedOptions) + const settle = () => { + pending.settled = true + } + const pending: SuspensePromiseEntry = { + fetchPromise, + // Retry the render when the fetch settles, even on failure. + promise: fetchPromise.then(settle, settle), + settled: false, + } + suspensePromiseCache.set(query, pending) + entry = pending + } + + entry.fetchPromise.catch(() => errorResetBoundary.clearReset()) + return entry.promise +} + +type SuspenseOptions = DefaultedQueryObserverOptions +type SuspenseResult = QueryObserverResult +type SnapshotReader = { getSnapshot: () => T } + +const useReadSuspenseQuery = ( + defaultedOptions: SuspenseOptions, + reader: SnapshotReader, + observer: QueryObserver, + client: QueryClient, + errorResetBoundary: QueryErrorResetBoundaryValue, +) => { + if (!defaultedOptions.suspense) return + + const snapshot = reader.getSnapshot() + const query = client.getQueryCache().build(client, defaultedOptions) + const suspend = shouldSuspend(snapshot, errorResetBoundary, query) + if (suspend === undefined) return + + const promise = getSuspensePromise( + defaultedOptions, + observer, + errorResetBoundary, + query, + ) + if (suspend) { + use(promise) + } +} + +/** Supplies Suspense behavior for one query. */ +export const suspenseQueryPolicy = { + prepare: ensureSuspenseTimers, + readQuery: useReadSuspenseQuery, +} + +const useReadSuspenseQueries = ( + defaultedQueries: Array, + reader: SnapshotReader>, + client: QueryClient, + errorResetBoundary: QueryErrorResetBoundaryValue, +) => { + const snapshot = reader.getSnapshot() + + const suspensePromises = snapshot.map((result, index) => { + const opts = defaultedQueries[index] + + if (!opts?.suspense) { + return undefined + } + + const query = client.getQueryCache().build(client, opts) + const suspend = shouldSuspend(result, errorResetBoundary, query) + + if (suspend === undefined) { + return undefined + } + + const queryObserver = new QueryObserver(client, opts) + const promise = getSuspensePromise( + opts, + queryObserver, + errorResetBoundary, + query, + ) + + return suspend ? promise : undefined + }) + + // Start every fetch before calling use(), because use() suspends immediately. + for (const promise of suspensePromises) { + if (promise) { + use(promise) + } + } +} + +/** Supplies Suspense behavior for parallel queries. */ +export const suspenseQueriesPolicy = { + prepare: ensureSuspenseTimers, + readQueries: useReadSuspenseQueries, +} diff --git a/packages/react-query-no-core-pluggable/src/types.ts b/packages/react-query-no-core-pluggable/src/types.ts new file mode 100644 index 00000000000..c0ca73490e4 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/types.ts @@ -0,0 +1,471 @@ +/* istanbul ignore file */ + +import type { + DefaultError, + DefinedInfiniteQueryObserverResult, + DefinedQueryObserverResult, + DistributiveOmit, + InfiniteData, + InfiniteQueryExecuteOptions, + InfiniteQueryObserverOptions, + InfiniteQueryObserverPlaceholderResult, + InfiniteQueryObserverResult, + MutateFunction, + MutationObserverOptions, + MutationObserverResult, + OmitKeyof, + Override, + QueryExecuteOptions, + QueryKey, + QueryObserverOptions, + QueryObserverPlaceholderResult, + QueryObserverResult, + SkipToken, +} from './runtime/index' + +/** + * {@link UseBaseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseBaseQueryOptions = UseBaseQueryOptions< + any, + any, + any, + any, + any +> +/** + * The options shared by `useQuery` and `useSuspenseQuery`. Extends {@link QueryObserverOptions} + * with the React-specific `subscribed` option. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryData - The type of the data actually held in the query cache — the input to `select` and + * `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`. + * @template TQueryKey - The type of your `queryKey`. + */ +export interface UseBaseQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends QueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +> { + /** + * Set this to `false` to unsubscribe this observer from updates to the query cache. + * @defaultValue true + */ + subscribed?: boolean +} + +/** + * The options accepted by `usePrefetchQuery` — everything you can pass to `queryClient.query`, with a + * required `queryFn`. Pass `defaultQueryFn` to use the client defaults. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryData - The type of the data actually held in the query cache — the input to `select` and + * `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`. + * @template TQueryKey - The type of your `queryKey`. + */ +export type UsePrefetchQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = DistributiveOmit< + QueryExecuteOptions, + 'queryFn' +> & { + /** + * Pass a query function or `defaultQueryFn` to use the client defaults. Prefetch hooks do not accept `skipToken`. + */ + queryFn: Exclude< + QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >['queryFn'], + SkipToken | undefined + > +} + +/** + * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `queryClient.infiniteQuery`, + * with a required `queryFn`. Pass `defaultQueryFn` to use the client defaults. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params — a prefetch never reads `data` back out, so this + * parameter only matters if you reuse these options elsewhere with `select` applied. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export type UsePrefetchInfiniteQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = DistributiveOmit< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + 'queryFn' +> & { + /** + * Pass a query function or `defaultQueryFn` to use the client defaults. Prefetch hooks do not accept `skipToken`. + */ + queryFn: Exclude< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >['queryFn'], + SkipToken | undefined + > +} + +/** + * {@link UseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseQueryOptions = UseQueryOptions +/** + * The options accepted by `useQuery`. Same as {@link UseBaseQueryOptions}, minus `suspense` (which + * `react-query` derives from which hook you call rather than exposing as an option). + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryKey - The type of your `queryKey`. + */ +export interface UseQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends OmitKeyof< + UseBaseQueryOptions, + 'suspense' +> {} + +/** + * {@link UseSuspenseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseSuspenseQueryOptions = UseSuspenseQueryOptions< + any, + any, + any, + any +> +/** + * Options for a `useSuspenseQuery` call whose data is defined. The options match those of + * {@link UseQueryOptions} except for `throwOnError` and `enabled`. + * Use the other overload for a query function that can be `skipToken`. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryKey - The type of your `queryKey`. + */ +export interface UseSuspenseQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends OmitKeyof< + UseQueryOptions, + 'queryFn' | 'enabled' | 'throwOnError' +> { + /** + * The query function. Use `defaultQueryFn` to use the client's configured function. + */ + queryFn: Exclude< + UseQueryOptions['queryFn'], + SkipToken + > +} + +/** + * {@link UseInfiniteQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseInfiniteQueryOptions = UseInfiniteQueryOptions< + any, + any, + any, + any, + any +> +/** + * The options accepted by `useInfiniteQuery`. Extends {@link InfiniteQueryObserverOptions} + * with the React-specific `subscribed` option, minus `suspense` (which + * `react-query` derives from which hook you call rather than exposing as an option). + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export interface UseInfiniteQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> extends OmitKeyof< + InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + 'suspense' +> { + /** + * Set this to `false` to unsubscribe this observer from updates to the query cache. + * @defaultValue true + */ + subscribed?: boolean +} + +/** + * {@link UseSuspenseInfiniteQueryOptions} with all type parameters set to `any`, useful when the specific types + * aren't relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseSuspenseInfiniteQueryOptions = + UseSuspenseInfiniteQueryOptions +/** + * The options accepted by `useSuspenseInfiniteQuery`. Same as {@link UseInfiniteQueryOptions}, except for + * `enabled` and `throwOnError`. If `placeholderData` provides data, the query can render while the fetch runs. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export interface UseSuspenseInfiniteQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> extends OmitKeyof< + UseInfiniteQueryOptions, + 'queryFn' | 'enabled' | 'throwOnError' +> { + /** + * The query function. Use `defaultQueryFn` to use the client defaults. Use the other overload when the function can be `skipToken`. + */ + queryFn: Exclude< + UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >['queryFn'], + SkipToken + > +} + +/** + * The result of `useQuery` when `initialData` isn't set — `data` may be `undefined` while the query is + * `pending`. Re-exports {@link QueryObserverResult}. `useInfiniteQuery` returns + * {@link UseInfiniteQueryResult} instead. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseBaseQueryResult< + TData = unknown, + TError = DefaultError, +> = QueryObserverResult + +/** + * The result of `useQuery`. Same as {@link UseBaseQueryResult}. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseQueryResult< + TData = unknown, + TError = DefaultError, +> = UseBaseQueryResult + +/** The result of `useSuspenseQuery`, including defined placeholder data when configured. */ +export type UseSuspenseQueryResult = + | DefinedQueryObserverResult + | QueryObserverPlaceholderResult + +/** + * The result of `useQuery` when `initialData` is set. The `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). + * Re-exports {@link DefinedQueryObserverResult}. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type DefinedUseQueryResult< + TData = unknown, + TError = DefaultError, +> = DefinedQueryObserverResult + +/** + * The result of `useInfiniteQuery` when `initialData` isn't set — `data` may be `undefined` while the query is + * `pending`. Re-exports {@link InfiniteQueryObserverResult}. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseInfiniteQueryResult< + TData = unknown, + TError = DefaultError, +> = InfiniteQueryObserverResult + +/** + * The result of `useInfiniteQuery` when `initialData` is set — `data` is never `undefined` (unless a + * `select` changes `TData` to include `undefined`). Re-exports {@link DefinedInfiniteQueryObserverResult} + *. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type DefinedUseInfiniteQueryResult< + TData = unknown, + TError = DefaultError, +> = DefinedInfiniteQueryObserverResult + +/** + * The result of `useSuspenseInfiniteQuery`, including defined placeholder data when configured. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseSuspenseInfiniteQueryResult< + TData = unknown, + TError = DefaultError, +> = + | DefinedInfiniteQueryObserverResult + | InfiniteQueryObserverPlaceholderResult + +/** + * {@link UseMutationOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any mutation in a helper function. + */ +export type AnyUseMutationOptions = UseMutationOptions +/** + * The options accepted by `useMutation`. Same as {@link MutationObserverOptions}, + * minus the internal `_defaulted` flag. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export interface UseMutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends OmitKeyof< + MutationObserverOptions, + '_defaulted' +> {} + +/** + * The type of `mutate`, as returned by `useMutation`. Forwards the variables (and an optional per-call + * `onSuccess`/`onError`/`onSettled`) to the underlying `mutate` call. Fire-and-forget — errors are surfaced + * through the mutation result instead of being thrown by `mutate`, unless `throwOnError` makes `useMutation` + * rethrow them. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseMutateFunction< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = ( + ...args: Parameters< + MutateFunction + > +) => void + +/** + * The type of `mutateAsync`, as returned by `useMutation`. Similar to {@link UseMutateFunction}, but returns a + * promise which can be awaited. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseMutateAsyncFunction< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = MutateFunction + +/** + * The result of `useMutation`. Same as {@link MutationObserverResult}, with + * `mutate` narrowed to the fire-and-forget {@link UseMutateFunction} signature, plus the added `mutateAsync`. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseBaseMutationResult< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> = Override< + MutationObserverResult, + { mutate: UseMutateFunction } +> & { + /** + * Similar to `mutate`, but returns a promise which can be awaited. + */ + mutateAsync: UseMutateAsyncFunction< + TData, + TError, + TVariables, + TOnMutateResult + > +} + +/** + * The result of `useMutation`. Same as {@link UseBaseMutationResult}. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseMutationResult< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> = UseBaseMutationResult diff --git a/packages/react-query-no-core-pluggable/src/useBaseQuery.ts b/packages/react-query-no-core-pluggable/src/useBaseQuery.ts new file mode 100644 index 00000000000..525dbc328d5 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/useBaseQuery.ts @@ -0,0 +1,155 @@ +'use client' +import * as React from 'react' +import { useIsRestoring } from './IsRestoringProvider' +import { useQueryClient } from './QueryClientProvider' +import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary' +import { + ensurePreventErrorBoundaryRetry, + getHasError, + useClearResetErrorBoundary, +} from './errorBoundaryUtils' +import { noop, notifyManager } from './runtime/index' +import type { + QueryClient, + QueryKey, + QueryObserver, + QueryObserverResult, +} from './runtime/index' +import type { suspenseQueryPolicy } from './suspense' +import type { UseBaseQueryOptions } from './types' + +/** + * Base implementation shared by `useQuery`, `useInfiniteQuery`, `useSuspenseQuery`, and + * `useSuspenseInfiniteQuery`. + * @param options - The options passed to the calling hook. + * @param Observer - The observer class (`QueryObserver` or + * `InfiniteQueryObserver`). + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest + * context will be used. + * @param suspense - Render policy used by the dedicated Suspense hooks. + * @returns The query result, tracking which properties are read unless `notifyOnChangeProps` is + * set. + * @throws {Error} If `options` is not an object (outside production), or the query error when it should be + * thrown to the nearest error boundary (see `throwOnError`). While suspending, it throws a promise instead. + */ +export function useBaseQuery< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + options: UseBaseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + Observer: typeof QueryObserver, + queryClient?: QueryClient, + suspense?: typeof suspenseQueryPolicy, +): QueryObserverResult { + if (process.env.NODE_ENV !== 'production') { + if (typeof options !== 'object' || Array.isArray(options)) { + throw new Error( + 'Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object', + ) + } + } + + const isRestoring = useIsRestoring() + const errorResetBoundary = useQueryErrorResetBoundary() + const client = useQueryClient(queryClient) + const defaultedOptions = client.defaultQueryOptions({ + ...options, + suspense: !!suspense, + }) + + const query = client + .getQueryCache() + .get( + defaultedOptions.queryHash, + ) + + if (process.env.NODE_ENV !== 'production') { + if (!defaultedOptions.queryFn) { + console.error( + `[${defaultedOptions.queryHash}]: No query function was provided or configured in the query defaults. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`, + ) + } + } + + const subscribed = options.subscribed !== false + + // Make sure results are optimistically set in fetching state before subscribing or updating options + defaultedOptions._optimisticResults = isRestoring + ? 'isRestoring' + : subscribed + ? 'optimistic' + : undefined + + suspense?.prepare(defaultedOptions) + ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query) + useClearResetErrorBoundary(errorResetBoundary) + + const [observer] = React.useState( + () => + new Observer( + client, + defaultedOptions, + ), + ) + + const reader = observer.createResultReader(defaultedOptions) + + suspense?.readQuery( + defaultedOptions, + reader, + observer, + client, + errorResetBoundary, + ) + + React.useEffect(() => { + reader.commit() + }, [reader]) + + const shouldSubscribe = !isRestoring && subscribed + const result = React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => { + const unsubscribe = shouldSubscribe + ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) + : noop + + // Update result to make sure we did not miss any query updates + // between creating the observer and subscribing to it. + observer.updateResult() + + return unsubscribe + }, + [observer, shouldSubscribe], + ), + reader.getSnapshot, + reader.getSnapshot, + ) + + // Handle error boundary + if ( + getHasError({ + result, + errorResetBoundary, + throwOnError: defaultedOptions.throwOnError, + query, + suspense: defaultedOptions.suspense, + }) + ) { + throw result.error + } + + // Handle result property usage tracking + return !defaultedOptions.notifyOnChangeProps + ? observer.trackResult(result) + : result +} diff --git a/packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts b/packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts new file mode 100644 index 00000000000..d895e3c3dd3 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts @@ -0,0 +1,364 @@ +'use client' +import { InfiniteQueryObserver } from './runtime/index' +import { useBaseQuery } from './useBaseQuery' +import type { + DefinedInitialDataInfiniteOptions, + UndefinedInitialDataInfiniteOptions, +} from './infiniteQueryOptions' +import type { + DefaultError, + InfiniteData, + QueryClient, + QueryKey, + QueryObserver, +} from './runtime/index' +import type { + DefinedUseInfiniteQueryResult, + UseInfiniteQueryOptions, + UseInfiniteQueryResult, +} from './types' + +/** + * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of + * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + * + * This overload is selected when `initialData` is known to be defined. + * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` known to be defined. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`, + * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and + * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default + * `InfiniteData` shape. + * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default + * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user + * actions, or add conditions like `hasNextPage && !isFetching`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @example + * ```tsx + * import { useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' + * + * function Projects() { + * // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the + * // list stays visible alongside the error. + * const { data, isError, error } = useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * initialData: { pages: [], pageParams: [] }, + * }) + * + * return ( + *
+ * {isError ? Error: {error.message} : null} + *
    + * {data.pages.map((page) => page.projects.map((p) =>
  • {p.name}
  • ))} + *
+ *
+ * ) + * } + * ``` + */ +export function useInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): DefinedUseInfiniteQueryResult + +/** + * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of + * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`, + * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and + * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default + * `InfiniteData` shape. + * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default + * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user + * actions, or add conditions like `hasNextPage && !isFetching`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @example + * Fetching the next page from a "Load More" button click: + * ```tsx + * import { useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' + * + * function Projects() { + * const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = + * useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + * <> + *
    + * {data.pages.map((page) => + * page.projects.map((project) =>
  • {project.name}
  • ), + * )} + *
+ * + * + * ) + * } + * ``` + * @example + * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a + * sentinel element after the list: + * ```tsx + * import { useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' + * import { useEffect, useRef } from 'react' + * + * function Projects() { + * const { + * data, + * isPending, + * isError, + * error, + * fetchNextPage, + * hasNextPage, + * isFetching, + * isFetchingNextPage, + * } = useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * const sentinelRef = useRef(null) + * + * useEffect(() => { + * const sentinel = sentinelRef.current + * if (sentinel == null || !hasNextPage || isFetching) return + * + * const observer = new IntersectionObserver(([entry]) => { + * if (entry?.isIntersecting) fetchNextPage() + * }) + * observer.observe(sentinel) + * + * return () => observer.disconnect() + * }, [hasNextPage, isFetching, fetchNextPage]) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + * <> + *
    + * {data.pages.map((page) => + * page.projects.map((project) =>
  • {project.name}
  • ), + * )} + *
+ *
{isFetchingNextPage ? 'Loading more...' : null}
+ * + * ) + * } + * ``` + */ +export function useInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): UseInfiniteQueryResult + +/** + * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of + * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + * @param options - The {@link UseInfiniteQueryOptions} to use — everything you can pass to `useInfiniteQuery`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`, + * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and + * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default + * `InfiniteData` shape. + * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default + * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user + * actions, or add conditions like `hasNextPage && !isFetching`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @example + * Fetching the next page from a "Load More" button click: + * ```tsx + * import { useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' + * + * function Projects() { + * const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = + * useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + * <> + *
    + * {data.pages.map((page) => + * page.projects.map((project) =>
  • {project.name}
  • ), + * )} + *
+ * + * + * ) + * } + * ``` + * @example + * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a + * sentinel element after the list: + * ```tsx + * import { useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' + * import { useEffect, useRef } from 'react' + * + * function Projects() { + * const { + * data, + * isPending, + * isError, + * error, + * fetchNextPage, + * hasNextPage, + * isFetching, + * isFetchingNextPage, + * } = useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * const sentinelRef = useRef(null) + * + * useEffect(() => { + * const sentinel = sentinelRef.current + * if (sentinel == null || !hasNextPage || isFetching) return + * + * const observer = new IntersectionObserver(([entry]) => { + * if (entry?.isIntersecting) fetchNextPage() + * }) + * observer.observe(sentinel) + * + * return () => observer.disconnect() + * }, [hasNextPage, isFetching, fetchNextPage]) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + * <> + *
    + * {data.pages.map((page) => + * page.projects.map((project) =>
  • {project.name}
  • ), + * )} + *
+ *
{isFetchingNextPage ? 'Loading more...' : null}
+ * + * ) + * } + * ``` + * @example + * A query that's disabled, type safe, until `postId` is set — pass `skipToken` as `queryFn` + * instead of setting `enabled: false`: + * ```tsx + * import { skipToken, useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' + * + * function Comments({ postId }: { postId: string | undefined }) { + * // Use `isLoading`, not `isPending`, so the loading state doesn't show while the query is disabled. + * const { data, isLoading, isError, error } = useInfiniteQuery({ + * queryKey: ['post', postId, 'comments'], + * queryFn: + * postId != null + * ? ({ pageParam }) => fetchComments(postId, pageParam) + * : skipToken, + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * if (postId == null) return 'Select a post' + * if (isLoading) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
    + * {data?.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} + *
+ * ) + * } + * ``` + */ +export function useInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): UseInfiniteQueryResult + +export function useInfiniteQuery( + options: UseInfiniteQueryOptions, + queryClient?: QueryClient, +) { + return useBaseQuery( + options, + InfiniteQueryObserver as typeof QueryObserver, + queryClient, + ) +} diff --git a/packages/react-query-no-core-pluggable/src/useIsFetching.ts b/packages/react-query-no-core-pluggable/src/useIsFetching.ts new file mode 100644 index 00000000000..b423949a91b --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/useIsFetching.ts @@ -0,0 +1,56 @@ +'use client' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import { notifyManager } from './runtime/index' +import type { QueryClient, QueryFilters } from './runtime/index' + +/** + * The `useIsFetching` hook returns the `number` of the queries that your application is loading or fetching in + * the background (useful for app-wide loading indicators). + * @param filters - The {@link QueryFilters} to narrow down the matched queries. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns Will be the `number` of the queries that your application is currently loading or fetching in the + * background. + * @example + * ```tsx + * import { useIsFetching } from '@tanstack/react-query-no-core-pluggable' + * + * function PostsFetchingIndicator() { + * // How many queries matching the posts prefix are fetching? + * const isFetchingPosts = useIsFetching({ queryKey: ['posts'] }) + * + * return isFetchingPosts ? Refreshing posts... : null + * } + * ``` + * @example + * A global loading indicator for any query fetching in the background, not just the ones on screen: + * ```tsx + * import { useIsFetching } from '@tanstack/react-query-no-core-pluggable' + * + * function GlobalLoadingIndicator() { + * const isFetching = useIsFetching() + * + * return isFetching ? ( + *
Queries are fetching in the background...
+ * ) : null + * } + * ``` + */ +export function useIsFetching( + filters?: Omit, + queryClient?: QueryClient, +): number { + const client = useQueryClient(queryClient) + const queryCache = client.getQueryCache() + + return React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => + queryCache.subscribe(notifyManager.batchCalls(onStoreChange)), + [queryCache], + ), + () => client.isFetching(filters), + () => client.isFetching(filters), + ) +} diff --git a/packages/react-query-no-core-pluggable/src/useMutation.ts b/packages/react-query-no-core-pluggable/src/useMutation.ts new file mode 100644 index 00000000000..b4b64f471a1 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/useMutation.ts @@ -0,0 +1,241 @@ +'use client' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import { + MutationObserver, + noop, + notifyManager, + shouldThrowError, +} from './runtime/index' +import type { DefaultError, QueryClient } from './runtime/index' +import type { + UseMutateFunction, + UseMutationOptions, + UseMutationResult, +} from './types' + +// HOOK + +/** + * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. + * `useMutation` is the hook for that. + * @param options - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second + * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared + * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks + * fire only for the latest call you've made, and only while the component is still mounted — unmounting before + * the mutation settles removes the subscription and prevents them from firing. + * @throws {Error} The mutation error, when `throwOnError` is `true` or returns `true` for it, so that it is + * thrown to the nearest error boundary. + * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites, or to look + * the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`). + * @example + * ```tsx + * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core-pluggable' + * + * function AddTodo() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + * }) + * + * return ( + * + * ) + * } + * ``` + * @example + * Rendering the mutation's own state, rather than just firing it off: + * ```tsx + * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core-pluggable' + * + * function AddTodo() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + * }) + * + * return ( + *
+ * {addMutation.isPending ? ( + * 'Adding todo...' + * ) : ( + * <> + * {addMutation.isError ? ( + *
An error occurred: {addMutation.error.message}
+ * ) : null} + * + * + * )} + *
+ * ) + * } + * ``` + * @example + * Optimistic update via `onMutate`, rolling back on `onError`: + * ```tsx + * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core-pluggable' + * + * function AddTodo() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onMutate: async (newTodo) => { + * await queryClient.cancelQueries({ queryKey: ['todos'] }) + * const previousTodos = queryClient.getQueryData>(['todos']) + * + * queryClient.setQueryData>(['todos'], (old) => [ + * ...(old ?? []), + * newTodo, + * ]) + * + * // Passed to `onError` as `onMutateResult` if the mutation fails. + * return { previousTodos } + * }, + * onError: (_err, _newTodo, onMutateResult) => { + * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos) + * }, + * onSettled: () => { + * queryClient.invalidateQueries({ queryKey: ['todos'] }) + * }, + * }) + * + * return ( + * + * ) + * } + * ``` + * @example + * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a + * promise per call instead, so you can wait for all of them when they succeed: + * ```tsx + * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core-pluggable' + * + * function AddTodos() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + * }) + * + * async function handleAddAll(todos: Array) { + * try { + * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo))) + * } catch (error) { + * console.error('Failed to add todos:', error) + * } + * } + * + * return ( + * + * ) + * } + * ``` + * @example + * If some of the mutations above can fail independently of the others, and you want to know which ones + * did — rather than losing that information the moment the first one rejects — swap `Promise.all` for + * `Promise.allSettled`: + * ```tsx + * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core-pluggable' + * + * function AddTodos() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + * }) + * + * async function handleAddAll(todos: Array) { + * const addResults = await Promise.allSettled( + * todos.map((todo) => addMutation.mutateAsync(todo)), + * ) + * + * addResults.forEach((addResult, index) => { + * if (addResult.status === 'rejected') { + * console.error(`Failed to add "${todos[index]}":`, addResult.reason) + * } + * }) + * } + * + * return ( + * + * ) + * } + * ``` + */ +export function useMutation< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + options: UseMutationOptions, + queryClient?: QueryClient, +): UseMutationResult { + const client = useQueryClient(queryClient) + + const [observer] = React.useState( + () => + new MutationObserver( + client, + options, + ), + ) + + React.useEffect(() => { + observer.setOptions(options) + }, [observer, options]) + + const result = React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => + observer.subscribe(notifyManager.batchCalls(onStoreChange)), + [observer], + ), + () => observer.getCurrentResult(), + () => observer.getCurrentResult(), + ) + + const mutate = React.useCallback< + UseMutateFunction + >( + ( + ...args: Parameters< + UseMutateFunction + > + ) => { + observer.mutate(args[0] as TVariables, args[1]).catch(noop) + }, + [observer], + ) + + if ( + result.error && + shouldThrowError(observer.options.throwOnError, [result.error]) + ) { + throw result.error + } + + return { ...result, mutate, mutateAsync: result.mutate } +} diff --git a/packages/react-query-no-core-pluggable/src/useMutationState.ts b/packages/react-query-no-core-pluggable/src/useMutationState.ts new file mode 100644 index 00000000000..8a71c381bf4 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/useMutationState.ts @@ -0,0 +1,205 @@ +'use client' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import { notifyManager, replaceEqualDeep } from './runtime/index' +import type { + Mutation, + MutationCache, + MutationFilters, + MutationState, + QueryClient, +} from './runtime/index' + +/** + * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending` + * (useful for app-wide loading indicators). + * @param filters - The {@link MutationFilters} to narrow down the matched mutations. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns Will be the `number` of the mutations that your application currently has `pending`. + * @example + * ```tsx + * import { useIsMutating } from '@tanstack/react-query-no-core-pluggable' + * + * function PostsMutatingIndicator() { + * // How many mutations matching the posts prefix are in progress? + * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] }) + * + * return isMutatingPosts ? Saving posts... : null + * } + * ``` + */ +export function useIsMutating( + filters?: Omit, + queryClient?: QueryClient, +): number { + const client = useQueryClient(queryClient) + return useMutationState( + { filters: { ...filters, status: 'pending' } }, + client, + ).length +} + +type MutationTypeFromResult = [TResult] extends [ + MutationState< + infer TData, + infer TError, + infer TVariables, + infer TOnMutateResult + >, +] + ? Mutation + : Mutation + +type MutationStateOptions< + TResult = MutationState, + TMutation extends Mutation = + MutationTypeFromResult, +> = { + filters?: MutationFilters + select?: (mutation: TMutation) => TResult +} + +/** + * Creates snapshot getters that share equal selected results across renders. + * A new getter is created on each render. Each getter caches its snapshot until the matching mutations + * or their states change. + * @returns A factory for snapshot getters with a shared result cache. + */ +function createSnapshotFactory< + TResult = MutationState, + TMutation extends Mutation = + MutationTypeFromResult, +>() { + let previousResult: Array | undefined + + return ( + mutationCache: MutationCache, + options: MutationStateOptions, + ) => { + let inputs: Array = [] + let snapshot: Array | undefined + + return (): Array => { + const mutations = mutationCache.findAll(options.filters) + const nextInputs = mutations.flatMap((mutation) => [ + mutation, + mutation.state, + ]) + + if ( + !snapshot || + nextInputs.length !== inputs.length || + nextInputs.some((input, index) => !Object.is(input, inputs[index])) + ) { + inputs = nextInputs + snapshot = replaceEqualDeep( + previousResult, + mutations.map( + (mutation): TResult => + (options.select + ? options.select(mutation as TMutation) + : mutation.state) as TResult, + ), + ) + previousResult = snapshot + } + + return snapshot + } + } +} + +/** + * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass + * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation + * state. + * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the + * mutation state. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns Will be an Array of whatever `select` returns for each matching mutation. + * @example + * Get all variables of all running mutations: + * ```tsx + * import { useMutationState } from '@tanstack/react-query-no-core-pluggable' + * + * function PendingPosts() { + * const pendingVariables = useMutationState({ + * filters: { status: 'pending' }, + * select: (mutation) => mutation.state.variables, + * }) + * + * return <>{pendingVariables.length} posts saving... + * } + * ``` + * @example + * Get all data for specific mutations via the `mutationKey`: + * ```tsx + * import { useMutation, useMutationState } from '@tanstack/react-query-no-core-pluggable' + * + * const mutationKey = ['posts'] + * + * function Posts() { + * // Some mutation that we want to get the state for + * const mutation = useMutation({ + * mutationKey, + * mutationFn: createPosts, + * }) + * + * const savedPosts = useMutationState({ + * // this mutation key needs to match the mutation key of the given mutation (see above) + * filters: { mutationKey, status: 'success' }, + * select: (mutation) => mutation.state.data, + * }) + * + * return ( + * + * ) + * } + * ``` + * @example + * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new + * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the + * last item that `useMutationState` returns to get the latest successful invocation: + * ```tsx + * import { useMutationState } from '@tanstack/react-query-no-core-pluggable' + * + * function LatestPost() { + * const savedPosts = useMutationState({ + * filters: { mutationKey: ['posts'], status: 'success' }, + * select: (mutation) => mutation.state.data, + * }) + * + * const latestSavedPost = savedPosts[savedPosts.length - 1] + * + * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'} + * } + * ``` + */ +export function useMutationState< + TResult = MutationState, + TMutation extends Mutation = + MutationTypeFromResult, +>( + options: MutationStateOptions = {}, + queryClient?: QueryClient, +): Array { + const mutationCache = useQueryClient(queryClient).getMutationCache() + const [createSnapshot] = React.useState(() => + createSnapshotFactory(), + ) + const getSnapshot = createSnapshot(mutationCache, options) + + return React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => + mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)), + [mutationCache], + ), + getSnapshot, + getSnapshot, + ) +} diff --git a/packages/react-query-no-core-pluggable/src/usePrefetchInfiniteQuery.tsx b/packages/react-query-no-core-pluggable/src/usePrefetchInfiniteQuery.tsx new file mode 100644 index 00000000000..4bf20560b89 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/usePrefetchInfiniteQuery.tsx @@ -0,0 +1,72 @@ +import { useQueryClient } from './QueryClientProvider' +import { noop } from './runtime/index' +import type { + DefaultError, + InfiniteData, + QueryClient, + QueryKey, +} from './runtime/index' +import type { UsePrefetchInfiniteQueryOptions } from './types' + +/** + * `usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render, + * before a suspense boundary that wraps a component that uses `useSuspenseInfiniteQuery`. You can pass + * everything to `usePrefetchInfiniteQuery` that you can pass to `queryClient.infiniteQuery`, though + * `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required. Pass `defaultQueryFn` to use the client defaults. + * + * `getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages, + * as well as pageParam information, and should return a single variable that will be passed to your query + * function as `context.pageParam`. Return `undefined` or `null` to indicate there is no next page available. + * + * The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left + * over from a previous attempt — so calling this on every render is cheap and won't refetch data that's + * already there or already in flight. + * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `queryClient.infiniteQuery`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @example + * ```tsx + * import { Suspense } from 'react' + * import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' + * + * const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function App() { + * // Fire the prefetch during render, before the suspense boundary below. + * usePrefetchInfiniteQuery(projectsOptions) + * + * return ( + * Loading projects...}> + * + * + * ) + * } + * ``` + */ +export function usePrefetchInfiniteQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UsePrefetchInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): void { + const client = useQueryClient(queryClient) + + if (!client.getQueryState(options.queryKey)) { + void client.infiniteQuery(options).catch(noop) + } +} diff --git a/packages/react-query-no-core-pluggable/src/usePrefetchQuery.tsx b/packages/react-query-no-core-pluggable/src/usePrefetchQuery.tsx new file mode 100644 index 00000000000..458c9424d88 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/usePrefetchQuery.tsx @@ -0,0 +1,59 @@ +import { useQueryClient } from './QueryClientProvider' +import { noop } from './runtime/index' +import type { DefaultError, QueryClient, QueryKey } from './runtime/index' +import type { UsePrefetchQueryOptions } from './types' + +/** + * `usePrefetchQuery` does not return anything, it should be used just to fire a prefetch during render, before + * a suspense boundary that wraps a component that uses `useSuspenseQuery`. You can pass everything to + * `usePrefetchQuery` that you can pass to `queryClient.query`, though `queryKey` is always required, and + * `queryFn` is required. Pass `defaultQueryFn` to use the client defaults. + * + * The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left + * over from a previous attempt — so calling this on every render is cheap and won't refetch data that's + * already there or already in flight. + * @param options - The {@link UsePrefetchQueryOptions} to use — everything you can pass to `queryClient.query`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @example + * ```tsx + * import { Suspense } from 'react' + * import { usePrefetchQuery } from '@tanstack/react-query-no-core-pluggable' + * + * function App() { + * // Fire the prefetch during render, before the suspense boundary below. + * usePrefetchQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * return ( + * Loading posts...}> + * + * + * ) + * } + * ``` + */ +export function usePrefetchQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UsePrefetchQueryOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + queryClient?: QueryClient, +): void { + const client = useQueryClient(queryClient) + + if (!client.getQueryState(options.queryKey)) { + void client.query(options).catch(noop) + } +} diff --git a/packages/react-query-no-core-pluggable/src/useQueries.ts b/packages/react-query-no-core-pluggable/src/useQueries.ts new file mode 100644 index 00000000000..7854ac811bf --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/useQueries.ts @@ -0,0 +1,487 @@ +'use client' +import * as React from 'react' +import { useIsRestoring } from './IsRestoringProvider' +import { useQueryClient } from './QueryClientProvider' +import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary' +import { + ensurePreventErrorBoundaryRetry, + getHasError, + useClearResetErrorBoundary, +} from './errorBoundaryUtils' +import { QueriesObserver, noop, notifyManager } from './runtime/index' +import type { + DefaultError, + OmitKeyof, + QueriesObserverOptions, + QueriesPlaceholderDataFunction, + QueryClient, + QueryFunction, + QueryKey, + QueryObserverOptions, + ThrowOnError, +} from './runtime/index' +import type { suspenseQueriesPolicy } from './suspense' +import type { + DefinedUseQueryResult, + UseQueryOptions, + UseQueryResult, +} from './types' + +// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`. +// `placeholderData` function always gets undefined passed +type UseQueryOptionsForUseQueries< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = OmitKeyof< + UseQueryOptions, + 'placeholderData' | 'subscribed' +> & { + placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction +} + +// Avoid TS depth-limit error in case of large array literal +type MAXIMUM_DEPTH = 20 + +// Widen the type of the symbol to enable type inference even if skipToken is not immutable. +type SkipTokenForUseQueries = symbol + +type GetUseQueryOptionsForUseQueries = + // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData } + T extends { + queryFnData: infer TQueryFnData + error?: infer TError + data: infer TData + } + ? UseQueryOptionsForUseQueries + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? UseQueryOptionsForUseQueries + : T extends { data: infer TData; error?: infer TError } + ? UseQueryOptionsForUseQueries + : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData] + T extends [infer TQueryFnData, infer TError, infer TData] + ? UseQueryOptionsForUseQueries + : T extends [infer TQueryFnData, infer TError] + ? UseQueryOptionsForUseQueries + : T extends [infer TQueryFnData] + ? UseQueryOptionsForUseQueries + : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: (data: any) => infer TData + throwOnError?: ThrowOnError + } + ? UseQueryOptionsForUseQueries< + TQueryFnData, + unknown extends TError ? DefaultError : TError, + unknown extends TData ? TQueryFnData : TData, + TQueryKey + > + : // Fallback + UseQueryOptionsForUseQueries + +// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult +type GetDefinedOrUndefinedQueryResult = T extends { + initialData?: infer TInitialData +} + ? unknown extends TInitialData + ? UseQueryResult + : TInitialData extends TData + ? DefinedUseQueryResult + : TInitialData extends () => infer TInitialDataResult + ? unknown extends TInitialDataResult + ? UseQueryResult + : TInitialDataResult extends TData + ? DefinedUseQueryResult + : UseQueryResult + : UseQueryResult + : UseQueryResult + +type GetUseQueryResult = + // Part 1: responsible for mapping explicit type parameter to function result, if object + T extends { queryFnData: any; error?: infer TError; data: infer TData } + ? GetDefinedOrUndefinedQueryResult + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? GetDefinedOrUndefinedQueryResult + : T extends { data: infer TData; error?: infer TError } + ? GetDefinedOrUndefinedQueryResult + : // Part 2: responsible for mapping explicit type parameter to function result, if tuple + T extends [any, infer TError, infer TData] + ? GetDefinedOrUndefinedQueryResult + : T extends [infer TQueryFnData, infer TError] + ? GetDefinedOrUndefinedQueryResult + : T extends [infer TQueryFnData] + ? GetDefinedOrUndefinedQueryResult + : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: (data: any) => infer TData + throwOnError?: ThrowOnError + } + ? GetDefinedOrUndefinedQueryResult< + T, + unknown extends TData ? TQueryFnData : TData, + unknown extends TError ? DefaultError : TError + > + : // Fallback + UseQueryResult + +/** + * The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's + * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements — past that, a tuple falls + * back to a single homogeneous options type. + * + * An opaque array (e.g. `unknown[]`) is returned as-is; a non-tuple array whose element type structurally + * matches a query options object is mapped per-element instead, still inferring each entry individually; any + * other non-tuple array — one whose element type doesn't match the expected options shape — falls back to + * that same homogeneous options type too. + * @template T - The type of the `queries` array as written at the call site. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type QueriesOptions< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseQueryOptionsForUseQueries] + : T extends [infer Head, ...infer Tails] + ? QueriesOptions< + [...Tails], + [...TResults, GetUseQueryOptionsForUseQueries], + [...TDepth, 1] + > + : ReadonlyArray extends T + ? T + : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type! + // use this to infer the param types in the case of Array.map() argument + T extends Array< + UseQueryOptionsForUseQueries< + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryKey + > + > + ? Array< + UseQueryOptionsForUseQueries< + TQueryFnData, + TError, + TData, + TQueryKey + > + > + : // Fallback + Array + +/** + * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each + * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped + * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a + * single homogeneous {@link UseQueryResult} type. + * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type QueriesResults< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseQueryResult] + : T extends [infer Head, ...infer Tails] + ? QueriesResults< + [...Tails], + [...TResults, GetUseQueryResult], + [...TDepth, 1] + > + : { [K in keyof T]: GetUseQueryResult } + +type UseQueriesInput, TCombinedResult> = { + /** + * An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and + * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and + * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData` + * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function. + */ + queries: + | readonly [...QueriesOptions] + | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries }] + /** + * Use this to combine the results of the queries into a single value. The result will be structurally + * shared to be as referentially stable as possible. + */ + combine?: (result: QueriesResults) => TCombinedResult + /** + * Set this to `false` to unsubscribe this observer from updates to the query cache. + * @defaultValue true + */ + subscribed?: boolean +} + +/** + * The `useQueries` hook can be used to fetch a variable number of queries. + * + * The `queries` key accepts an array with query option objects mostly identical to `useQuery` — the top-level + * `subscribed` option isn't accepted per query (see `placeholderData` below for another difference). A custom + * `QueryClient` is supplied once, as `useQueries`' own top-level second argument, rather than per query. + * + * Having the same query key more than once in the array of query objects may cause some data to be shared + * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired + * structure. + * + * The `combine` option can be used to combine the results of the queries into a single value. The result will + * be structurally shared to be as referentially stable as possible. + * @param options - The `queries` array to run, and the optional `combine` and `subscribed` options. + * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context + * will be used. + * @returns The combined result. Without `combine`, this is an array with all the query results, in the same + * order as the input. When `combine` is provided, this is the value returned by `combine` instead. + * @throws {Error} The error of the first query that should be thrown to the nearest error boundary (see + * `throwOnError`). While suspending, it throws a promise instead. + * @remarks The `combine` function only re-runs if it changed referentially, or if any of the query results + * changed. An inlined `combine` function, as shown in the example below, therefore runs on every render — wrap + * it in `useCallback`, or extract it to a stable function reference if it doesn't have any dependencies, to + * avoid that. + * + * Unlike `useQuery`, `useQueries` cannot infer the `data` argument of an _inline_ `select` from its sibling + * `queryFn`. Because `useQueries` infers the type of the whole `queries` array at once, the `select` parameter + * of a query object written inline cannot be contextually typed from that same object's `queryFn`, so it falls + * back to `unknown` — a [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate + * the `select` parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in + * a single object _before_ it reaches `useQueries`, to work around this — see the example below. The same + * limitation applies to {@link useSuspenseQueries}. + * + * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from + * previously rendered queries, because the number of queries can differ between renders. + * @example + * ```tsx + * import { useQueries } from '@tanstack/react-query-no-core-pluggable' + * + * function Posts({ ids }: { ids: Array }) { + * const postQueries = useQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * staleTime: Infinity, + * })), + * }) + * + * return ( + *
    + * {postQueries.map((query, index) => { + * if (query.isPending) return
  • Loading...
  • + * if (query.isError) return
  • Error: {query.error.message}
  • + * return
  • {query.data.title}
  • + * })} + *
+ * ) + * } + * ``` + * @example + * Combining results into a single value: + * ```tsx + * import { useQueries } from '@tanstack/react-query-no-core-pluggable' + * + * function Posts({ ids }: { ids: Array }) { + * const { data, isPending, isError } = useQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * })), + * combine: (postQueries) => { + * return { + * data: postQueries.map((query) => query.data), + * isPending: postQueries.some((query) => query.isPending), + * isError: postQueries.some((query) => query.isError), + * } + * }, + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return 'Error loading posts' + * + * return ( + *
    + * {data.map((post) => ( + *
  • {post?.title}
  • + * ))} + *
+ * ) + * } + * ``` + * @example + * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding + * `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is + * resolved before it reaches `useQueries`: + * ```tsx + * import { queryOptions, useQueries } from '@tanstack/react-query-no-core-pluggable' + * + * const postOptions = (id: number) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function PostTitle({ id }: { id: number }) { + * const [{ data: broken }] = useQueries({ + * queries: [ + * { + * ...postOptions(id), + * // ❌ `data` is `unknown` here + * select: (data) => data.title, + * }, + * ], + * }) + * + * const [{ data: fixed }] = useQueries({ + * queries: [ + * queryOptions({ + * ...postOptions(id), + * // ✅ `data` is `Post` + * select: (data) => data.title, + * }), + * ], + * }) + * + * return

{fixed}

+ * } + * ``` + */ +export function useQueries< + T extends Array, + TCombinedResult = QueriesResults, +>( + options: UseQueriesInput, + queryClient?: QueryClient, +): TCombinedResult { + return useBaseQueries(options, queryClient) +} + +/** + * Reads and subscribes to multiple queries. The dedicated Suspense hook can + * supply a render-time policy. + * @param options - The queries, combiner, and subscription setting. + * @param queryClient - The client to use in place of the nearest provider. + * @param suspense - The policy that prepares and reads queries during render. + * @returns The individual query results or the combined result. + * @throws {Error} The first query error configured to reach the error boundary. + */ +export function useBaseQueries< + T extends Array, + TCombinedResult = QueriesResults, +>( + { queries, ...options }: UseQueriesInput, + queryClient?: QueryClient, + suspense?: typeof suspenseQueriesPolicy, +): TCombinedResult { + const client = useQueryClient(queryClient) + const isRestoring = useIsRestoring() + const errorResetBoundary = useQueryErrorResetBoundary() + const subscribed = options.subscribed !== false + + const defaultedQueries = React.useMemo( + () => + queries.map((opts) => { + const defaultedOptions = client.defaultQueryOptions({ + ...opts, + suspense: !!suspense, + } as QueryObserverOptions) + + // Make sure the results are already in fetching state before subscribing or updating options + defaultedOptions._optimisticResults = isRestoring + ? 'isRestoring' + : subscribed + ? 'optimistic' + : undefined + + return defaultedOptions + }), + [queries, client, isRestoring, subscribed, suspense], + ) + + defaultedQueries.forEach((queryOptions) => { + suspense?.prepare(queryOptions) + const query = client.getQueryCache().get(queryOptions.queryHash) + ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query) + }) + + useClearResetErrorBoundary(errorResetBoundary) + + const [observer] = React.useState( + () => + new QueriesObserver( + client, + defaultedQueries, + options as QueriesObserverOptions, + ), + ) + + const reader = observer.createResultReader( + defaultedQueries, + options as QueriesObserverOptions, + ) + suspense?.readQueries(defaultedQueries, reader, client, errorResetBoundary) + + // Commit the combine cache before subscription can start a fetch. + React.useEffect(() => { + reader.commit() + }, [reader]) + + const shouldSubscribe = !isRestoring && subscribed + const results = React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => { + const unsubscribe = shouldSubscribe + ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) + : noop + + // Include cache updates that occurred before subscription. + observer + .getObservers() + .forEach((queryObserver) => queryObserver.updateResult()) + return unsubscribe + }, + [observer, shouldSubscribe], + ), + reader.getSnapshot, + reader.getSnapshot, + ) + + const firstErrorResult = results.find((result, index) => { + const query = defaultedQueries[index] + return ( + query && + getHasError({ + result, + errorResetBoundary, + throwOnError: query.throwOnError, + query: client.getQueryCache().get(query.queryHash), + suspense: query.suspense, + }) + ) + }) + + if (firstErrorResult) { + throw firstErrorResult.error + } + + return reader.combineResult(results) +} diff --git a/packages/react-query-no-core-pluggable/src/useQuery.ts b/packages/react-query-no-core-pluggable/src/useQuery.ts new file mode 100644 index 00000000000..842a1226bda --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/useQuery.ts @@ -0,0 +1,297 @@ +'use client' +import { QueryObserver } from './runtime/index' +import { useBaseQuery } from './useBaseQuery' +import type { + DefinedInitialDataOptions, + UndefinedInitialDataOptions, +} from './queryOptions' +import type { DefaultError, QueryClient, QueryKey } from './runtime/index' +import type { + DefinedUseQueryResult, + UseQueryOptions, + UseQueryResult, +} from './types' + +/** + * This overload is selected when `initialData` is known to be defined, so the resulting `data` is typed as never + * `undefined` (unless a `select` changes `TData` to include `undefined`). At runtime, `data` is still `undefined` + * if `select` throws on its first call. + * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The current query result, typed so that `status` is `success` or `error` (`status` never + * resolves to `pending` in this overload's type, since `initialData` guarantees data upfront). `status` is + * `error` if the query has an error from a fetch that failed after its retries or if `select` threw, and + * `success` otherwise. `isSuccess`/`isError` are derived booleans for convenience. + * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`. + * @example + * ```tsx + * import { useQuery } from '@tanstack/react-query-no-core-pluggable' + * + * function Posts() { + * // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, + * // so the list stays visible alongside the error. + * const { data, isError, error } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * initialData: [], + * }) + * + * return ( + *
+ * {isError ? Error: {error.message} : null} + *
    + * {data.map((post) =>
  • {post.title}
  • )} + *
+ *
+ * ) + * } + * ``` + */ +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: DefinedInitialDataOptions, + queryClient?: QueryClient, +): DefinedUseQueryResult + +/** + * This overload is selected when `initialData` is omitted, may be `undefined`, or is a function that may + * return `undefined`, so the resulting `data` can be `undefined`. + * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The current query result. `status` is `error` if the query has an error from a fetch that failed + * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns + * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError` + * are derived booleans for convenience. + * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`. + * @example + * ```tsx + * import { useQuery } from '@tanstack/react-query-no-core-pluggable' + * + * function Posts() { + * const { status, data, error, isFetching } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * if (status === 'pending') return 'Loading...' + * if (status === 'error') return Error: {error.message} + * + * return ( + *
+ *
    + * {data.map((post) => ( + *
  • {post.title}
  • + * ))} + *
+ *
{isFetching ? 'Background Updating...' : ' '}
+ *
+ * ) + * } + * ``` + * @example + * The same query, checking `isPending`/`isError` instead of `status` — pick whichever reads better to you: + * ```tsx + * import { useQuery } from '@tanstack/react-query-no-core-pluggable' + * + * function Posts() { + * const { isPending, isError, data, error } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
    + * {data.map((post) =>
  • {post.title}
  • )} + *
+ * ) + * } + * ``` + */ +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UndefinedInitialDataOptions, + queryClient?: QueryClient, +): UseQueryResult + +/** + * Fallback overload for options whose `initialData` presence isn't statically known — for example, an + * object typed as {@link UseQueryOptions} rather than an object literal. Prefer one of the other overloads + * when possible, since they infer whether `data` can be `undefined` from `initialData` directly. + * @param options - The {@link UseQueryOptions} to use — everything you can pass to `useQuery`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The current query result. `status` is `error` if the query has an error from a fetch that failed + * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns + * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError` + * are derived booleans for convenience. + * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`. + * @example + * ```tsx + * import { useQuery } from '@tanstack/react-query-no-core-pluggable' + * + * function Posts() { + * const { status, data, error, isFetching } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * if (status === 'pending') return 'Loading...' + * if (status === 'error') return Error: {error.message} + * + * return ( + *
+ *
    + * {data.map((post) => ( + *
  • {post.title}
  • + * ))} + *
+ *
{isFetching ? 'Background Updating...' : ' '}
+ *
+ * ) + * } + * ``` + * @example + * `select` derives whatever `data` a component needs from the cached value, without changing what's + * actually stored in the cache — the cache still holds the full `Post[]`, but `data` here is a `number`: + * ```tsx + * import { useQuery } from '@tanstack/react-query-no-core-pluggable' + * + * function PostCount() { + * const { data, isPending, isError, error } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * select: (posts) => posts.length, + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return {data} posts + * } + * ``` + * @example + * A dependent query, only enabled once `postId` is set — use `isLoading`, not `isPending`, so the + * loading state doesn't show while the query is disabled: + * ```tsx + * import { useQuery } from '@tanstack/react-query-no-core-pluggable' + * + * function Post({ postId }: { postId: number | undefined }) { + * const { data, isLoading, isError, error } = useQuery({ + * queryKey: ['post', postId], + * queryFn: () => fetchPost(postId!), + * enabled: postId != null, + * }) + * + * if (postId == null) return 'Select a post' + * if (isLoading) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data?.title}

+ * } + * ``` + * @example + * The same dependent query, type safe: `skipToken` disables the query without needing the + * non-null assertion above, since `queryFn` is only ever called when `postId` is defined. + * `refetch` doesn't work while `queryFn` is `skipToken` — use `enabled: false` instead if you + * need to trigger the query manually: + * ```tsx + * import { skipToken, useQuery } from '@tanstack/react-query-no-core-pluggable' + * + * function Post({ postId }: { postId: number | undefined }) { + * const { data, isLoading, isError, error } = useQuery({ + * queryKey: ['post', postId], + * queryFn: postId != null ? () => fetchPost(postId) : skipToken, + * }) + * + * if (postId == null) return 'Select a post' + * if (isLoading) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data?.title}

+ * } + * ``` + * @example + * Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries + * over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was + * fetched rather than from now: + * ```tsx + * import { useQuery, useQueryClient } from '@tanstack/react-query-no-core-pluggable' + * + * function Post({ postId }: { postId: number }) { + * const queryClient = useQueryClient() + * + * const { data, isError, error } = useQuery({ + * queryKey: ['post', postId], + * queryFn: () => fetchPost(postId), + * initialData: () => + * queryClient + * .getQueryData>(['posts']) + * ?.find((post) => post.id === postId), + * initialDataUpdatedAt: () => + * queryClient.getQueryState(['posts'])?.dataUpdatedAt, + * }) + * + * if (isError) return Error: {error.message} + * + * return

{data?.title}

+ * } + * ``` + * @example + * Paginated data, keeping the previous page's data visible while the next page loads: + * ```tsx + * import { keepPreviousData, useQuery } from '@tanstack/react-query-no-core-pluggable' + * import { useState } from 'react' + * + * function Posts() { + * const [page, setPage] = useState(0) + * + * const { data, isPlaceholderData, isError, error } = useQuery({ + * queryKey: ['posts', page], + * queryFn: () => fetchPosts(page), + * placeholderData: keepPreviousData, + * }) + * + * if (isError) return Error: {error.message} + * + * return ( + *
+ *
    + * {data?.map((post) =>
  • {post.title}
  • )} + *
+ * + *
+ * ) + * } + * ``` + */ +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UseQueryOptions, + queryClient?: QueryClient, +): UseQueryResult + +export function useQuery(options: UseQueryOptions, queryClient?: QueryClient) { + return useBaseQuery(options, QueryObserver, queryClient) +} diff --git a/packages/react-query-no-core-pluggable/src/useSuspenseInfiniteQuery.ts b/packages/react-query-no-core-pluggable/src/useSuspenseInfiniteQuery.ts new file mode 100644 index 00000000000..d19264b0d1c --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/useSuspenseInfiniteQuery.ts @@ -0,0 +1,184 @@ +'use client' +import { InfiniteQueryObserver, skipToken } from './runtime/index' +import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' +import { useBaseQuery } from './useBaseQuery' +import type { + DefaultError, + InfiniteData, + OmitKeyof, + QueryClient, + QueryKey, + QueryObserver, +} from './runtime/index' +import type { + UseInfiniteQueryOptions, + UseInfiniteQueryResult, + UseSuspenseInfiniteQueryOptions, + UseSuspenseInfiniteQueryResult, +} from './types' + +type SkippableSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, + TPageParam, +> = OmitKeyof< + UseInfiniteQueryOptions, + 'enabled' | 'throwOnError' +> + +/** + * The options for `useSuspenseInfiniteQuery` are the same as for `useInfiniteQuery`, except for `throwOnError` + * and `enabled`. + * + * Caveat: cancellation does not work. + * @param options - The {@link UseSuspenseInfiniteQueryOptions} to use — the same options as `useInfiniteQuery`, minus the ones listed above. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The same object as `useInfiniteQuery`, except that `data` is guaranteed to be defined, + * `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived flags set + * accordingly). + * @remarks Multiple suspenseful query calls in the same component suspend serially, causing a request + * waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until + * then. There's no way to parallelize multiple infinite queries under Suspense. Also keep in mind that + * imperative fetch calls, such as `fetchNextPage`, may interfere with the default refetch behavior, + * resulting in outdated data. Make sure to call these functions only in response to user actions, or add + * conditions like `hasNextPage && !isFetching`. + * @see {@link useInfiniteQuery} for the non-Suspense version of this hook. + * @example + * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is + * required around ``. A failed background refetch instead continues to render the cached data. + * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseInfiniteQuery, + * } from '@tanstack/react-query-no-core-pluggable' + * + * function Projects() { + * // `data` is guaranteed to be defined here — no `isPending` check needed. + * const { data, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = + * useSuspenseInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * return ( + *
+ *
    + * {data.pages.map((page) => + * page.projects.map((project) =>
  • {project.name}
  • ), + * )} + *
+ * + *
+ * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * Loading projects...}> + * + * + *
+ * )} + *
+ * ) + * } + * ``` + */ +export function useSuspenseInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UseSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): UseSuspenseInfiniteQueryResult + +/** + * A skipped query does not fetch automatically or suspend. Query errors without cached + * data reach the nearest error boundary. + * @param options - The infinite query options. The query function can be `skipToken`. + * @param queryClient - The client to use. Defaults to the client from the nearest context. + * @returns An infinite query result that can be pending and can have undefined data. + */ +export function useSuspenseInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: SkippableSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): UseInfiniteQueryResult + +export function useSuspenseInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: SkippableSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): UseInfiniteQueryResult { + const skipped = options.queryFn === skipToken + + return useBaseQuery( + { + ...options, + enabled: !skipped, + throwOnError: defaultThrowOnError, + }, + InfiniteQueryObserver as typeof QueryObserver, + queryClient, + skipped ? undefined : suspenseQueryPolicy, + ) as UseInfiniteQueryResult +} diff --git a/packages/react-query-no-core-pluggable/src/useSuspenseQueries.ts b/packages/react-query-no-core-pluggable/src/useSuspenseQueries.ts new file mode 100644 index 00000000000..20a5854ad4c --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/useSuspenseQueries.ts @@ -0,0 +1,548 @@ +'use client' +import { skipToken } from './runtime/index' +import { defaultThrowOnError, suspenseQueriesPolicy } from './suspense' +import { useBaseQueries } from './useQueries' +import type { + DefaultError, + OmitKeyof, + QueriesPlaceholderDataFunction, + QueryClient, + QueryFunction, + QueryKey, + ThrowOnError, +} from './runtime/index' +import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types' + +// `placeholderData` functions in useQueries never receive previous query data. +type UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = OmitKeyof< + UseSuspenseQueryOptions, + 'placeholderData' +> & { + placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction +} + +// Avoid TS depth-limit error in case of large array literal +type MAXIMUM_DEPTH = 20 + +// Widen the type of the symbol to enable type inference even if skipToken is not immutable. +type SkipTokenForUseQueries = symbol + +type GetUseSuspenseQueryOptions = + // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData } + T extends { + queryFnData: infer TQueryFnData + error?: infer TError + data: infer TData + } + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : T extends { data: infer TData; error?: infer TError } + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData] + T extends [infer TQueryFnData, infer TError, infer TData] + ? UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TError, + TData + > + : T extends [infer TQueryFnData, infer TError] + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : T extends [infer TQueryFnData] + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: (data: any) => infer TData + throwOnError?: ThrowOnError + } + ? UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TError, + TData, + TQueryKey + > + : T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + throwOnError?: ThrowOnError + } + ? UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TError, + TQueryFnData, + TQueryKey + > + : // Fallback + UseSuspenseQueryOptionsForUseSuspenseQueries + +type GetUseSuspenseQueryResult = + // Part 1: responsible for mapping explicit type parameter to function result, if object + T extends { queryFnData: any; error?: infer TError; data: infer TData } + ? UseSuspenseQueryResult + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? UseSuspenseQueryResult + : T extends { data: infer TData; error?: infer TError } + ? UseSuspenseQueryResult + : // Part 2: responsible for mapping explicit type parameter to function result, if tuple + T extends [any, infer TError, infer TData] + ? UseSuspenseQueryResult + : T extends [infer TQueryFnData, infer TError] + ? UseSuspenseQueryResult + : T extends [infer TQueryFnData] + ? UseSuspenseQueryResult + : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: (data: any) => infer TData + throwOnError?: ThrowOnError + } + ? UseSuspenseQueryResult< + unknown extends TData ? TQueryFnData : TData, + unknown extends TError ? DefaultError : TError + > + : T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + throwOnError?: ThrowOnError + } + ? UseSuspenseQueryResult< + TQueryFnData, + unknown extends TError ? DefaultError : TError + > + : // Fallback + UseSuspenseQueryResult + +/** + * The `queries` array accepted by `useSuspenseQueries`. Recursively unwraps each tuple element so every + * entry's `queryFn`/`select` are inferred individually, up to 20 elements — past that, a tuple falls back to + * a single homogeneous {@link UseSuspenseQueryOptions} type. + * + * An opaque array (e.g. `unknown[]`) is returned as-is; a non-tuple array whose element type structurally + * matches a query options object is mapped per-element instead, still inferring each entry individually; any + * other non-tuple array — one whose element type doesn't match the expected options shape — falls back to + * that same homogeneous options type too. + * @template T - The type of the `queries` array as written at the call site. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type SuspenseQueriesOptions< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseSuspenseQueryOptions] + : T extends [infer Head, ...infer Tails] + ? SuspenseQueriesOptions< + [...Tails], + [...TResults, GetUseSuspenseQueryOptions], + [...TDepth, 1] + > + : Array extends T + ? T + : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type! + // use this to infer the param types in the case of Array.map() argument + T extends Array< + UseSuspenseQueryOptionsForUseSuspenseQueries< + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryKey + > + > + ? Array< + UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TError, + TData, + TQueryKey + > + > + : // Fallback + Array + +/** + * The result type returned by `useSuspenseQueries`, when no `combine` is provided. Mirrors + * {@link SuspenseQueriesOptions}: each tuple element's result type is inferred individually, up to 20 elements. + * A non-tuple array is mapped per-element instead, still inferring each entry individually; only past 20 + * elements does this fall back to a single homogeneous {@link UseSuspenseQueryResult} type. + * @template T - The type of the `queries` array, as inferred by {@link SuspenseQueriesOptions}. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type SuspenseQueriesResults< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseSuspenseQueryResult] + : T extends [infer Head, ...infer Tails] + ? SuspenseQueriesResults< + [...Tails], + [...TResults, GetUseSuspenseQueryResult], + [...TDepth, 1] + > + : { [K in keyof T]: GetUseSuspenseQueryResult } + +/** + * The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed` + * option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`. + * @param options - The `queries` array to run in Suspense, and an optional `combine` function. + * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context + * will be used. + * @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be + * defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived + * flags set accordingly). + * + * Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone + * stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid + * this, make sure to set a high enough `staleTime`. Cancellation does not work. + * @example + * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is + * required around ``. A failed background refetch instead continues to render the cached data. + * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-no-core-pluggable' + * + * function Posts({ ids }: { ids: Array }) { + * // Every result is guaranteed to be defined — no per-query `isPending` check needed. + * const postQueries = useSuspenseQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * })), + * }) + * + * return ( + *
    + * {postQueries.map((query) => ( + *
  • {query.data.title}
  • + * ))} + *
+ * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * Loading posts...}> + * + * + *
+ * )} + *
+ * ) + * } + * ``` + * @example + * Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so + * they fetch in parallel rather than suspending one after another: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-no-core-pluggable' + * + * function Dashboard() { + * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({ + * queries: [ + * { queryKey: ['users'], queryFn: fetchUsers }, + * { queryKey: ['teams'], queryFn: fetchTeams }, + * { queryKey: ['projects'], queryFn: fetchProjects }, + * ], + * }) + * + * return ( + *
+ * + * + * + *
+ * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * Loading dashboard...}> + * + * + *
+ * )} + *
+ * ) + * } + * ``` + * @example + * `combine`s the results into a single boolean, so `Refresh` only re-renders when that boolean changes, + * not on every individual query update. This overload is the only one that accepts `combine`: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-no-core-pluggable' + * + * function Refresh() { + * const anyFetching = useSuspenseQueries({ + * queries: [ + * { queryKey: ['users'], queryFn: fetchUsers }, + * { queryKey: ['teams'], queryFn: fetchTeams }, + * ], + * combine: (results) => results.some((result) => result.isFetching), + * }) + * + * return anyFetching ? Refreshing… : null + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * Loading dashboard...}> + * + * + *
+ * )} + *
+ * ) + * } + * ``` + */ +export function useSuspenseQueries< + T extends Array, + TCombinedResult = SuspenseQueriesResults, +>( + options: { + /** + * An array with query option objects identical to `useSuspenseQuery`. + */ + queries: + | readonly [...SuspenseQueriesOptions] + | readonly [...{ [K in keyof T]: GetUseSuspenseQueryOptions }] + /** + * Use this to combine the results of the queries into a single value. The result will be structurally + * shared to be as referentially stable as possible. + */ + combine?: (result: SuspenseQueriesResults) => TCombinedResult + }, + queryClient?: QueryClient, +): TCombinedResult + +/** + * The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed` + * option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`. + * @param options - The `queries` array to run in Suspense, and an optional `combine` function. + * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context + * will be used. + * @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be + * defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived + * flags set accordingly). + * + * Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone + * stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid + * this, make sure to set a high enough `staleTime`. Cancellation does not work. + * @example + * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is + * required around ``. A failed background refetch instead continues to render the cached data. + * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-no-core-pluggable' + * + * function Posts({ ids }: { ids: Array }) { + * // Every result is guaranteed to be defined — no per-query `isPending` check needed. + * const postQueries = useSuspenseQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * })), + * }) + * + * return ( + *
    + * {postQueries.map((query) => ( + *
  • {query.data.title}
  • + * ))} + *
+ * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * Loading posts...}> + * + * + *
+ * )} + *
+ * ) + * } + * ``` + * @example + * Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so + * they fetch in parallel rather than suspending one after another: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-no-core-pluggable' + * + * function Dashboard() { + * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({ + * queries: [ + * { queryKey: ['users'], queryFn: fetchUsers }, + * { queryKey: ['teams'], queryFn: fetchTeams }, + * { queryKey: ['projects'], queryFn: fetchProjects }, + * ], + * }) + * + * return ( + *
+ * + * + * + *
+ * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * Loading dashboard...}> + * + * + *
+ * )} + *
+ * ) + * } + * ``` + */ +export function useSuspenseQueries< + T extends Array, + TCombinedResult = SuspenseQueriesResults, +>( + options: { + /** + * An array with query option objects identical to `useSuspenseQuery`. + */ + queries: readonly [...SuspenseQueriesOptions] + /** + * Use this to combine the results of the queries into a single value. The result will be structurally + * shared to be as referentially stable as possible. + */ + combine?: (result: SuspenseQueriesResults) => TCombinedResult + }, + queryClient?: QueryClient, +): TCombinedResult + +export function useSuspenseQueries(options: any, queryClient?: QueryClient) { + return useBaseQueries( + { + ...options, + queries: options.queries.map((query: any) => { + if (process.env.NODE_ENV !== 'production') { + if (query.queryFn === skipToken) { + console.error('skipToken is not allowed for useSuspenseQueries') + } + } + + return { + ...query, + throwOnError: defaultThrowOnError, + enabled: true, + } + }), + }, + queryClient, + suspenseQueriesPolicy, + ) +} diff --git a/packages/react-query-no-core-pluggable/src/useSuspenseQuery.ts b/packages/react-query-no-core-pluggable/src/useSuspenseQuery.ts new file mode 100644 index 00000000000..b187bbcf23b --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/useSuspenseQuery.ts @@ -0,0 +1,150 @@ +'use client' +import { QueryObserver, skipToken } from './runtime/index' +import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' +import { useBaseQuery } from './useBaseQuery' +import type { + DefaultError, + OmitKeyof, + QueryClient, + QueryKey, +} from './runtime/index' +import type { + UseQueryOptions, + UseQueryResult, + UseSuspenseQueryOptions, + UseSuspenseQueryResult, +} from './types' + +type SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, +> = OmitKeyof< + UseQueryOptions, + 'enabled' | 'throwOnError' +> + +/** + * Runs a query with Suspense. The options match those of `useQuery` except for `throwOnError` and `enabled`. + * + * Caveat: cancellation does not work. + * @param options - The {@link UseSuspenseQueryOptions} for a query that always runs. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns A result with data of type `TData` and a status of `success` or `error`. + * @remarks Multiple `useSuspenseQuery` calls in the same component suspend serially, causing a request + * waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until then. + * Use {@link useSuspenseQueries} instead when you have more than one suspenseful query in a component, so they + * fetch in parallel. + * @example + * The query error is thrown if the fetch fails and no cached data exists yet, so an error boundary is + * required around ``. A failed background refetch instead continues to render the cached data. + * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { QueryErrorResetBoundary, useSuspenseQuery } from '@tanstack/react-query-no-core-pluggable' + * + * function Posts() { + * // `data` is guaranteed to be defined here — no `isPending` check needed. + * const { data, isFetching } = useSuspenseQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * return ( + *
+ *

Posts {isFetching ? '(refreshing...)' : null}

+ *
    + * {data.map((post) => ( + *
  • {post.title}
  • + * ))} + *
+ *
+ * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * Loading posts...}> + * + * + *
+ * )} + *
+ * ) + * } + * ``` + */ +export function useSuspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UseSuspenseQueryOptions, + queryClient?: QueryClient, +): UseSuspenseQueryResult + +/** + * Pass `skipToken` as `queryFn` to skip the query. While skipped, the query can read cached data + * but does not fetch automatically or suspend. Query errors without cached data reach the nearest error boundary. + * Pass a query function to resume normal Suspense behavior. + * @param options - Options for a query that can be skipped. + * @param queryClient - The client to use. Defaults to the client from the nearest context. + * @returns A result whose data can be undefined and whose status can be `pending`. + */ +export function useSuspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey + >, + queryClient?: QueryClient, +): UseQueryResult + +export function useSuspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey + >, + queryClient?: QueryClient, +): UseQueryResult { + const skipped = options.queryFn === skipToken + + return useBaseQuery( + { + ...options, + enabled: !skipped, + throwOnError: defaultThrowOnError, + }, + QueryObserver, + queryClient, + skipped ? undefined : suspenseQueryPolicy, + ) +} diff --git a/packages/react-query-no-core-pluggable/test-setup.ts b/packages/react-query-no-core-pluggable/test-setup.ts new file mode 100644 index 00000000000..cc010a39cfd --- /dev/null +++ b/packages/react-query-no-core-pluggable/test-setup.ts @@ -0,0 +1,16 @@ +import '@testing-library/jest-dom/vitest' +import { act, cleanup as cleanupRTL } from '@testing-library/react' +import { cleanup as cleanupRRS } from '@testing-library/react-render-stream' +import { afterEach } from 'vitest' +import { notifyManager } from './src/runtime/index' + +// https://testing-library.com/docs/react-testing-library/api#cleanup +afterEach(() => { + cleanupRTL() + cleanupRRS() +}) + +// Wrap notifications with act to make sure React knows about React Query updates +notifyManager.setNotifyFunction((fn) => { + act(fn) +}) diff --git a/packages/react-query-no-core-pluggable/tests/compat-client.ts b/packages/react-query-no-core-pluggable/tests/compat-client.ts new file mode 100644 index 00000000000..a39bfc975f2 --- /dev/null +++ b/packages/react-query-no-core-pluggable/tests/compat-client.ts @@ -0,0 +1,15 @@ +import { + QueryClient as PluggableQueryClient, + infiniteQueryPlugin, + mutationPlugin, +} from '../src/runtime/index' +import type { QueryClientConfig } from '../src/runtime/index' + +/** Runs the upstream suites against a client with the full upstream feature set. */ +export class QueryClient extends PluggableQueryClient { + constructor(config?: QueryClientConfig) { + super({ ...config, plugins: [mutationPlugin, infiniteQueryPlugin] }) + } +} + +export type AdapterClientOptions = 'plugins' diff --git a/packages/react-query-no-core-pluggable/tsconfig.json b/packages/react-query-no-core-pluggable/tsconfig.json new file mode 100644 index 00000000000..cae6ad65d3f --- /dev/null +++ b/packages/react-query-no-core-pluggable/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "./dist-ts", + "rootDir": ".", + "jsx": "react-jsx" + }, + "include": [ + "src", + "tests", + "test-setup.ts", + "*.config.ts", + "*.config.js", + "package.json" + ] +} diff --git a/packages/react-query-no-core-pluggable/tsconfig.legacy.json b/packages/react-query-no-core-pluggable/tsconfig.legacy.json new file mode 100644 index 00000000000..20f2156d95b --- /dev/null +++ b/packages/react-query-no-core-pluggable/tsconfig.legacy.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "outDir": "./dist-ts/legacy" + }, + "include": ["src"], + "exclude": ["src/__tests__"] +} diff --git a/packages/react-query-no-core-pluggable/tsconfig.prod.json b/packages/react-query-no-core-pluggable/tsconfig.prod.json new file mode 100644 index 00000000000..2bb29fdf02a --- /dev/null +++ b/packages/react-query-no-core-pluggable/tsconfig.prod.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "incremental": false, + "composite": false, + "rootDir": "../../" + }, + "include": ["src"], + "exclude": ["src/__tests__"] +} diff --git a/packages/react-query-no-core-pluggable/tsdown.config.ts b/packages/react-query-no-core-pluggable/tsdown.config.ts new file mode 100644 index 00000000000..a486c9a8d14 --- /dev/null +++ b/packages/react-query-no-core-pluggable/tsdown.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'tsdown' +import { getTsdownConfig } from './root.tsdown.config.js' + +export default defineConfig({ + ...getTsdownConfig({ entry: ['src/index.ts'] }), + // Preserve React's client boundaries and let the consuming app remove unused plugins. + unbundle: true, +}) diff --git a/packages/react-query-no-core-pluggable/vite.config.ts b/packages/react-query-no-core-pluggable/vite.config.ts new file mode 100644 index 00000000000..79b96a728ee --- /dev/null +++ b/packages/react-query-no-core-pluggable/vite.config.ts @@ -0,0 +1,33 @@ +import react from '@vitejs/plugin-react' +import { defineConfig } from 'vitest/config' +import packageJson from './package.json' + +export default defineConfig({ + plugins: [react()], + // fix from https://github.com/vitest-dev/vitest/issues/6992#issuecomment-2509408660 + resolve: { + conditions: ['@tanstack/custom-condition'], + }, + environments: { + ssr: { + resolve: { + conditions: ['@tanstack/custom-condition'], + }, + }, + }, + test: { + name: packageJson.name, + dir: './src', + watch: false, + environment: 'jsdom', + setupFiles: ['test-setup.ts'], + coverage: { + enabled: !!process.env.CI, + provider: 'istanbul', + include: ['src/**/*'], + exclude: ['src/__tests__/**'], + }, + typecheck: { enabled: true }, + restoreMocks: true, + }, +}) diff --git a/packages/react-query-no-core/README.md b/packages/react-query-no-core/README.md new file mode 100644 index 00000000000..1358c181827 --- /dev/null +++ b/packages/react-query-no-core/README.md @@ -0,0 +1,31 @@ +# @tanstack/react-query-no-core + +An experimental ESM adapter for React 19 with its own query runtime. Import the client, provider and hooks from this package. Its client includes mutations and infinite queries by default. + +```tsx +import { + QueryClient, + QueryClientProvider, + useQuery, +} from '@tanstack/react-query-no-core' + +const client = new QueryClient() + +function Greeting() { + const { data } = useQuery({ + queryKey: ['greeting'], + queryFn: () => Promise.resolve('Hello'), + }) + return

{data}

+} + +export function App() { + return ( + + + + ) +} +``` + +The original adapter and both experimental adapters share their TypeScript definitions through `@tanstack/query-types`. Each React adapter owns its provider context and each client owns its caches. diff --git a/packages/react-query-no-core/oxlint.config.ts b/packages/react-query-no-core/oxlint.config.ts new file mode 100644 index 00000000000..91da02f7ef4 --- /dev/null +++ b/packages/react-query-no-core/oxlint.config.ts @@ -0,0 +1,51 @@ +import pluginReact from '@eslint-react/eslint-plugin' +import reactHooks from 'eslint-plugin-react-hooks' +import { defineConfig } from 'oxlint' +import rootConfig from './root.oxlint.config.ts' + +export default defineConfig({ + extends: [rootConfig], + settings: rootConfig.settings, + jsPlugins: [ + // 'react-hooks' is reserved for Oxlint's native plugin, which lacks the React Compiler rules + { name: 'react-hooks-js', specifier: 'eslint-plugin-react-hooks' }, + '@eslint-react/eslint-plugin', + ], + rules: { + ...Object.fromEntries( + Object.entries(reactHooks.configs.flat.recommended.rules).map( + ([name, value]) => [ + name.replace(/^react-hooks\//, 'react-hooks-js/'), + value, + ], + ), + ), + ...pluginReact.configs.recommended.rules, + 'react-hooks-js/exhaustive-deps': 'error', + 'react-hooks-js/unsupported-syntax': 'error', + 'react-hooks-js/incompatible-library': 'error', + '@eslint-react/no-context-provider': 'off', // We need to be React 18 compatible + '@eslint-react/no-use-context': 'off', // We need to be React 18 compatible + // Covered by 'eslint-plugin-react-hooks' + '@eslint-react/error-boundaries': 'off', + '@eslint-react/exhaustive-deps': 'off', + '@eslint-react/globals': 'off', + '@eslint-react/immutability': 'off', + '@eslint-react/purity': 'off', + '@eslint-react/refs': 'off', + '@eslint-react/rules-of-hooks': 'off', + '@eslint-react/set-state-in-effect': 'off', + '@eslint-react/set-state-in-render': 'off', + '@eslint-react/static-components': 'off', + '@eslint-react/unsupported-syntax': 'off', + '@eslint-react/use-memo': 'off', + }, + overrides: [ + { + files: ['**/__tests__/**'], + rules: { + 'typescript/no-unnecessary-condition': 'off', + }, + }, + ], +}) diff --git a/packages/react-query-no-core/package.json b/packages/react-query-no-core/package.json new file mode 100644 index 00000000000..d58db8aaee9 --- /dev/null +++ b/packages/react-query-no-core/package.json @@ -0,0 +1,80 @@ +{ + "name": "@tanstack/react-query-no-core", + "version": "5.108.4", + "description": "React Query with an integrated query runtime", + "author": "tannerlinsley", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/TanStack/query.git", + "directory": "packages/react-query-no-core" + }, + "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": "node ../../scripts/test-react-query-compat.mjs", + "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__" + ], + "dependencies": { + "@tanstack/query-types": "workspace:*" + }, + "devDependencies": { + "@eslint-react/eslint-plugin": "catalog:", + "@types/react": "catalog:", + "eslint-plugin-react-hooks": "catalog:", + "react": "catalog:", + "typescript": "catalog:" + }, + "peerDependencies": { + "@types/react": "^19", + "react": "^19" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + }, + "nx": { + "targets": { + "test:lib": { + "inputs": [ + "default", + "^production", + "reactQueryCompatibility" + ] + } + } + } +} diff --git a/packages/react-query-no-core/root.oxlint.config.ts b/packages/react-query-no-core/root.oxlint.config.ts new file mode 120000 index 00000000000..56565c65534 --- /dev/null +++ b/packages/react-query-no-core/root.oxlint.config.ts @@ -0,0 +1 @@ +../../oxlint.config.ts \ No newline at end of file diff --git a/packages/react-query-no-core/root.tsdown.config.js b/packages/react-query-no-core/root.tsdown.config.js new file mode 120000 index 00000000000..a997d5d337c --- /dev/null +++ b/packages/react-query-no-core/root.tsdown.config.js @@ -0,0 +1 @@ +../../scripts/getTsdownConfig.js \ No newline at end of file diff --git a/packages/react-query-no-core/src/HydrationBoundary.tsx b/packages/react-query-no-core/src/HydrationBoundary.tsx new file mode 100644 index 00000000000..47f6a0b77f9 --- /dev/null +++ b/packages/react-query-no-core/src/HydrationBoundary.tsx @@ -0,0 +1,140 @@ +'use client' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import { hydrate } from './runtime' +import type { + DehydratedState, + HydrateOptions, + OmitKeyof, + QueryClient, +} from './runtime' + +/** + * The props accepted by `HydrationBoundary`. + */ +export interface HydrationBoundaryProps { + /** + * The state to hydrate. Pass the result of `dehydrate(queryClient)`. + */ + state: DehydratedState + /** + * Optional. Note: unlike `hydrate`, `mutations` cannot be set here. + */ + options?: OmitKeyof & { + defaultOptions?: OmitKeyof< + Exclude, + 'mutations' + > + } + /** + * The components to render — always rendered unconditionally, not gated on hydration. New queries are + * hydrated into the cache during render; for queries that already exist in the cache, only newer dehydrated + * data is hydrated, and that happens in an effect after commit, so `children` may render briefly before it + * lands. + */ + children?: React.ReactNode + /** + * Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. + */ + queryClient?: QueryClient +} + +/** + * `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by + * `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on + * update timestamp. + * + * Note: Only `queries` can be dehydrated with an `HydrationBoundary`. + * @param props - The dehydrated `state` to hydrate, the hydrate `options`, an optional custom + * `queryClient`, and the `children` to render. + * @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the + * cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect + * after commit. + * @example + * ```tsx + * import { HydrationBoundary } from '@tanstack/react-query-no-core' + * + * function App() { + * return ... + * } + * ``` + * @example + * Server-side prefetch handed off to the client via `dehydrate`: + * ```tsx + * import { HydrationBoundary, dehydrate, noop } from '@tanstack/react-query-no-core' + * + * async function ServerComponent() { + * const queryClient = getQueryClient() + * + * await queryClient + * .query({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * .catch(noop) + * + * return ( + * + * + * + * ) + * } + * ``` + */ +export const HydrationBoundary = ({ + children, + options = {}, + state, + queryClient, +}: HydrationBoundaryProps) => { + const client = useQueryClient(queryClient) + + const optionsRef = React.useRef(options) + React.useEffect(() => { + optionsRef.current = options + }) + + // Hydrate new queries during render so children can read their data. + // Hydrate existing queries after commit so an aborted transition cannot update them. + const hydrationQueue: DehydratedState['queries'] | undefined = + React.useMemo(() => { + const queryCache = client.getQueryCache() + + const newQueries: DehydratedState['queries'] = [] + const existingQueries: DehydratedState['queries'] = [] + for (const dehydratedQuery of state.queries) { + const existingQuery = queryCache.get(dehydratedQuery.queryHash) + + if (!existingQuery) { + newQueries.push(dehydratedQuery) + continue + } + + const hydrationIsNewer = + dehydratedQuery.state.dataUpdatedAt > + existingQuery.state.dataUpdatedAt || + (dehydratedQuery.promise && + existingQuery.state.status !== 'pending' && + existingQuery.state.fetchStatus !== 'fetching' && + dehydratedQuery.dehydratedAt > existingQuery.state.dataUpdatedAt) + + if (hydrationIsNewer) { + existingQueries.push(dehydratedQuery) + } + } + + if (newQueries.length > 0) { + // oxlint-disable-next-line react-hooks-js/refs -- new queries are hydrated during render on purpose, and 'options' is read through a ref so that a new 'options' object does not rerun this memo + hydrate(client, { queries: newQueries }, optionsRef.current) + } + return existingQueries.length > 0 ? existingQueries : undefined + }, [client, state]) + + React.useEffect(() => { + if (hydrationQueue) { + hydrate(client, { queries: hydrationQueue }, optionsRef.current) + } + }, [client, hydrationQueue]) + + return children as React.ReactElement +} diff --git a/packages/react-query-no-core/src/IsRestoringProvider.ts b/packages/react-query-no-core/src/IsRestoringProvider.ts new file mode 100644 index 00000000000..abb353406a6 --- /dev/null +++ b/packages/react-query-no-core/src/IsRestoringProvider.ts @@ -0,0 +1,18 @@ +'use client' +import * as React from 'react' + +const IsRestoringContext = React.createContext(false) + +/** + * If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to + * check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid + * race conditions between the restore and mounting queries. + * @returns `true` while a persisted client is being restored, `false` otherwise. + */ +export const useIsRestoring = () => React.useContext(IsRestoringContext) + +/** + * The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently + * being restored, read by `useIsRestoring`. + */ +export const IsRestoringProvider = IsRestoringContext.Provider diff --git a/packages/react-query-no-core/src/QueryClientProvider.tsx b/packages/react-query-no-core/src/QueryClientProvider.tsx new file mode 100644 index 00000000000..8659fa6e346 --- /dev/null +++ b/packages/react-query-no-core/src/QueryClientProvider.tsx @@ -0,0 +1,84 @@ +'use client' +import * as React from 'react' +import type { QueryClient } from './runtime' + +/** + * The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it. + */ +export const QueryClientContext = React.createContext( + undefined, +) + +/** + * The `useQueryClient` hook returns the current `QueryClient` instance. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The current `QueryClient` instance. + * @throws {Error} If no `queryClient` argument is passed and no `QueryClientProvider` is found in the + * component tree. + */ +export const useQueryClient = (queryClient?: QueryClient) => { + const client = React.useContext(QueryClientContext) + + if (queryClient) { + return queryClient + } + + if (!client) { + throw new Error('No QueryClient set, use QueryClientProvider to set one') + } + + return client +} + +/** + * The props accepted by `QueryClientProvider`. + */ +export type QueryClientProviderProps = { + /** + * **Required** + * + * The `QueryClient` instance to provide. + */ + client: QueryClient + /** + * The components that get access to the provided `QueryClient`. + */ + children?: React.ReactNode +} + +/** + * Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also + * calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to + * focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or + * comes back online). + * @param props - The `client` to provide, and the `children` that get access to it. + * @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`. + * @example + * ```tsx + * import { QueryClient, QueryClientProvider } from '@tanstack/react-query-no-core' + * + * const queryClient = new QueryClient() + * + * function App() { + * return ... + * } + * ``` + */ +export const QueryClientProvider = ({ + client, + children, +}: QueryClientProviderProps): React.JSX.Element => { + React.useEffect(() => { + client.mount() + return () => { + client.unmount() + } + }, [client]) + + return ( + + {children} + + ) +} diff --git a/packages/react-query-no-core/src/QueryErrorResetBoundary.tsx b/packages/react-query-no-core/src/QueryErrorResetBoundary.tsx new file mode 100644 index 00000000000..41e745b6579 --- /dev/null +++ b/packages/react-query-no-core/src/QueryErrorResetBoundary.tsx @@ -0,0 +1,169 @@ +'use client' +import * as React from 'react' + +// CONTEXT + +/** + * Resets any query errors within the boundary, so queries know they can try again. + */ +export type QueryErrorResetFunction = () => void + +/** + * Returns whether the boundary has been reset and not yet cleared. + */ +export type QueryErrorIsResetFunction = () => boolean + +/** + * Clears the reset state, so queries know not to try again until the boundary is reset again. + */ +export type QueryErrorClearResetFunction = () => void + +/** + * The value a `QueryErrorResetBoundary` shares through context, used to reset query errors within + * it and to check whether a reset was requested. + */ +export interface QueryErrorResetBoundaryValue { + /** + * Clears the reset state, so queries know not to try again until the boundary is reset again. + */ + clearReset: QueryErrorClearResetFunction + /** + * Returns whether the boundary has been reset and not yet cleared. + */ + isReset: QueryErrorIsResetFunction + /** + * Resets any query errors within the boundary, so queries know they can try again. + */ + reset: QueryErrorResetFunction +} + +/** + * Creates the value shared through the boundary's context, which tracks whether a reset was + * requested. + * @returns The `clearReset`, `isReset`, and `reset` functions of the boundary. + */ +function createValue(): QueryErrorResetBoundaryValue { + let isReset = false + return { + /** + * Clears the reset state, so queries know not to try again until the boundary is reset again. + */ + clearReset: () => { + isReset = false + }, + /** + * Resets any query errors within the boundary, so queries know they can try again. + */ + reset: () => { + isReset = true + }, + /** + * Returns whether the boundary has been reset and not yet cleared. + * @returns `true` if the boundary has been reset and not yet cleared. + */ + isReset: () => { + return isReset + }, + } +} + +const QueryErrorResetBoundaryContext = React.createContext(createValue()) + +// HOOK + +/** + * This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary + * defined it will reset them globally. + * @returns The boundary's {@link QueryErrorResetBoundaryValue}. + * @example + * ```tsx + * import { ErrorBoundary } from 'react-error-boundary' + * import { useQueryErrorResetBoundary } from '@tanstack/react-query-no-core' + * + * function App({ children }: { children: React.ReactNode }) { + * const { reset } = useQueryErrorResetBoundary() + * + * return ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * {children} + *
+ * ) + * } + * ``` + */ +export const useQueryErrorResetBoundary = () => + React.useContext(QueryErrorResetBoundaryContext) + +// COMPONENT + +/** + * A render-prop function usable as `children` on `QueryErrorResetBoundary`. + * @param value - The boundary's {@link QueryErrorResetBoundaryValue}. + * @returns The children to render. + */ +export type QueryErrorResetBoundaryFunction = ( + value: QueryErrorResetBoundaryValue, +) => React.ReactNode + +/** + * The props accepted by `QueryErrorResetBoundary`. + */ +export interface QueryErrorResetBoundaryProps { + /** + * Either a plain node, or a function that receives the boundary's {@link QueryErrorResetBoundaryValue} and + * returns a node. + */ + children: QueryErrorResetBoundaryFunction | React.ReactNode +} + +/** + * When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to + * try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can + * reset any query errors within the boundaries of the component. + * @param props - The `children` to render. + * @returns The `children`, rendered as-is, or called with the boundary's {@link QueryErrorResetBoundaryValue} + * if `children` is a function. + * @example + * ```tsx + * import { ErrorBoundary } from 'react-error-boundary' + * import { QueryErrorResetBoundary } from '@tanstack/react-query-no-core' + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * + *
+ * )} + *
+ * ) + * } + * ``` + */ +export const QueryErrorResetBoundary = ({ + children, +}: QueryErrorResetBoundaryProps) => { + const [value] = React.useState(() => createValue()) + return ( + + {typeof children === 'function' ? children(value) : children} + + ) +} diff --git a/packages/react-query-no-core/src/errorBoundaryUtils.ts b/packages/react-query-no-core/src/errorBoundaryUtils.ts new file mode 100644 index 00000000000..f80e52deb03 --- /dev/null +++ b/packages/react-query-no-core/src/errorBoundaryUtils.ts @@ -0,0 +1,103 @@ +'use client' +import * as React from 'react' +import { shouldThrowError } from './runtime' +import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import type { + DefaultedQueryObserverOptions, + Query, + QueryKey, + QueryObserverResult, + ThrowOnError, +} from './runtime' + +/** + * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`), + * unless the error boundary has been reset, so a remount doesn't retry the failed query before the + * user resets the boundary. Mutates the options. + * @param options - The defaulted query options to adjust. + * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`. + * @param query - The query, used to evaluate a `throwOnError` function against its error. + */ +export const ensurePreventErrorBoundaryRetry = < + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + options: DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + errorResetBoundary: QueryErrorResetBoundaryValue, + query: Query | undefined, +) => { + const throwOnError = + query?.state.status === 'error' && + typeof options.throwOnError === 'function' + ? shouldThrowError(options.throwOnError, [ + query.state.error as TError, + query, + ]) + : options.throwOnError + + if (options.suspense || throwOnError) { + // Prevent retrying failed query if the error boundary has not been reset yet + if (!errorResetBoundary.isReset()) { + options.retryOnMount = false + } + } +} + +/** + * Clears the reset state of the error boundary after the component mounts, so later errors are + * thrown to the boundary again. + * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`. + */ +export const useClearResetErrorBoundary = ( + errorResetBoundary: QueryErrorResetBoundaryValue, +) => { + React.useEffect(() => { + errorResetBoundary.clearReset() + }, [errorResetBoundary]) +} + +/** + * Checks whether the query error should be thrown to the nearest error boundary: the query errored + * and isn't fetching, the boundary hasn't been reset, and either `suspense` is enabled with no data + * or `throwOnError` says so. + * @param params - The observer `result`, the `errorResetBoundary`, the `throwOnError` option, the + * `query`, and the `suspense` option. + * @returns `true` if the error should be thrown. + */ +export const getHasError = < + TData, + TError, + TQueryFnData, + TQueryData, + TQueryKey extends QueryKey, +>({ + result, + errorResetBoundary, + throwOnError, + query, + suspense, +}: { + result: QueryObserverResult + errorResetBoundary: QueryErrorResetBoundaryValue + throwOnError: ThrowOnError + query: Query | undefined + suspense: boolean | undefined +}) => { + return ( + result.isError && + !errorResetBoundary.isReset() && + !result.isFetching && + query && + ((suspense && result.data === undefined) || + shouldThrowError(throwOnError, [result.error, query])) + ) +} diff --git a/packages/react-query-no-core/src/index.ts b/packages/react-query-no-core/src/index.ts new file mode 100644 index 00000000000..ec5aac29a4c --- /dev/null +++ b/packages/react-query-no-core/src/index.ts @@ -0,0 +1,83 @@ +/* istanbul ignore file */ + +// Query runtime +// oxlint-disable-next-line tanstack-query/no-restricted-syntax +export * from './runtime' + +// React Query +export type { + AnyUseBaseQueryOptions, + UseBaseQueryOptions, + UsePrefetchQueryOptions, + UsePrefetchInfiniteQueryOptions, + AnyUseQueryOptions, + UseQueryOptions, + AnyUseSuspenseQueryOptions, + UseSuspenseQueryOptions, + AnyUseInfiniteQueryOptions, + UseInfiniteQueryOptions, + AnyUseSuspenseInfiniteQueryOptions, + UseSuspenseInfiniteQueryOptions, + UseBaseQueryResult, + UseQueryResult, + UseSuspenseQueryResult, + DefinedUseQueryResult, + UseInfiniteQueryResult, + DefinedUseInfiniteQueryResult, + UseSuspenseInfiniteQueryResult, + AnyUseMutationOptions, + UseMutationOptions, + UseMutateFunction, + UseMutateAsyncFunction, + UseBaseMutationResult, + UseMutationResult, +} from './types' +export { useQueries } from './useQueries' +export type { QueriesResults, QueriesOptions } from './useQueries' +export { useQuery } from './useQuery' +export { useSuspenseQuery } from './useSuspenseQuery' +export { useSuspenseInfiniteQuery } from './useSuspenseInfiniteQuery' +export { useSuspenseQueries } from './useSuspenseQueries' +export type { + SuspenseQueriesResults, + SuspenseQueriesOptions, +} from './useSuspenseQueries' +export { usePrefetchQuery } from './usePrefetchQuery' +export { usePrefetchInfiniteQuery } from './usePrefetchInfiniteQuery' +export { queryOptions } from './queryOptions' +export type { + DefinedInitialDataOptions, + UndefinedInitialDataOptions, + UnusedSkipTokenOptions, +} from './queryOptions' +export { infiniteQueryOptions } from './infiniteQueryOptions' +export type { + DefinedInitialDataInfiniteOptions, + UndefinedInitialDataInfiniteOptions, + UnusedSkipTokenInfiniteOptions, +} from './infiniteQueryOptions' +export { + QueryClientContext, + QueryClientProvider, + useQueryClient, +} from './QueryClientProvider' +export type { QueryClientProviderProps } from './QueryClientProvider' +export type { QueryErrorResetBoundaryProps } from './QueryErrorResetBoundary' +export { HydrationBoundary } from './HydrationBoundary' +export type { HydrationBoundaryProps } from './HydrationBoundary' +export type { + QueryErrorClearResetFunction, + QueryErrorIsResetFunction, + QueryErrorResetBoundaryFunction, + QueryErrorResetFunction, +} from './QueryErrorResetBoundary' +export { + QueryErrorResetBoundary, + useQueryErrorResetBoundary, +} from './QueryErrorResetBoundary' +export { useIsFetching } from './useIsFetching' +export { useIsMutating, useMutationState } from './useMutationState' +export { useMutation } from './useMutation' +export { mutationOptions } from './mutationOptions' +export { useInfiniteQuery } from './useInfiniteQuery' +export { useIsRestoring, IsRestoringProvider } from './IsRestoringProvider' diff --git a/packages/react-query-no-core/src/infiniteQueryOptions.ts b/packages/react-query-no-core/src/infiniteQueryOptions.ts new file mode 100644 index 00000000000..d95f732d974 --- /dev/null +++ b/packages/react-query-no-core/src/infiniteQueryOptions.ts @@ -0,0 +1,302 @@ +import type { + DefaultError, + InfiniteData, + InitialDataFunction, + NonUndefinedGuard, + OmitKeyof, + QueryKey, + QueryKeyWithDataTag, + SkipToken, +} from './runtime' +import type { UseInfiniteQueryOptions } from './types' + +/** + * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is omitted, may be + * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is + * `pending`. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export type UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData?: + | undefined + | NonUndefinedGuard> + | InitialDataFunction< + NonUndefinedGuard> + > +} + +/** + * The options accepted by the `infiniteQueryOptions` overload selected when `queryFn` is not `skipToken` and + * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` — same as + * {@link UndefinedInitialDataInfiniteOptions}, but `queryFn` may not be `skipToken`. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export type UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = OmitKeyof< + UseInfiniteQueryOptions, + 'queryFn' +> & { + queryFn: Exclude< + UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >['queryFn'], + SkipToken + > +} + +/** + * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is known to be + * defined — `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export type DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData: + | NonUndefinedGuard> + | (() => NonUndefinedGuard>) +} + +/** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * `options.queryKey` is required and is the query key to generate options for. + * + * This overload is selected when `initialData` is known to be defined. + * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` known to be defined. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or + * automatically as the user scrolls. + * @see {@link useInfiniteQuery} to run an infinite query with these options. + * @example + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core' + * + * export const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * initialData: { pages: [], pageParams: [] }, + * }) + * + * function Projects() { + * // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the + * // list stays visible alongside the error. + * const { data, isError, error } = useInfiniteQuery(projectsOptions) + * + * return ( + *
+ * {isError ? Error: {error.message} : null} + *
    + * {data.pages.map((page) => page.projects.map((p) =>
  • {p.name}
  • ))} + *
+ *
+ * ) + * } + * ``` + */ +export function infiniteQueryOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & + QueryKeyWithDataTag, TError> + +/** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * `options.queryKey` is required and is the query key to generate options for. + * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or + * automatically as the user scrolls. + * @see {@link useInfiniteQuery} to run an infinite query with these options. + * @example + * A parameterized factory, so the same options object can be reused per `postId`: + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core' + * + * export const commentsOptions = (postId: string) => + * infiniteQueryOptions({ + * queryKey: ['post', postId, 'comments'], + * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Comments({ postId }: { postId: string }) { + * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
    + * {data.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} + *
+ * ) + * } + * ``` + */ +export function infiniteQueryOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & + QueryKeyWithDataTag, TError> + +/** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * `options.queryKey` is required and is the query key to generate options for. + * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks See {@link useInfiniteQuery} for examples that fetch further pages (from a button click or + * automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set. + * @see {@link useInfiniteQuery} to run an infinite query with these options. + * @example + * A parameterized factory, so the same options object can be reused per `postId`: + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core' + * + * export const commentsOptions = (postId: string) => + * infiniteQueryOptions({ + * queryKey: ['post', postId, 'comments'], + * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Comments({ postId }: { postId: string }) { + * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
    + * {data.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} + *
+ * ) + * } + * ``` + */ +export function infiniteQueryOptions< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & + QueryKeyWithDataTag, TError> + +export function infiniteQueryOptions(options: unknown) { + return options +} diff --git a/packages/react-query-no-core/src/mutationOptions.ts b/packages/react-query-no-core/src/mutationOptions.ts new file mode 100644 index 00000000000..c8a25795195 --- /dev/null +++ b/packages/react-query-no-core/src/mutationOptions.ts @@ -0,0 +1,92 @@ +import type { DefaultError, WithRequired } from './runtime' +import type { UseMutationOptions } from './types' + +/** + * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A + * `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with + * `useMutationState`. + * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a + * required `mutationKey`. + * @returns The same options object, unchanged. + * @see {@link useMutation} to run the mutation these options describe. + * @example + * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator: + * ```tsx + * import { mutationOptions, useMutationState } from '@tanstack/react-query-no-core' + * + * const createPostOptions = mutationOptions({ + * mutationKey: ['posts', 'create'], + * mutationFn: createPost, + * }) + * + * function SavingIndicator() { + * const isCreatingPost = useMutationState({ + * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' }, + * }).length > 0 + * + * return isCreatingPost ? Saving… : null + * } + * ``` + */ +export function mutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + options: WithRequired< + UseMutationOptions, + 'mutationKey' + >, +): WithRequired< + UseMutationOptions, + 'mutationKey' +> +/** + * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No + * `mutationKey` is required on this overload — use this when you don't need to target the mutation via a + * `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters, + * such as `status`. + * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a + * `mutationKey`. + * @returns The same options object, unchanged. + * @remarks See the other overload's example for looking a mutation up via `useMutationState`. + * @see {@link useMutation} to run the mutation these options describe. + * @example + * ```tsx + * import { mutationOptions, useMutation } from '@tanstack/react-query-no-core' + * + * export const createPostOptions = mutationOptions({ + * mutationFn: createPost, + * }) + * + * function CreatePost() { + * const mutation = useMutation(createPostOptions) + * return + * } + * ``` + */ +export function mutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + options: Omit< + UseMutationOptions, + 'mutationKey' + >, +): Omit< + UseMutationOptions, + 'mutationKey' +> +export function mutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + options: UseMutationOptions, +): UseMutationOptions { + return options +} diff --git a/packages/react-query-no-core/src/queryOptions.ts b/packages/react-query-no-core/src/queryOptions.ts new file mode 100644 index 00000000000..7e1f4fc7ebb --- /dev/null +++ b/packages/react-query-no-core/src/queryOptions.ts @@ -0,0 +1,242 @@ +import type { + DefaultError, + DefaultQueryFn, + InitialDataFunction, + NonUndefinedGuard, + OmitKeyof, + QueryFunction, + QueryKey, + QueryKeyWithDataTag, + SkipToken, +} from './runtime' +import type { UseQueryOptions } from './types' + +/** + * The options accepted by the `queryOptions` overload selected when `initialData` is omitted, may be + * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is + * `pending`. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export type UndefinedInitialDataOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = UseQueryOptions & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData?: + | undefined + | InitialDataFunction> + | NonUndefinedGuard +} + +/** + * The options accepted by the `queryOptions` overload selected when `queryFn` is not `skipToken` and + * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` — same as + * {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export type UnusedSkipTokenOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = OmitKeyof< + UseQueryOptions, + 'queryFn' +> & { + queryFn: Exclude< + UseQueryOptions['queryFn'], + SkipToken + > +} + +/** + * The options accepted by the `queryOptions` overload selected when `initialData` is known to be defined — + * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. + * @template TQueryKey - The type of your `queryKey`. + */ +export type DefinedInitialDataOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = Omit, 'queryFn'> & { + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). If set to a function, the function will be called **once** during the shared/root + * query initialization, and be expected to synchronously return the initial data. Initial data is + * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the + * cache. + */ + initialData: + | NonUndefinedGuard + | (() => NonUndefinedGuard) + queryFn: QueryFunction | DefaultQueryFn +} + +/** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * is the query key to generate options for. + * + * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never + * `undefined` (unless a `select` changes `TData` to include `undefined`). + * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-no-core' + * + * export const postsOptions = queryOptions({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * initialData: [], + * }) + * + * function Posts() { + * // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, + * // so the list stays visible alongside the error. + * const { data, isError, error } = useQuery(postsOptions) + * + * return ( + *
+ * {isError ? Error: {error.message} : null} + *
    + * {data.map((post) =>
  • {post.title}
  • )} + *
+ *
+ * ) + * } + * ``` + */ +export function queryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: DefinedInitialDataOptions, +): DefinedInitialDataOptions & + QueryKeyWithDataTag + +/** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * is the query key to generate options for. + * @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `useQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * A parameterized factory, so the same options object can be reused per `id`: + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-no-core' + * + * export const postOptions = (id: string) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function Post({ id }: { id: string }) { + * const { data, isPending, isError, error } = useQuery(postOptions(id)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data.title}

+ * } + * ``` + */ +export function queryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UnusedSkipTokenOptions, +): UnusedSkipTokenOptions & + QueryKeyWithDataTag + +/** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * is the query key to generate options for. + * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * A parameterized factory, so the same options object can be reused per `id`: + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-no-core' + * + * export const postOptions = (id: string) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function Post({ id }: { id: string }) { + * const { data, isPending, isError, error } = useQuery(postOptions(id)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data.title}

+ * } + * ``` + * @example + * A factory that disables the query, type safe, until `postId` is set: + * ```tsx + * import { queryOptions, skipToken, useQuery } from '@tanstack/react-query-no-core' + * + * export const postOptions = (postId: number | undefined) => + * queryOptions({ + * queryKey: ['post', postId], + * queryFn: postId != null ? () => fetchPost(postId) : skipToken, + * }) + * + * function Post({ postId }: { postId: number | undefined }) { + * const { data, isLoading, isError, error } = useQuery(postOptions(postId)) + * + * if (postId == null) return 'Select a post' + * if (isLoading) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data?.title}

+ * } + * ``` + */ +export function queryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UndefinedInitialDataOptions, +): UndefinedInitialDataOptions & + QueryKeyWithDataTag + +export function queryOptions(options: unknown) { + return options +} diff --git a/packages/react-query-no-core/src/runtime/environmentManager.ts b/packages/react-query-no-core/src/runtime/environmentManager.ts new file mode 100644 index 00000000000..884adf23e94 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/environmentManager.ts @@ -0,0 +1,41 @@ +import type { IsServerValue } from '@tanstack/query-types/bindings' + +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/react-query-no-core' + * + * 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 + }, +} + +export type { IsServerValue } from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/focusManager.ts b/packages/react-query-no-core/src/runtime/focusManager.ts new file mode 100644 index 00000000000..d2b8745b1cc --- /dev/null +++ b/packages/react-query-no-core/src/runtime/focusManager.ts @@ -0,0 +1,142 @@ +import { Subscribable } from './subscribable' +import type { + FocusManagerListener as Listener, + FocusManagerSetupFn as SetupFn, +} from '@tanstack/query-types/bindings' + +/** + * 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/react-query-no-core' + * + * 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/react-query-no-core' + * + * // 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/react-query-no-core/src/runtime/hydration.ts b/packages/react-query-no-core/src/runtime/hydration.ts new file mode 100644 index 00000000000..25f4fd5cac7 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/hydration.ts @@ -0,0 +1,368 @@ +import { Mutation } from './mutation' +import { noop } from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + DehydratedMutation, + DehydratedQuery, + DehydratedState, + TransformerFn, +} from '@tanstack/query-types/bindings' +import type { Query } from './query' +import type { QueryClient } from './queryClient' +import type { QueryRuntime } from './runtimeBinding' + +/** + * 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 Promise | undefined + + // .catch can be unavailable on certain kinds of thenable's + // oxlint-disable-next-line typescript/no-unnecessary-condition + thenResult?.catch?.(noop) + + if (data !== undefined) { + return { data } + } + + return undefined +} + +export type DehydrateOptions = Shared.DehydrateOptions + +export type HydrateOptions = Shared.HydrateOptions + +// 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: mutation.options.scope }), + ...(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 queryClient.query({ + * queryKey: ['posts'], + * queryFn: getPosts, + * }) + * + * const dehydratedState = dehydrate(queryClient) + * ``` + */ +export function dehydrate( + client: QueryClient, + options: DehydrateOptions = {}, +): DehydratedState { + const filterMutation = + options.shouldDehydrateMutation ?? + client.getDefaultOptions().dehydrate?.shouldDehydrateMutation ?? + defaultShouldDehydrateMutation + + const mutations = client + .getMutationCache() + .getAll() + .flatMap((mutation) => + filterMutation(mutation) ? [dehydrateMutation(mutation)] : [], + ) + + const filterQuery = + options.shouldDehydrateQuery ?? + client.getDefaultOptions().dehydrate?.shouldDehydrateQuery ?? + defaultShouldDehydrateQuery + + const shouldRedactErrors = + options.shouldRedactErrors ?? + client.getDefaultOptions().dehydrate?.shouldRedactErrors + + const serializeData = + options.serializeData ?? client.getDefaultOptions().dehydrate?.serializeData + + const queries = client + .getQueryCache() + .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 { + const queryCache = client.getQueryCache() + const deserializeData = + options?.defaultOptions?.deserializeData ?? + client.getDefaultOptions().hydrate?.deserializeData + + dehydratedState.mutations?.forEach(({ state, ...mutationOptions }) => { + Mutation.build( + client, + { + ...client.getDefaultOptions().hydrate?.mutations, + ...options?.defaultOptions?.mutations, + ...mutationOptions, + }, + state, + ) + }) + + dehydratedState.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, + { + ...client.getDefaultOptions().hydrate?.queries, + ...options?.defaultOptions?.queries, + queryKey, + queryHash, + meta, + _type: queryType, + }, + // 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) + } + }, + ) +} + +export type { DehydratedState } from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/index.ts b/packages/react-query-no-core/src/runtime/index.ts new file mode 100644 index 00000000000..0b313930aa5 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/index.ts @@ -0,0 +1,167 @@ +/* istanbul ignore file */ + +export { focusManager } from './focusManager' +export type { FocusManager } from './focusManager' +export { environmentManager } from './environmentManager' +export { + defaultShouldDehydrateMutation, + defaultShouldDehydrateQuery, + dehydrate, + dehydrateQuery, + hydrate, +} from './hydration' +export { InfiniteQueryObserver } from './infiniteQueryObserver' +export { MutationCache } from './mutationCache' +export type { MutationCacheNotifyEvent } from './mutationCache' +export { MutationObserver } from './mutationObserver' +export { defaultScheduler, notifyManager } from './notifyManager' +export { onlineManager } from './onlineManager' +export type { OnlineManager } from './onlineManager' +export { QueriesObserver } from './queriesObserver' +export { QueryCache } from './queryCache' +export type { QueryCacheNotifyEvent } from './queryCache' +export { QueryClient } from './queryClient' +export { QueryObserver } from './queryObserver' +export type { QueryObserverResultReader } from './queryObserver' +export { CancelledError } from './retryer' +export { + timeoutManager, + type ManagedTimerId, + type TimeoutCallback, + type TimeoutManager, + type TimeoutProvider, +} from './timeoutManager' +export { + hashKey, + keepPreviousData, + matchMutation, + matchQuery, + noop, + partialMatchKey, + replaceEqualDeep, + shouldThrowError, + defaultQueryFn, + skipToken, +} from './utils' +export type { + DefaultQueryFn, + MutationFilters, + QueryFilters, + SkipToken, + Updater, +} from './utils' + +export { streamedQuery } from './streamedQuery' + +// Types +export type { + DehydratedState, + DehydrateOptions, + HydrateOptions, +} from './hydration' +export { Mutation } from './mutation' +export type { MutationState } from './mutation' +export type { MutationCacheConfig } from './mutationCache' +export type { + QueriesObserverOptions, + QueriesObserverResultReader, +} from './queriesObserver' +export { Query } from './query' +export type { QueryState } from './query' +export type { QueryCacheConfig } from './queryCache' +export { dataTagSymbol, dataTagErrorSymbol, unsetMarker } from './types' +export type { + NonUndefinedGuard, + DistributiveOmit, + OmitKeyof, + Override, + Register, + DefaultError, + QueryKey, + UnsetMarker, + AnyDataTag, + DataTag, + QueryKeyWithDataTag, + InferDataFromTag, + InferErrorFromTag, + QueryFunction, + StaleTime, + StaleTimeFunction, + QueryBooleanOption, + QueryPersister, + QueryFunctionContext, + InitialDataFunction, + PlaceholderDataFunction, + QueriesPlaceholderDataFunction, + EqualityFn, + CacheKeyHashFunction, + CacheKeyConfig, + GetPreviousPageParamFunction, + GetNextPageParamFunction, + InfiniteData, + QueryMeta, + NetworkMode, + NotifyOnChangeProps, + QueryOptions, + InitialPageParam, + InfiniteQueryPageParamsOptions, + ThrowOnError, + QueryObserverOptions, + WithRequired, + DefaultedQueryObserverOptions, + InfiniteQueryObserverOptions, + DefaultedInfiniteQueryObserverOptions, + QueryExecuteOptions, + InfiniteQueryExecuteOptions, + ResultOptions, + RefetchOptions, + InvalidateQueryFilters, + RefetchQueryFilters, + InvalidateOptions, + ResetOptions, + FetchNextPageOptions, + FetchPreviousPageOptions, + QueryStatus, + FetchStatus, + QueryObserverBaseResult, + QueryObserverPendingResult, + QueryObserverLoadingResult, + QueryObserverLoadingErrorResult, + QueryObserverRefetchErrorResult, + QueryObserverSuccessResult, + QueryObserverPlaceholderResult, + DefinedQueryObserverResult, + QueryObserverResult, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverPendingResult, + InfiniteQueryObserverLoadingResult, + InfiniteQueryObserverLoadingErrorResult, + InfiniteQueryObserverRefetchErrorResult, + InfiniteQueryObserverSuccessResult, + InfiniteQueryObserverPlaceholderResult, + DefinedInfiniteQueryObserverResult, + InfiniteQueryObserverResult, + MutationKey, + MutationStatus, + MutationScope, + MutationMeta, + MutationFunctionContext, + MutationFunction, + MutationOptions, + MutationObserverOptions, + MutateOptions, + MutateFunctionRest, + MutateFunction, + MutationObserverBaseResult, + MutationObserverIdleResult, + MutationObserverLoadingResult, + MutationObserverErrorResult, + MutationObserverSuccessResult, + MutationObserverResult, + QueryClientConfig, + DefaultOptions, + CancelOptions, + SetDataOptions, + NotifyEventType, + NotifyEvent, +} from './types' diff --git a/packages/react-query-no-core/src/runtime/infiniteQueryBehavior.ts b/packages/react-query-no-core/src/runtime/infiniteQueryBehavior.ts new file mode 100644 index 00000000000..ce7137c31b7 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/infiniteQueryBehavior.ts @@ -0,0 +1,187 @@ +import { + addConsumeAwareSignal, + addToArray, + ensureQueryFn, + fetchSignal, +} from './utils' +import type { QueryBehavior } from './query' +import type { InfiniteData, InfiniteQueryPageParamsOptions } from './types' +import type { FetchSignalContext } from './utils' + +/** + * Creates the behavior that fetches the pages of an infinite query: the next or previous page for + * `fetchNextPage`/`fetchPreviousPage`, or all pages again from the start on a refetch. + * @param pages - The number of pages to fetch from the start when all pages are fetched again, + * e.g. from the `pages` option of `queryClient.infiniteQuery`. Defaults to the number of cached + * pages. + * @returns The query behavior to set on an infinite query. + */ +export function infiniteQueryBehavior( + pages?: number, +): QueryBehavior> { + return { + onFetch: (context, query) => { + const options = context.options as InfiniteQueryPageParamsOptions + 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 = 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) { + context.fetchFn = () => { + return context.options.persister?.( + fetchFn as any, + { + client: context.client, + queryKey: context.queryKey, + meta: context.options.meta, + signal: context.signal, + }, + query, + ) + } + } else { + context.fetchFn = 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 +} diff --git a/packages/react-query-no-core/src/runtime/infiniteQueryObserver.ts b/packages/react-query-no-core/src/runtime/infiniteQueryObserver.ts new file mode 100644 index 00000000000..8fbd5546791 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/infiniteQueryObserver.ts @@ -0,0 +1,277 @@ +import { hasNextPage, hasPreviousPage } from './infiniteQueryBehavior' +import { QueryObserver } from './queryObserver' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + InfiniteQueryObserverListener, + ReplaceReturnType, +} from '@tanstack/query-types/bindings' +import type { Query } from './query' +import type { QueryClient } from './queryClient' +import type { + QueryObserverResultContext, + QueryObserverResultReader, +} from './queryObserver' +import type { QueryRuntime } from './runtimeBinding' +import type { Subscribable } from './subscribable' +import type { + DefaultError, + DefaultedInfiniteQueryObserverOptions, + FetchNextPageOptions, + FetchPreviousPageOptions, + InfiniteData, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverResult, + QueryKey, + QueryObserverResult, +} from './types' + +type InfiniteObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, + TPageParam, +> = Shared.InfiniteObserverOptionsInput< + QueryRuntime, + 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`, and is the primitive that framework adapters (e.g. + * `useInfiniteQuery`) build their hooks on top of. + * @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 { + options._type = 'infinite' + super.setOptions(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({ + ...options, + _type: 'infinite', + }) 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' }, + }, + }) + } + + protected 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 { isFetching, isRefetching, isError, isRefetchError } = parentResult + const fetchDirection = state.fetchMeta?.fetchMore?.direction + + const isFetchNextPageError = isError && fetchDirection === 'forward' + const isFetchingNextPage = isFetching && fetchDirection === 'forward' + + const isFetchPreviousPageError = isError && fetchDirection === 'backward' + const isFetchingPreviousPage = isFetching && fetchDirection === 'backward' + + const result: InfiniteQueryObserverBaseResult = { + ...parentResult, + fetchNextPage: this.fetchNextPage, + fetchPreviousPage: this.fetchPreviousPage, + hasNextPage: hasNextPage(options, state.data), + hasPreviousPage: hasPreviousPage(options, state.data), + isFetchNextPageError, + isFetchingNextPage, + isFetchPreviousPageError, + isFetchingPreviousPage, + isRefetchError: + isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError, + isRefetching: + isRefetching && !isFetchingNextPage && !isFetchingPreviousPage, + } + + return result as InfiniteQueryObserverResult + } +} diff --git a/packages/react-query-no-core/src/runtime/mutation.ts b/packages/react-query-no-core/src/runtime/mutation.ts new file mode 100644 index 00000000000..79a3c27bf95 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/mutation.ts @@ -0,0 +1,503 @@ +import { notifyManager } from './notifyManager' +import { Removable } from './removable' +import { createRetryer } from './retryer' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + MutationAction as Action, + MutationState, +} from '@tanstack/query-types/bindings' +import type { MutationCache } from './mutationCache' +import type { MutationObserver } from './mutationObserver' +import type { QueryClient } from './queryClient' +import type { Retryer } from './retryer' +import type { QueryRuntime } from './runtimeBinding' +import type { + DefaultError, + MutationFunctionContext, + MutationMeta, + MutationOptions, +} from './types' + +type MutationConfig = + Shared.MutationConfig< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult + > + +// 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 = queryClient.getMutationCache() + * + * 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 = client.getMutationCache() + return cache.register( + (mutationId) => + new Mutation({ + client, + mutationCache: cache, + mutationId, + options: client.defaultMutationOptions(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.setOptions(config.options) + this.scheduleGc() + } + + /** + * Replaces the mutation's options and applies their `gcTime`. + * @internal + * @param options - The new mutation options. + */ + setOptions( + options: MutationOptions, + ): void { + this.options = options + + this.updateGcTime(this.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. queryClient.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, + } +} + +export type { + MutationState, + MutationAction as Action, +} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/mutationCache.ts b/packages/react-query-no-core/src/runtime/mutationCache.ts new file mode 100644 index 00000000000..5ebdcc079d7 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/mutationCache.ts @@ -0,0 +1,270 @@ +import { notifyManager } from './notifyManager' +import { Subscribable } from './subscribable' +import { matchMutation, noop } from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { Mutation } from './mutation' +import type { QueryRuntime } from './runtimeBinding' +import type { DefaultError } from './types' +import type { MutationFilters } from './utils' + +export type MutationCacheConfig = Shared.MutationCacheConfig + +export type MutationCacheNotifyEvent = + Shared.MutationCacheNotifyEvent + +type MutationCacheListener = Shared.MutationCacheListener + +// CLASS + +/** + * The `MutationCache` is the storage for mutations. + * + * Normally, you will not interact with the `MutationCache` directly and instead use a + * `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of + * safe/known updates to the cache, such as mutations being added, removed, or updated. + * @example + * ```ts + * const unsubscribe = mutationCache.subscribe((event) => { + * console.log(event.type, event.mutation) + * }) + * ``` + */ +export class MutationCache extends Subscribable { + #mutations: Set> + #scopes: Map>> + #mutationId: number + + constructor(public config: MutationCacheConfig = {}) { + super() + this.#mutations = new Set() + this.#scopes = new Map() + 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) + const scope = scopeFor(mutation) + if (typeof scope === 'string') { + const scopedMutations = this.#scopes.get(scope) + if (scopedMutations) { + scopedMutations.push(mutation) + } else { + this.#scopes.set(scope, [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() + const scope = scopeFor(mutation) + const scopedMutations = this.#scopes.get(scope) + if (scopedMutations) { + const index = scopedMutations.indexOf(mutation) + if (index !== -1) { + scopedMutations.splice(index, 1) + if (!scopedMutations.length) { + this.#scopes.delete(scope) + } + } + } + } + + // 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 { + const firstPendingMutation = this.#scopes + .get(scopeFor(mutation)) + ?.find((candidate) => candidate.state.status === 'pending') + return !firstPendingMutation || firstPendingMutation === mutation + } + + /** + * 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 { + const next = this.#scopes + .get(scopeFor(mutation)) + ?.find((entry) => entry !== mutation && entry.state.isPaused) + + return next?.continue() ?? Promise.resolve() + } + + /** + * Removes all mutations and clears their garbage collection timers. + * Mutations that are already running continue to execute. + * @example + * ```ts + * const mutationCache = queryClient.getMutationCache() + * + * mutationCache.clear() + * ``` + */ + clear(): void { + notifyManager.batch(() => { + const mutations = this.getAll() + this.#mutations.clear() + this.#scopes.clear() + mutations.forEach((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 = queryClient.getMutationCache() + * + * 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 = queryClient.getMutationCache() + * + * 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 = queryClient.getMutationCache() + * + * 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)), + ), + ) + } +} + +/** + * Returns the scope id of a mutation, used to run mutations with the same scope one after another. + * @param mutation - The mutation to read the scope of. + * @returns The mutation's `scope.id`, or `undefined` if it has no scope. + */ +function scopeFor(mutation: Mutation) { + return mutation.options.scope?.id +} diff --git a/packages/react-query-no-core/src/runtime/mutationObserver.ts b/packages/react-query-no-core/src/runtime/mutationObserver.ts new file mode 100644 index 00000000000..2feb3590d83 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/mutationObserver.ts @@ -0,0 +1,331 @@ +import { Mutation, getDefaultState } from './mutation' +import { notifyManager } from './notifyManager' +import { Subscribable } from './subscribable' +import { hashKeyByOptions, shallowEqualObjects } from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { Action } from './mutation' +import type { QueryClient } from './queryClient' +import type { QueryRuntime } from './runtimeBinding' +import type { + DefaultError, + MutateOptions, + MutationFunctionContext, + MutationObserverOptions, + MutationObserverResult, +} from './types' + +type MutationObserverListener = + Shared.MutationObserverListener< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult + > + +// 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 + * QueryClient#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 = this.#client.defaultMutationOptions(options) + if (!shallowEqualObjects(this.options, prevOptions)) { + this.#client.getMutationCache().notify({ + type: 'observerOptionsUpdated', + mutation: this.#currentMutation, + observer: this, + }) + } + + if ( + prevOptions?.mutationKey && + this.options.mutationKey && + hashKeyByOptions( + prevOptions.mutationKey, + this.#client.getMutationCache().config.mutationKey, + ) !== + hashKeyByOptions( + this.options.mutationKey, + this.#client.getMutationCache().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/react-query-no-core/src/runtime/notifyManager.ts b/packages/react-query-no-core/src/runtime/notifyManager.ts new file mode 100644 index 00000000000..ce3f61244ee --- /dev/null +++ b/packages/react-query-no-core/src/runtime/notifyManager.ts @@ -0,0 +1,148 @@ +import type { + BatchCallsCallback, + BatchNotifyFunction, + NotifyCallback, + NotifyFunction, + ScheduleFunction, +} from '@tanstack/query-types/bindings' + +/** + * 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 batchNotifyFn: BatchNotifyFunction = (callback: () => void) => { + 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(() => { + batchNotifyFn(() => { + 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 + }, + /** + * Use this method to set a custom function to batch notifications together into a single tick. + * Framework adapters use this to plug in their own batching primitive, so that a single query + * update only triggers one re-render instead of one per subscriber. + * @param fn - Receives a function that runs a batch of notifications and must call it. + * @example + * ```ts + * import { notifyManager } from '@tanstack/react-query-no-core' + * import { batch } from 'solid-js' + * + * notifyManager.setBatchNotifyFunction(batch) + * ``` + */ + setBatchNotifyFunction: (fn: BatchNotifyFunction) => { + batchNotifyFn = 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/react-query-no-core' + * + * // 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/react-query-no-core/src/runtime/onlineManager.ts b/packages/react-query-no-core/src/runtime/onlineManager.ts new file mode 100644 index 00000000000..78a07bb1662 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/onlineManager.ts @@ -0,0 +1,120 @@ +import { Subscribable } from './subscribable' +import type { + OnlineManagerListener as Listener, + OnlineManagerSetupFn as SetupFn, +} from '@tanstack/query-types/bindings' + +/** + * 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/react-query-no-core' + * + * 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/react-query-no-core' + * + * // 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/react-query-no-core/src/runtime/queriesObserver.ts b/packages/react-query-no-core/src/runtime/queriesObserver.ts new file mode 100644 index 00000000000..1a9392c5ca5 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/queriesObserver.ts @@ -0,0 +1,468 @@ +import { notifyManager } from './notifyManager' +import { QueryObserver } from './queryObserver' +import { Subscribable } from './subscribable' +import { + replaceEqualDeep, + shallowEqualObjects, + shouldThrowError, +} from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + CombineContext, + CombineFn, + QueriesObserverListener, + QueriesObserverOptions, + QueriesObserverResultReader, +} from '@tanstack/query-types/bindings' +import type { QueryClient } from './queryClient' +import type { ObserverOptionsInput } from './queryObserver' +import type { QueryRuntime } from './runtimeBinding' +import type { QueryObserverResult } from './types' + +/** + * 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 `Query` instances currently being observed, in + * the same order as the queries passed to the constructor or `setQueries`. + * @returns The observed queries. + */ + getQueries() { + return this.#observers.map((observer) => observer.getCurrentQuery()) + } + + /** + * 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, + ): QueriesObserverResultReader { + const matches = this.#findMatchingObservers(queries).map((match) => ({ + ...match, + reader: match.observer.createResultReader(match.defaultedQueryOptions), + })) + const queryHashes = matches.map( + (match) => match.defaultedQueryOptions.queryHash, + ) + const combine = options?.combine + const context = { ...this.#combineContext } + let result = this.#result + + const getSnapshot = () => { + const nextResult = matches.map((match) => match.reader.getSnapshot()) + if (!shallowEqualObjects(nextResult, result)) { + result = nextResult + } + return result + } + + return { + getSnapshot, + combineResult: (input) => { + // Notifications may have already combined these results. + const committed = this.#combineContext + if ( + committed.combine === combine && + equalResults(input, committed.result) && + shallowEqualObjects(queryHashes, committed.queryHashes) + ) { + Object.assign(context, committed) + } + return this.#combineResult( + this.#trackResult(input, matches), + combine, + queryHashes, + context, + input, + ) + }, + commit: () => { + this.#combineContext = { ...context } + this.#setQueries(matches, { combine }) + if ( + this.#options?.combine === combine && + equalResults(this.#result, context.result) + ) { + this.#combinedResult = context.value + } + }, + } + } + + #trackResult( + result: Array, + matches: Array, + ) { + const trackedProps = new Set() + + return matches.map((match, index) => { + const observerResult = result[index]! + return !match.defaultedQueryOptions.notifyOnChangeProps + ? match.observer.trackResult(observerResult, (accessedProp) => { + // track property on all observers to ensure proper (synchronized) tracking (#7000) + if (!trackedProps.has(accessedProp)) { + trackedProps.add(accessedProp) + matches.forEach((m) => { + m.observer.trackProp(accessedProp) + }) + } + }) + : observerResult + }) + } + + #combineResult( + input: Array, + combine: CombineFn | undefined, + queryHashes?: Array, + context = this.#combineContext, + result = this.#result, + ): TCombinedResult { + if (combine) { + const queryHashesChanged = + queryHashes !== undefined && + context.queryHashes !== undefined && + !shallowEqualObjects(queryHashes, context.queryHashes) + + if ( + !equalResults(result, context.result) || + queryHashesChanged || + combine !== context.combine + ) { + context.value = replaceEqualDeep(context.value, combine(input)) + context.combine = combine + context.result = result + if (queryHashes !== undefined) { + context.queryHashes = queryHashes + } + } + + return context.value as TCombinedResult + } + return input as any + } + + #shouldSkipCombine(): boolean { + return ( + !this.#options?.combine || + this.#observers.some((observer, index) => { + const result = this.#result[index] + return ( + (observer.options.suspense && result?.data === undefined) || + (!!result?.isError && + !result.isFetching && + shouldThrowError(observer.options.throwOnError, [ + result.error, + observer.getCurrentQuery(), + ])) + ) + }) + ) + } + + #findMatchingObservers( + queries: Array, + ): Array { + const prevObserversMap = new Map>() + + this.#observers.forEach((observer) => { + const key = observer.options.queryHash + if (!key) return + + const previousObservers = prevObserversMap.get(key) + + if (previousObservers) { + previousObservers.push(observer) + } else { + prevObserversMap.set(key, [observer]) + } + }) + + const observers: Array = [] + + queries.forEach((options) => { + const defaultedOptions = this.#client.defaultQueryOptions(options) + const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift() + const observer = + match ?? new QueryObserver(this.#client, defaultedOptions) + + observers.push({ + defaultedQueryOptions: defaultedOptions, + observer, + }) + }) + + return observers + } + + #subscribeTo(observer: QueryObserver): void { + // Create the listener here, not in `setQueries`: a listener created there + // keeps the previous observers, and their queries, alive (#12656) + observer.subscribe((result) => { + this.#onUpdate(observer, result) + }) + } + + #onUpdate(observer: QueryObserver, result: QueryObserverResult): void { + if (this.#updatingQueries) return + + const index = this.#observers.indexOf(observer) + if (index !== -1) { + this.#result = this.#result.slice() + this.#result[index] = result + this.#notify() + } + } + + #notify(): void { + if (this.hasListeners()) { + const shouldSkipCombine = this.#shouldSkipCombine() + const previousResult = this.#combinedResult + const newResult = shouldSkipCombine + ? previousResult + : this.#combineResult( + this.#trackResult(this.#result, this.#observerMatches), + this.#options?.combine, + this.#observerMatches.map( + (match) => match.defaultedQueryOptions.queryHash, + ), + ) + + this.#combinedResult = newResult + if (shouldSkipCombine || previousResult !== newResult) { + notifyManager.batch(() => { + this.listeners.forEach((listener) => { + listener(this.#result) + }) + }) + } + } + } +} + +type QueryObserverMatch = Shared.QueryObserverMatch + +export type { + QueriesObserverResultReader, + QueriesObserverOptions, +} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/query.ts b/packages/react-query-no-core/src/runtime/query.ts new file mode 100644 index 00000000000..fadde455f6e --- /dev/null +++ b/packages/react-query-no-core/src/runtime/query.ts @@ -0,0 +1,872 @@ +import { infiniteQueryBehavior } from './infiniteQueryBehavior' +import { notifyManager } from './notifyManager' +import { Removable } from './removable' +import { CancelledError, canFetch, createRetryer } from './retryer' +import { + ensureQueryFn, + fetchSignal, + noop, + replaceData, + resolveQueryValue, + skipToken, + timeUntilStale, +} from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + FetchOptions, + QueryAction as Action, + QueryState, +} from '@tanstack/query-types/bindings' +import type { QueryCache } from './queryCache' +import type { QueryClient } from './queryClient' +import type { QueryObserver } from './queryObserver' +import type { Retryer } from './retryer' +import type { QueryRuntime } from './runtimeBinding' +import type { + CancelOptions, + DefaultError, + InitialDataFunction, + QueryKey, + QueryMeta, + QueryOptions, + SetDataOptions, + StaleTime, +} from './types' + +type QueryConfig< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey = QueryKey, +> = Shared.QueryConfig + +export type FetchContext< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey = QueryKey, +> = Shared.FetchContext + +export type QueryBehavior< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = Shared.QueryBehavior + +// CLASS + +/** + * Represents a single cached query. A `Query` holds the query's key, options, + * state (data/error/status), and the observers currently subscribed to it. + * + * Instances are created and managed internally by `QueryCache`; application + * code typically interacts with queries indirectly through `QueryClient` or + * a framework hook like `useQuery`. Direct access to a `Query` instance is + * possible via `queryCache.find()`/`findAll()` for inspecting cache state. + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * const query = queryCache.find({ queryKey: ['posts'] }) + * + * if (query) { + * console.log(query.state.dataUpdatedAt) + * } + * ``` + */ +export class Query< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends Removable { + queryKey: TQueryKey + queryHash: string + options!: QueryOptions + state: QueryState + #queryType?: 'infinite' + + #initialState: QueryState + #revertState?: QueryState + #cache: QueryCache + #client: QueryClient + #retryer?: Retryer + #fetchPromise?: Promise + observers: Array> + #defaultOptions?: QueryOptions + #abortSignalConsumed: boolean + + constructor(config: QueryConfig) { + super() + + this.#abortSignalConsumed = false + this.#defaultOptions = config.defaultOptions + this.setOptions(config.options) + this.observers = [] + this.#client = config.client + this.#cache = this.#client.getQueryCache() + this.queryKey = config.queryKey + this.queryHash = config.queryHash + this.#initialState = getDefaultState(this.options) + this.state = config.state ?? this.#initialState + this.scheduleGc() + } + /** + * The `meta` object passed in the query's options, if any. + * @returns The query's `meta`, or `undefined` if none was set. + */ + get meta(): QueryMeta | undefined { + return this.options.meta + } + + /** + * `'infinite'` for an infinite query, otherwise `undefined`. + * @internal + * @returns The type of the query, set from the `_type` option (e.g. `'infinite'`). + */ + get queryType() { + return this.#queryType + } + + /** + * The promise for the currently in-flight fetch, if the query is fetching. + * `undefined` when the query is not fetching. + * @returns The promise of the in-flight fetch, or `undefined`. + */ + get promise(): Promise | undefined { + return this.#retryer?.promise + } + + /** + * Replaces the query's options and applies their `gcTime`. If the query has no data yet, it gets + * the `initialData` from the new options, if any. + * @internal + * @param options - The new query options, merged on top of the query's default options. + */ + setOptions( + options?: QueryOptions, + ): void { + this.options = { ...this.#defaultOptions, ...options } + + if (options?._type) { + this.#queryType = options._type + } + + this.updateGcTime(this.options.gcTime) + + // oxlint-disable-next-line typescript/no-unnecessary-condition -- the constructor calls 'setOptions' before it assigns 'state' + if (this.state && this.state.data === undefined) { + const defaultState = getDefaultState(this.options) + if (defaultState.data !== undefined) { + this.setState( + successState(defaultState.data, defaultState.dataUpdatedAt), + ) + this.#initialState = defaultState + } + } + } + + protected override optionalRemove() { + if (!this.observers.length && this.state.fetchStatus === 'idle') { + this.#cache.remove(this) + } + } + + /** + * Writes new data to the query and marks it as successfully fetched. + * @internal + * @param newData - The data to write. Structural sharing with the current data is applied. + * @param options - Set `updatedAt` to override the timestamp, and `manual` to mark the write as + * manual (e.g. from `queryClient.setQueryData`). + * @returns The data that was written. + */ + setData( + newData: TData, + options?: SetDataOptions & { manual: boolean }, + ): TData { + const data = replaceData(this.state.data, newData, this.options) + + const manual = options?.manual + const dataUpdatedAt = options?.updatedAt + this.state = { + ...this.state, + ...successState(data, dataUpdatedAt), + dataUpdateCount: this.state.dataUpdateCount + 1, + ...(!manual && { + fetchStatus: 'idle' as const, + fetchFailureCount: 0, + fetchFailureReason: null, + }), + } + // A manual write becomes the snapshot to restore if a fetch is cancelled. + this.#revertState = manual ? this.state : undefined + this.#notify({ type: 'success', data, dataUpdatedAt, manual }) + + return data + } + + /** + * Merges the given partial state directly into this query's state, notifying observers. Used + * by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a + * user manually trigger a loading/error state or edit the cached data. + * @param state - The partial state to merge into the query's state. + */ + setState(state: Partial>): void { + this.#update(state, { type: 'setState', state }) + } + + /** + * Cancels the query's currently in-flight fetch, if any. + * - Returns a promise that resolves once the cancellation has settled. + * - If no fetch is in progress, resolves immediately. + * @param options - Set `revert` to restore the state from before the fetch started, and `silent` + * to suppress the cancellation error when a new fetch replaces the cancelled one. + * @returns A promise that resolves once the cancellation has settled. + * @example + * ```ts + * await query.cancel() + * ``` + */ + cancel(options?: CancelOptions): Promise { + const promise = this.#retryer?.promise + this.#retryer?.cancel(options) + return promise ? promise.then(noop, noop) : Promise.resolve() + } + + /** + * Silently cancels any in-flight fetch, then clears the query's garbage + * collection timeout. Called by `QueryCache` when the query is removed from + * the cache. + * @see {@link Query#cancel} + */ + override destroy(): void { + this.cancel({ silent: true }) + // An abort listener can unsubscribe and schedule GC during cancellation. + super.destroy() + } + + /** + * The state the query was created with. + * @internal + * @returns The state the query had when it was first created, used by {@link Query#reset}. + */ + get resetState(): QueryState { + return this.#initialState + } + + /** + * Resets the query back to its initial state (the state it had when it was + * first created, e.g. any `initialData`), destroying it first to cancel any + * in-flight fetch. + */ + reset(): void { + this.destroy() + this.setState(this.resetState) + } + + /** + * Returns `true` if the query has at least one observer for which `enabled` + * does not resolve to `false`. + * @returns `true` if the query has an enabled observer. + */ + isActive(): boolean { + return this.observers.some( + (observer) => resolveQueryValue(observer.options.enabled, this) !== false, + ) + } + + /** + * Returns `true` if the query is disabled, meaning it will not fetch + * automatically. + * - If the query has observers, it is disabled when none of them are active + * (see `isActive`). + * - If the query has no observers, it is disabled when its `queryFn` is + * `skipToken` or it has never been fetched. + * @returns `true` if the query is disabled. + */ + isDisabled(): boolean { + if (this.getObserversCount() > 0) { + return !this.isActive() + } + // if a query has no observers, it should still be considered disabled if it never attempted a fetch + return this.options.queryFn === skipToken || !this.isFetched() + } + + /** + * Returns `true` if the query has been fetched, i.e. it has resolved with + * either data or an error at least once. + * @returns `true` if the query has been fetched. + */ + isFetched() { + return this.state.dataUpdateCount + this.state.errorUpdateCount > 0 + } + + /** + * Returns `true` if the query has data and at least one observer configured with + * `staleTime: 'static'`, meaning it is treated as never stale. + * @returns `true` if the query is static. + */ + isStatic(): boolean { + if (this.state.data === undefined) { + return false + } + + if (this.getObserversCount() > 0) { + return this.observers.some( + (observer) => + resolveQueryValue(observer.options.staleTime, this) === 'static', + ) + } + + return false + } + + /** + * Returns `true` if the query is stale. + * - If the query has observers, defers to whether any observer's current + * result reports `isStale` (which accounts for each observer's own + * `staleTime` and `enabled` state). + * - If the query has no observers, it is considered stale when it has no + * data or has been invalidated. + * @returns `true` if the query is stale. + * @see {@link Query#isStaleByTime} + * @example + * ```ts + * if (query.isStale()) { + * // refetch or otherwise treat the cached data as outdated + * } + * ``` + */ + isStale(): boolean { + // check observers first, their `isStale` has the source of truth + // calculated with `isStaleByTime` and it takes `enabled` into account + if (this.getObserversCount() > 0) { + return this.observers.some( + (observer) => observer.getCurrentResult().isStale, + ) + } + + return this.state.data === undefined || this.state.isInvalidated + } + + /** + * Returns `true` if the query's data is stale relative to the given + * `staleTime` (defaults to `0`). + * - A query with no data is always stale. + * - `staleTime: 'static'` is never stale. + * - An invalidated query is always stale. + * - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`. + * @param staleTime - The time, in milliseconds, after which data is considered stale, or + * `'static'` to never treat existing data as stale. A query without data is stale either way. + * @returns `true` if the query's data is stale. + * @see {@link Query#isStale} + * @example + * ```ts + * const isStale = query.isStaleByTime(60 * 1000) + * ``` + */ + isStaleByTime(staleTime: StaleTime = 0): boolean { + // no data is always stale + if (this.state.data === undefined) { + return true + } + // static is never stale + if (staleTime === 'static') { + return false + } + // if the query is invalidated, it is stale + if (this.state.isInvalidated) { + return true + } + + return !timeUntilStale(this.state.dataUpdatedAt, staleTime) + } + + /** + * Refetches the query when the window regains focus, if an observer wants that, and continues a + * paused fetch. + * @internal + */ + onFocus(): void { + const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus()) + + observer?.refetch({ cancelRefetch: false }) + + // Continue fetch if currently paused + this.#retryer?.continue() + } + + /** + * Refetches the query when the app reconnects, if an observer wants that, and continues a paused + * fetch. + * @internal + */ + onOnline(): void { + const observer = this.observers.find((x) => x.shouldFetchOnReconnect()) + + observer?.refetch({ cancelRefetch: false }) + + // Continue fetch if currently paused + this.#retryer?.continue() + } + + /** + * Subscribes an observer to the query and stops its garbage collection. + * @internal + * @param observer - The observer to add. Adding an observer that is already subscribed does + * nothing. + */ + addObserver(observer: QueryObserver): void { + if (!this.observers.includes(observer)) { + this.observers.push(observer) + + // Stop the query from being garbage collected + this.clearGcTimeout() + + this.#cache.notify({ type: 'observerAdded', query: this, observer }) + } + } + + /** + * Unsubscribes an observer from the query. + * @internal + * @param observer - The observer to remove. When the last observer is removed, the in-flight + * fetch is cancelled if its abort signal was consumed (otherwise only its retries are stopped), + * and garbage collection is scheduled if the query is still in the cache. + */ + removeObserver(observer: QueryObserver): void { + const index = this.observers.indexOf(observer) + if (index !== -1) { + this.observers.splice(index, 1) + + if (!this.observers.length) { + // If the transport layer does not support cancellation + // we'll let the query continue so the result can be cached + if (this.#retryer) { + if ( + this.#abortSignalConsumed || + (this.state.fetchStatus === 'paused' && + this.state.status === 'pending') + ) { + this.#retryer.cancel({ revert: true }) + } else { + this.#retryer.cancelRetry() + } + } + + this.#scheduleGcIfCached() + } + + this.#cache.notify({ type: 'observerRemoved', query: this, observer }) + } + } + + /** + * Returns the number of observers currently subscribed to this query. + * @returns The number of observers. + * @example + * ```ts + * if (query.getObserversCount() === 0) { + * // no component is currently watching this query + * } + * ``` + */ + getObserversCount(): number { + return this.observers.length + } + + /** + * Marks the query as invalidated, unless it is already invalidated. This + * updates `state.isInvalidated` and notifies observers, but does not by + * itself trigger a refetch. + * @example + * ```ts + * query.invalidate() + * ``` + */ + invalidate(): void { + if (!this.state.isInvalidated) { + this.#update({ isInvalidated: true }, { type: 'invalidate' }) + } + } + + /** + * Fetches the query, i.e. runs its `queryFn` (through any configured + * retryer/behavior) and updates the query's state with the result. + * - If a fetch is already in flight, returns its promise instead of + * starting a new one, unless `fetchOptions.cancelRefetch` is set and the + * query already has data, in which case the current fetch is silently + * cancelled first. + * - If `options` is passed, it replaces the query's current options + * before fetching. + * @param options - Query options that replace the query's current options before fetching. They + * are not applied when an in-flight fetch is reused. + * @param fetchOptions - Set `cancelRefetch` to cancel an in-flight fetch first (only if the query + * already has data), and `meta` to pass extra information to the query's behavior. + * @returns A promise that resolves with the fetched data, or rejects with the fetch error. If the + * fetch is cancelled with `revert` while the query has data, it resolves with the restored data + * instead. + */ + async fetch( + options?: QueryOptions, + fetchOptions?: FetchOptions, + ): Promise { + if ( + this.state.fetchStatus !== 'idle' && + // If the promise in the retryer is already rejected, we have to definitely + // re-start the fetch; there is a chance that the query is still in a + // pending state when that happens + this.#retryer?.status() !== 'rejected' + ) { + if (this.state.data !== undefined && fetchOptions?.cancelRefetch) { + // Silently cancel current fetch if the user wants to cancel refetch + this.cancel({ silent: true }) + } else if (this.#retryer && this.#fetchPromise) { + // make sure that retries that were potentially cancelled due to unmounts can continue + this.#retryer.continueRetry() + // Return current promise if we are already fetching + return this.#fetchPromise + } + } + + // Update config if passed, otherwise the config from the last execution is used + if (options) { + this.setOptions(options) + } + + // Use the options from the first observer with a query function if no function is found. + // This can happen when the query is hydrated or created with setQueryData. + if (!this.options.queryFn) { + const observer = this.observers.find((x) => x.options.queryFn) + if (observer) { + this.setOptions(observer.options) + } + } + + if (process.env.NODE_ENV !== 'production') { + if (!Array.isArray(this.options.queryKey)) { + console.error( + `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`, + ) + } + } + + const abortController = new AbortController() + + const addSignalProperty: ( + object: object, + ) => asserts object is { signal: AbortSignal } = (object) => { + Object.defineProperties(object, { + [fetchSignal]: { value: abortController.signal, enumerable: true }, + signal: { + enumerable: true, + get: () => { + this.#abortSignalConsumed = true + return abortController.signal + }, + }, + }) + } + + // Create fetch function + const fetchFn = () => { + const queryFn = ensureQueryFn(this.options, fetchOptions) + + const queryFnContext = { + client: this.#client, + queryKey: this.queryKey, + meta: this.meta, + } + addSignalProperty(queryFnContext) + + this.#abortSignalConsumed = false + if (this.options.persister) { + return this.options.persister( + queryFn, + queryFnContext, + this as unknown as Query, + ) + } + + return queryFn(queryFnContext) + } + + // Trigger behavior hook + const context = { + fetchOptions, + options: this.options, + queryKey: this.queryKey, + client: this.#client, + state: this.state, + fetchFn, + } + addSignalProperty(context) + + if (this.#queryType === 'infinite') { + const behavior = infiniteQueryBehavior( + (this.options as { pages?: number }).pages, + ) as QueryBehavior + behavior.onFetch(context, this as unknown as Query) + } + + // Store state in case the current fetch needs to be reverted + this.#revertState = this.state + + // Set to fetching state if not already in it + if ( + this.state.fetchStatus === 'idle' || + this.state.fetchMeta !== context.fetchOptions?.meta + ) { + const meta = context.fetchOptions?.meta + this.#update( + { + ...fetchState(this.state.data, this.options), + fetchMeta: meta ?? null, + }, + { type: 'fetch', meta }, + ) + } + + // Try to fetch the data + const retryer = (this.#retryer = createRetryer({ + initialPromise: fetchOptions?.initialPromise as + | Promise + | undefined, + fn: context.fetchFn as () => Promise, + onCancel: (error) => { + if (error instanceof CancelledError && error.revert) { + this.setState({ + ...this.#revertState, + fetchStatus: 'idle' as const, + }) + } + abortController.abort() + }, + onFail: (failureCount, error) => { + this.#update( + { fetchFailureCount: failureCount, fetchFailureReason: error }, + { type: 'failed', failureCount, error }, + ) + }, + onPause: () => { + this.#update({ fetchStatus: 'paused' }, { type: 'pause' }) + }, + onContinue: () => { + this.#update({ fetchStatus: 'fetching' }, { type: 'continue' }) + }, + retry: context.options.retry, + retryDelay: context.options.retryDelay, + networkMode: context.options.networkMode, + canRun: () => true, + })) + + const fetchPromise = (async () => { + try { + const data = await retryer.promise + // this is more of a runtime guard + if (data === undefined) { + if (process.env.NODE_ENV !== 'production') { + console.error( + `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`, + ) + } + throw new Error(`${this.queryHash} data is undefined`) + } + + this.setData(data) + + // Notify cache callback + this.#cache.config.onSuccess?.(data, this as Query) + this.#cache.config.onSettled?.( + data, + this.state.error as any, + this as Query, + ) + return data + } catch (error) { + if (error instanceof CancelledError) { + if (error.silent) { + if (this.#retryer !== retryer && this.#fetchPromise) { + // A new fetch replaced the silently cancelled one, + // so we piggyback onto that promise. + return this.#fetchPromise + } + throw error + } else if (error.revert) { + // transform error into reverted state data + // if the initial fetch was cancelled, we have no data, so we have + // to get reject with a CancelledError + if (this.state.data === undefined) { + throw error + } + return this.state.data + } + } + const fetchError = error as TError + this.#update( + { + error: fetchError, + errorUpdatedAt: Date.now(), + errorUpdateCount: this.state.errorUpdateCount + 1, + fetchFailureCount: this.state.fetchFailureCount + 1, + fetchFailureReason: fetchError, + fetchStatus: 'idle', + status: 'error', + isInvalidated: true, + }, + { type: 'error', error: fetchError }, + ) + + // Notify cache callback + this.#cache.config.onError?.( + error as any, + this as Query, + ) + this.#cache.config.onSettled?.( + this.state.data, + error as any, + this as Query, + ) + + throw error // rethrow the error for further handling + } finally { + // The settled retryer's promise would otherwise pin this fetch's raw + // result (a second copy after structural sharing) for the query's lifetime + if (this.#retryer === retryer) { + this.#retryer = undefined + this.#fetchPromise = undefined + } + this.#scheduleGcIfCached() + } + })() + this.#fetchPromise = fetchPromise + retryer.start() + return fetchPromise + } + + #scheduleGcIfCached(): void { + if ( + this.#cache.get( + this.queryHash, + ) === this + ) { + this.scheduleGc() + } + } + + #update( + state: Partial>, + action: Action, + ): void { + this.state = { ...this.state, ...state } + this.#notify(action) + } + + #notify(action: Action): void { + notifyManager.batch(() => { + // Keep the current iteration stable if an observer unsubscribes + // synchronously while it is being notified. + this.observers.slice().forEach((observer) => { + observer.onQueryUpdate() + }) + + this.#cache.notify({ query: this, type: 'updated', action }) + }) + } +} + +/** + * Returns the state changes applied when a query starts fetching. + * @param data - The query's current data. If it is `undefined`, the query is also reset to + * `'pending'` with no error. + * @param options - The query options, whose `networkMode` decides whether the query is `'fetching'` + * or `'paused'`. + * @returns The partial query state for a starting fetch. + */ +export function fetchState< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, +>( + data: TData | undefined, + options: QueryOptions, +) { + return { + fetchFailureCount: 0, + fetchFailureReason: null, + fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused', + ...(data === undefined && + ({ + error: null, + status: 'pending', + } as const)), + } as const +} + +/** + * Returns the state changes applied when a query receives data. + * @param data - The new data. + * @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to the current time. + * @returns The partial query state for a successful update. + */ +function successState(data: TData | undefined, dataUpdatedAt?: number) { + return { + data, + dataUpdatedAt: dataUpdatedAt ?? Date.now(), + error: null, + isInvalidated: false, + status: 'success' as const, + } +} + +/** + * Returns the initial state of a query, based on its `initialData` and `initialDataUpdatedAt` + * options. + * @param options - The query options. + * @returns The initial query state: `'success'` if `initialData` is set, otherwise `'pending'`. + */ +function getDefaultState< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, +>( + options: QueryOptions, +): QueryState { + const data = + typeof options.initialData === 'function' + ? (options.initialData as InitialDataFunction)() + : options.initialData + + const hasData = data !== undefined + + const initialDataUpdatedAt = hasData + ? typeof options.initialDataUpdatedAt === 'function' + ? options.initialDataUpdatedAt() + : options.initialDataUpdatedAt + : 0 + + return { + data, + dataUpdateCount: 0, + dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0, + error: null, + errorUpdateCount: 0, + errorUpdatedAt: 0, + fetchFailureCount: 0, + fetchFailureReason: null, + fetchMeta: null, + isInvalidated: false, + status: hasData ? 'success' : 'pending', + fetchStatus: 'idle', + } +} + +export type { + QueryState, + FetchDirection, + FetchMeta, + FetchOptions, + QueryAction as Action, +} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/queryCache.ts b/packages/react-query-no-core/src/runtime/queryCache.ts new file mode 100644 index 00000000000..834a79a6eec --- /dev/null +++ b/packages/react-query-no-core/src/runtime/queryCache.ts @@ -0,0 +1,298 @@ +import { notifyManager } from './notifyManager' +import { Query } from './query' +import { Subscribable } from './subscribable' +import { hashKeyByOptions, matchQuery } from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { QueryState } from './query' +import type { QueryClient } from './queryClient' +import type { QueryRuntime } from './runtimeBinding' +import type { + DefaultError, + QueryKey, + QueryOptions, + WithRequired, +} from './types' +import type { QueryFilters } from './utils' + +export type QueryCacheConfig = Shared.QueryCacheConfig + +export type QueryCacheNotifyEvent = Shared.QueryCacheNotifyEvent + +type QueryCacheListener = Shared.QueryCacheListener + +export type QueryStore = Shared.QueryStore + +// CLASS + +/** + * The `QueryCache` is the storage mechanism for TanStack Query. It stores all the data, meta + * information, and state of the queries it contains. + * + * Normally, you will not interact with the `QueryCache` directly and instead use a `QueryClient` + * for a specific cache. You can subscribe to it (inherited from `Subscribable`) to be informed of + * safe/known updates to the cache, such as queries being added, removed, or updated — updates made + * outside of the cache's own tracked mechanisms (e.g. mutating a query's state object directly) do + * not notify subscribers. + * @example + * ```ts + * const unsubscribe = queryCache.subscribe((event) => { + * console.log(event.type, event.query) + * }) + * ``` + */ +export class QueryCache extends Subscribable { + #queries: QueryStore + + constructor(public config: QueryCacheConfig = {}) { + super() + this.#queries = new Map() + } + + /** + * Returns the existing `Query` instance for the given options' `queryKey`/`queryHash`, or + * builds and adds a new one to the cache if none exists yet. Used by framework adapters and + * plugins (e.g. broadcast/persistence) that need to get-or-create a `Query` directly, bypassing + * the reactive `QueryObserver` machinery. + * @param client - The client the query belongs to, used to default its options. + * @param options - The query options, including the `queryKey`. A new query is created with the + * options defaulted by {@link QueryClient#defaultQueryOptions}. + * @param state - The initial state of a newly created query, e.g. when hydrating. Ignored if the + * query already exists. + * @returns The existing or newly created query. + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * + * const query = queryCache.build(queryClient, { + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * ``` + */ + build< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + client: QueryClient, + options: WithRequired< + QueryOptions, + 'queryKey' + >, + state?: QueryState, + ): Query { + const queryKey = options.queryKey + const queryHash = + options.queryHash ?? hashKeyByOptions(queryKey, this.config.queryKey) + let query = this.get(queryHash) + + if (!query) { + query = new Query({ + client, + queryKey, + queryHash, + options: client.defaultQueryOptions(options), + state, + defaultOptions: client.getQueryDefaults(queryKey), + }) + this.add(query) + } + + return query + } + + /** + * Adds a query to the cache. + * @internal + * @param query - The query to add. If a query with the same hash is already cached, nothing + * happens. + */ + add(query: Query): void { + if (!this.#queries.has(query.queryHash)) { + this.#queries.set(query.queryHash, query) + + this.notify({ + type: 'added', + query, + }) + } + } + + /** + * Destroys the given `Query` and removes it from the cache, notifying subscribers with a + * `'removed'` event. A no-op if the query is no longer the one currently stored under its hash + * (e.g. it was already replaced). Used by plugins (e.g. the broadcast client) that mirror + * removals across `QueryCache` instances. + * @param query - The query to remove. + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * const query = queryCache.find({ queryKey: ['posts'] }) + * + * if (query) { + * queryCache.remove(query) + * } + * ``` + */ + remove(query: Query): void { + const queryInMap = this.#queries.get(query.queryHash) + + if (queryInMap === query) { + query.destroy() + this.#queries.delete(query.queryHash) + this.notify({ type: 'removed', query }) + } + } + + /** + * Removes all queries from the cache. + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * + * queryCache.clear() + * ``` + */ + clear(): void { + notifyManager.batch(() => { + this.getAll().forEach((query) => { + this.remove(query) + }) + }) + } + + /** + * Returns the `Query` instance stored under the given `queryHash`, or `undefined` if none + * exists. Unlike {@link QueryCache#find}, this looks up by the already-computed hash rather + * than by `QueryFilters`. Used by plugins (e.g. broadcast/hydration) that already have a hash + * to look up directly. + * @param queryHash - The hash of the query to look up. + * @returns The query stored under the hash, or `undefined`. + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * const queryHash = hashKey(['posts']) + * + * const query = queryCache.get(queryHash) + * ``` + */ + get< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + queryHash: string, + ): Query | undefined { + return this.#queries.get(queryHash) as + | Query + | undefined + } + + /** + * Returns all queries within the cache. + * @returns Every query in the cache. + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * + * const queries = queryCache.getAll() + * ``` + */ + getAll(): Array { + return [...this.#queries.values()] + } + + /** + * A slightly more advanced method that can be used to get an existing query instance from the + * cache. This instance not only contains all the state for the query, but all of the instances, + * and underlying guts of the query as well. If the query 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 query in rare scenarios (e.g. looking at `query.state.dataUpdatedAt` to + * decide whether a query is fresh enough to be used as an initial value). + * @param filters - The filters to match, including the required `queryKey`. `exact` defaults to + * `true`. + * @returns The first matching query, or `undefined`. + * @see {@link QueryCache#findAll} + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * + * const query = queryCache.find({ queryKey: ['posts'] }) + * ``` + */ + find( + filters: WithRequired, + ): Query | undefined { + const defaultedFilters = { exact: true, ...filters } + + return this.getAll().find((query) => + matchQuery(defaultedFilters, query, this.config.queryKey), + ) as Query | undefined + } + + /** + * An even more advanced method that can be used to get existing query instances from the cache + * that partially match a query key. If no queries match, an empty array is returned. + * + * This is not typically needed for most applications, but can come in handy when needing more + * information about queries in rare scenarios. + * @param filters - The filters to match. Without filters, every query is returned. + * @returns The matching queries. + * @see {@link QueryCache#find} + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * + * const queries = queryCache.findAll({ queryKey: ['posts'] }) + * ``` + */ + findAll(filters: QueryFilters = {}): Array { + const queries = this.getAll() + return Object.keys(filters).length > 0 + ? queries.filter((query) => + matchQuery(filters, query, this.config.queryKey), + ) + : queries + } + + /** + * Notifies every cache listener of an event, in one batch. + * @internal + * @param event - The event passed to every listener. + */ + notify(event: QueryCacheNotifyEvent): void { + notifyManager.batch(() => { + this.listeners.forEach((listener) => { + listener(event) + }) + }) + } + + /** + * Calls {@link Query#onFocus} on every cached query, in one batch. + * @internal + */ + onFocus(): void { + notifyManager.batch(() => { + this.getAll().forEach((query) => { + query.onFocus() + }) + }) + } + + /** + * Calls {@link Query#onOnline} on every cached query, in one batch. + * @internal + */ + onOnline(): void { + notifyManager.batch(() => { + this.getAll().forEach((query) => { + query.onOnline() + }) + }) + } +} diff --git a/packages/react-query-no-core/src/runtime/queryClient.ts b/packages/react-query-no-core/src/runtime/queryClient.ts new file mode 100644 index 00000000000..5afee16c341 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/queryClient.ts @@ -0,0 +1,1077 @@ +import { focusManager } from './focusManager' +import { MutationCache } from './mutationCache' +import { notifyManager } from './notifyManager' +import { onlineManager } from './onlineManager' +import { QueryCache } from './queryCache' +import { + defaultQueryFn, + functionalUpdate, + hashKeyByOptions, + noop, + partialMatchKey, + resolveQueryValue, + skipToken, +} from './utils' +import type { WithoutSkipToken } from '@tanstack/query-types/bindings' +import type { QueryState } from './query' +import type { + CacheKeyConfig, + CancelOptions, + DefaultError, + DefaultOptions, + DefaultedQueryObserverOptions, + InferDataFromTag, + InferErrorFromTag, + InfiniteData, + InfiniteQueryExecuteOptions, + InvalidateOptions, + InvalidateQueryFilters, + MutationKey, + MutationObserverOptions, + MutationOptions, + OmitKeyof, + QueryClientConfig, + QueryExecuteOptions, + QueryKey, + QueryObserverOptionsBase, + QueryOptions, + RefetchOptions, + RefetchQueryFilters, + ResetOptions, + SetDataOptions, +} from './types' +import type { MutationFilters, QueryFilters, Updater } from './utils' + +type QueryDefaults = OmitKeyof, 'queryKey'> +type MutationDefaults = MutationOptions + +class KeyDefaults< + TKey extends ReadonlyArray, + TOptions extends object, +> { + #entries = new Map() + + set(key: TKey, options: TOptions, config?: CacheKeyConfig): void { + this.#entries.set(hashKeyByOptions(key, config), { key, options }) + } + + get(key: TKey, config?: CacheKeyConfig): Partial { + const result: Partial = {} + for (const entry of this.#entries.values()) { + if (partialMatchKey(key, entry.key, config?.equalityFn)) { + Object.assign(result, entry.options) + } + } + return result + } +} + +// CLASS + +/** + * `QueryClient` is used to interact with a cache of queries and mutations. It owns a + * `QueryCache` and a `MutationCache` (creating default ones if none are passed in) and holds + * the default options that are applied to queries and mutations created through it. + * @example + * ```ts + * const queryClient = new QueryClient({ + * defaultOptions: { + * queries: { + * staleTime: Infinity, + * }, + * }, + * }) + * + * await queryClient.query({ queryKey: ['posts'], queryFn: fetchPosts }) + * ``` + */ +export class QueryClient { + #queryCache: QueryCache + #mutationCache: MutationCache + #defaultOptions: DefaultOptions + #queryDefaults = new KeyDefaults() + #mutationDefaults = new KeyDefaults() + #mountCount: number + #unsubscribeFocus?: () => void + #unsubscribeOnline?: () => void + + constructor(config: QueryClientConfig = {}) { + this.#queryCache = config.queryCache || new QueryCache() + this.#mutationCache = config.mutationCache || new MutationCache() + this.#defaultOptions = config.defaultOptions || {} + this.#mountCount = 0 + } + + /** + * Called by a framework adapter's `QueryClientProvider`-equivalent when it mounts, to start + * listening for focus/online events and resume paused mutations. Ref-counted via an internal + * mount count, so nested or multiple providers sharing the same `QueryClient` don't tear down + * the shared listeners until the last one unmounts. + */ + mount(): void { + this.#mountCount++ + if (this.#mountCount !== 1) return + + this.#unsubscribeFocus = focusManager.subscribe(async (focused) => { + if (focused) { + await this.resumePausedMutations() + this.#queryCache.onFocus() + } + }) + this.#unsubscribeOnline = onlineManager.subscribe(async (online) => { + if (online) { + await this.resumePausedMutations() + this.#queryCache.onOnline() + } + }) + } + + /** + * The inverse of {@link QueryClient#mount} — called by a framework adapter's + * `QueryClientProvider`-equivalent when it unmounts. Only tears down the focus/online + * listeners once the mount count returns to `0`. + */ + unmount(): void { + this.#mountCount-- + if (this.#mountCount !== 0) return + + this.#unsubscribeFocus?.() + this.#unsubscribeFocus = undefined + + this.#unsubscribeOnline?.() + this.#unsubscribeOnline = undefined + } + + /** + * Returns the number of queries in the cache that are currently fetching, optionally + * matching a set of filters. This includes background-fetching, loading new pages, and + * loading more infinite query results. + * @param filters - Narrows down which fetching queries are counted. Without filters, every + * fetching query is counted. + * @returns The number of matching queries whose `fetchStatus` is `'fetching'`. + * @example + * ```ts + * if (queryClient.isFetching()) { + * console.log('At least one query is fetching!') + * } + * ``` + */ + isFetching(filters?: Omit): number { + return this.#queryCache.findAll({ ...filters, fetchStatus: 'fetching' }) + .length + } + + /** + * Returns the number of mutations in the cache that are currently pending, optionally + * matching a set of filters. + * @param filters - Narrows down which pending mutations are counted. Without filters, every + * pending mutation is counted. + * @returns The number of matching mutations whose `status` is `'pending'`. + * @example + * ```ts + * if (queryClient.isMutating()) { + * console.log('At least one mutation is pending!') + * } + * ``` + */ + isMutating< + TMutationFilters extends MutationFilters = MutationFilters< + any, + any + >, + >(filters?: NoInfer>): number { + return this.#mutationCache.findAll({ ...filters, status: 'pending' }).length + } + + /** + * Imperative (non-reactive) way to retrieve data for a QueryKey. + * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates. + * + * Hint: Do not use this function inside a component, because it won't receive updates. + * Use `useQuery` to create a `QueryObserver` that subscribes to changes. + * @param queryKey - The query key of the query to read. + * @returns The cached data for the query, or `undefined` if no query with this key has been observed yet. + * @see {@link QueryClient#getQueriesData} + */ + getQueryData< + TQueryFnData = unknown, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, + >(queryKey: TTaggedQueryKey): TInferredQueryFnData | undefined { + const options = this.defaultQueryOptions({ queryKey }) + + return this.#queryCache.get(options.queryHash)?.state + .data + } + + /** + * 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 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 QueryClient#getQueryData} + * @example + * ```ts + * const data = queryClient.getQueriesData({ queryKey: ['posts'] }) + * ``` + */ + getQueriesData< + TQueryFnData = unknown, + TQueryFilters extends QueryFilters = QueryFilters, + >(filters: TQueryFilters): Array<[QueryKey, TQueryFnData | undefined]> { + return this.#queryCache.findAll(filters).map(({ queryKey, state }) => { + const data = state.data as TQueryFnData | undefined + return [queryKey, data] + }) + } + + /** + * Synchronous way to immediately update a query's cached data. If the updater (or the value + * passed) resolves to `undefined`, the cache is left untouched and no query is created; + * otherwise, if the query does not exist yet, it will be created. To update multiple queries + * at once by partially matching query keys, use {@link QueryClient#setQueriesData} instead. + * + * Updates must be performed immutably: do not mutate `oldData`, or data previously retrieved + * via {@link QueryClient#getQueryData}, in place. + * @param queryKey - The query key to set data for. + * @param updater - Either the new data, or a function that receives the 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 The data that was written, or `undefined` if the updater returned `undefined` — in that case + * the write is skipped and the cache is left unchanged. + * @example + * ```ts + * queryClient.setQueryData(['posts'], newPosts) + * + * // Or, using an updater function that receives the current data: + * queryClient.setQueryData(['posts'], (oldPosts) => [...oldPosts, newPost]) + * ``` + */ + setQueryData< + TQueryFnData = unknown, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, + >( + queryKey: TTaggedQueryKey, + updater: Updater< + InferDataFromTag, TTaggedQueryKey> | undefined, + NoInfer | undefined + >, + options?: SetDataOptions, + ): NoInfer | undefined { + const defaultedOptions = this.defaultQueryOptions< + any, + any, + unknown, + any, + QueryKey + >({ queryKey }) + + const query = this.#queryCache.get< + InferDataFromTag, TTaggedQueryKey> + >(defaultedOptions.queryHash) + const prevData = query?.state.data + const data = functionalUpdate(updater, prevData) + + if (data === undefined) { + return undefined + } + + return this.#queryCache + .build(this, defaultedOptions) + .setData(data, { ...options, manual: true }) + } + + /** + * 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 QueryClient#setQueryData} for each matching query. + * @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 QueryClient#setQueryData}. + * @example + * ```ts + * queryClient.setQueriesData({ queryKey: ['posts'] }, (oldPosts) => + * oldPosts ? oldPosts.filter((post) => post.id !== deletedId) : oldPosts, + * ) + * ``` + */ + setQueriesData< + TQueryFnData, + TQueryFilters extends QueryFilters = QueryFilters, + >( + filters: TQueryFilters, + updater: Updater< + NoInfer | undefined, + NoInfer | undefined + >, + options?: SetDataOptions, + ): Array<[QueryKey, TQueryFnData | undefined]> { + return notifyManager.batch(() => + this.#queryCache + .findAll(filters) + .map(({ queryKey }) => [ + queryKey, + this.setQueryData(queryKey, updater, options), + ]), + ) + } + + /** + * Imperative (non-reactive) way to retrieve an existing query's state. If the query does not + * exist, `undefined` is returned. + * @param queryKey - The query key of the query to read. + * @returns The query's state, or `undefined` if no query with this key exists. + * @example + * ```ts + * const state = queryClient.getQueryState(['posts']) + * console.log(state?.dataUpdatedAt) + * ``` + */ + getQueryState< + TQueryFnData = unknown, + TError = DefaultError, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, + TInferredError = InferErrorFromTag, + >( + queryKey: TTaggedQueryKey, + ): QueryState | undefined { + const options = this.defaultQueryOptions({ queryKey }) + return this.#queryCache.get( + options.queryHash, + )?.state + } + + /** + * Removes queries from the cache that match the given filters. Unlike + * {@link QueryClient#invalidateQueries} or {@link QueryClient#refetchQueries}, this removes + * matching queries from the cache instead of refetching them. Without filters, every query in + * the cache is removed. + * @param filters - The filters that select which queries to remove. Without filters, every query + * is removed. + * @example + * ```ts + * queryClient.removeQueries({ queryKey: ['posts'], exact: true }) + * ``` + */ + removeQueries( + filters?: QueryFilters, + ): void { + const queryCache = this.#queryCache + notifyManager.batch(() => { + queryCache.findAll(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 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 queryClient.resetQueries({ queryKey: ['posts'], exact: true }) + * ``` + */ + resetQueries( + filters?: QueryFilters, + options?: ResetOptions, + ): Promise { + const queryCache = this.#queryCache + + return notifyManager.batch(() => { + const matched = queryCache.findAll(filters) + const queriesToRefetch = new Set(matched) + matched.forEach((query) => { + query.reset() + }) + return this.refetchQueries( + { + 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 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 queryClient.cancelQueries({ queryKey: ['posts'], exact: true }) + * ``` + */ + cancelQueries( + filters?: QueryFilters, + cancelOptions: CancelOptions = {}, + ): Promise { + const defaultedCancelOptions = { revert: true, ...cancelOptions } + + const promises = notifyManager.batch(() => + this.#queryCache + .findAll(filters) + .map((query) => query.cancel(defaultedCancelOptions)), + ) + + return Promise.all(promises).then(noop, noop) + } + + /** + * Marks queries matching the given filters as invalidated. Unlike + * {@link QueryClient#removeQueries}, invalidated queries stay in the cache. + * + * Unless `filters.refetchType` is `'none'`, matching queries are then refetched via + * {@link QueryClient#refetchQueries}, using `filters.refetchType` if set, otherwise + * `filters.type`, otherwise `'active'`. + * @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 QueryClient#refetchQueries}, e.g. `cancelRefetch` and + * `throwOnError`. + * @returns A promise that resolves once the refetch settles, or immediately if `refetchType` is + * `'none'`. + * @example + * ```ts + * await queryClient.invalidateQueries({ queryKey: ['posts'], refetchType: 'active' }) + * ``` + */ + invalidateQueries( + filters?: InvalidateQueryFilters, + options: InvalidateOptions = {}, + ): Promise { + return notifyManager.batch(() => { + this.#queryCache.findAll(filters).forEach((query) => { + query.invalidate() + }) + + if (filters?.refetchType === 'none') { + return Promise.resolve() + } + return this.refetchQueries( + { + ...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 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 queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' }) + * ``` + */ + refetchQueries( + filters?: RefetchQueryFilters, + options: RefetchOptions = {}, + ): Promise { + const fetchOptions = { + ...options, + cancelRefetch: options.cancelRefetch ?? true, + } + const promises = notifyManager.batch(() => + this.#queryCache + .findAll(filters) + .filter((query) => !query.isDisabled() && !query.isStatic()) + .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) + } + + /** + * Asynchronous method to fetch and cache a query, resolving with the data or throwing with + * the error. + * + * If the query already exists in the cache and its data is not stale (per the given + * `staleTime`), the cached data is returned without fetching. Otherwise, the query is fetched + * and the promise resolves once the fetch settles. If a `select` function is provided, it is + * applied to the data in both cases (cached or freshly fetched) before it is returned. + * + * Unlike a reactive observer, retries are disabled by default here (`retry: false`) unless + * explicitly configured, since there is no component to catch a thrown error and retry through + * re-render. + * + * The accepted options are `QueryObserverOptions` minus the fields that only make sense for a + * reactive observer — `enabled`, `refetchInterval`, `refetchIntervalInBackground`, + * `refetchOnWindowFocus`, `refetchOnReconnect`, `refetchOnMount`, `retryOnMount`, + * `notifyOnChangeProps`, `throwOnError`, `suspense`, and `placeholderData` are not part of this + * method's options. + * Shared query options can contain `skipToken` as their `queryFn`. If the supplied options contain + * the token, the call skips fetching and resolves with existing data regardless of freshness. + * It applies `select` when data exists and resolves to `undefined` on a cache miss. + * Use {@link QueryClient#getQueryData} to read the cache directly. + * @param options - The query options, including the `queryKey` and the `queryFn` used if the + * query needs to fetch. + * @returns A promise that resolves to the data, 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 queryClient.query({ queryKey, queryFn, staleTime: 10000 }) + * } catch (error) { + * console.log(error) + * } + * ``` + */ + query< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, + >( + options: WithoutSkipToken< + QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > + >, + ): Promise + query< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, + >( + options: QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + ): Promise + async query< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, + >( + options: QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + ): Promise { + const defaultedOptions = this.defaultQueryOptions(options) + let queryData: TQueryData + + if (options.queryFn === skipToken) { + const cachedData = this.#queryCache.get< + TQueryFnData, + TError, + TQueryData, + TQueryKey + >(defaultedOptions.queryHash)?.state.data + if (cachedData === undefined) return undefined + queryData = cachedData + } else { + // https://github.com/tannerlinsley/react-query/issues/652 + if (defaultedOptions.retry === undefined) { + defaultedOptions.retry = false + } + + const query = this.#queryCache.build(this, defaultedOptions) + + const isStale = query.isStaleByTime( + resolveQueryValue(defaultedOptions.staleTime, query), + ) + + queryData = isStale + ? await query.fetch(defaultedOptions) + : (query.state.data as TQueryData) + } + + const select = defaultedOptions.select + + if (select) { + return select(queryData) + } + + return queryData as unknown as TData + } + + /** + * 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 QueryClient#getQueryData} + * to read the cache directly. + * @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 queryClient.infiniteQuery({ + * queryKey, + * queryFn, + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextCursor, + * }) + * console.log(data.pages) + * } catch (error) { + * console.log(error) + * } + * ``` + */ + infiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: WithoutSkipToken< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + >, + ): Promise< + Array extends Array> + ? InfiniteData + : TData + > + infiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): Promise< + | undefined + | (Array extends Array> + ? InfiniteData + : TData) + > + infiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): Promise< + | undefined + | (Array extends Array> + ? InfiniteData + : TData) + > { + return this.query({ ...options, _type: 'infinite' } as any) + } + + /** + * Resumes mutations that were paused because there was no network connection. Does nothing + * (resolving immediately) if the client is currently offline. + * @returns A promise that resolves once the resumed mutations have settled. + * @example + * ```ts + * import { QueryClient } from '@tanstack/react-query-no-core' + * + * const queryClient = new QueryClient() + * await queryClient.resumePausedMutations() + * ``` + */ + resumePausedMutations(): Promise { + if (onlineManager.isOnline()) { + return this.#mutationCache.resumePausedMutations() + } + return Promise.resolve() + } + + /** + * Returns the query cache this client is connected to. + * @returns The {@link QueryCache} instance. + * @example + * ```ts + * import { QueryClient } from '@tanstack/react-query-no-core' + * + * const queryClient = new QueryClient() + * const queryCache = queryClient.getQueryCache() + * const queries = queryCache.findAll({ queryKey: ['posts'] }) + * ``` + */ + getQueryCache(): QueryCache { + return this.#queryCache + } + + /** + * Returns the mutation cache this client is connected to. + * @returns The {@link MutationCache} instance. + * @example + * ```ts + * import { QueryClient } from '@tanstack/react-query-no-core' + * + * const queryClient = new QueryClient() + * const mutationCache = queryClient.getMutationCache() + * const mutations = mutationCache.findAll({ status: 'pending' }) + * ``` + */ + getMutationCache(): MutationCache { + return this.#mutationCache + } + + /** + * Returns the default options that were set when creating the client, or via + * {@link QueryClient#setDefaultOptions}. + * @returns The client's current default options. + * @example + * ```ts + * import { QueryClient } from '@tanstack/react-query-no-core' + * + * const queryClient = new QueryClient() + * const defaultOptions = queryClient.getDefaultOptions() + * ``` + */ + getDefaultOptions(): DefaultOptions { + return this.#defaultOptions + } + + /** + * Dynamically sets the default options for this client, overwriting any previously defined + * default options. + * @param options - The new default options for queries and mutations. + * @see {@link QueryClient#getDefaultOptions} + * @example + * ```ts + * import { QueryClient } from '@tanstack/react-query-no-core' + * + * const queryClient = new QueryClient() + * queryClient.setDefaultOptions({ + * queries: { + * staleTime: Infinity, + * }, + * }) + * ``` + */ + setDefaultOptions(options: DefaultOptions): void { + this.#defaultOptions = options + } + + /** + * Sets default options for queries whose query key partially matches the given `queryKey`. + * + * If several registered query defaults match a given query key, they are merged together in + * registration order by {@link QueryClient#getQueryDefaults}, so register defaults from the + * most generic key to the least generic one — more specific defaults should be registered + * after more generic ones so they take precedence. + * @param queryKey - The query key that query keys are partially matched against. + * @param options - The default options applied to matching queries. + * @example + * ```ts + * queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts }) + * + * await queryClient.query({ queryKey: ['posts'] }) + * ``` + */ + setQueryDefaults< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + >( + queryKey: QueryKey, + options: Partial< + OmitKeyof< + QueryObserverOptionsBase, + 'queryKey' + > + >, + ): void { + this.#queryDefaults.set(queryKey, options, this.#queryCache.config.queryKey) + } + + /** + * Returns the default options registered for queries whose query key partially matches the + * given `queryKey`, via {@link QueryClient#setQueryDefaults}. If multiple registered defaults + * match, they are merged together in registration order. + * @param queryKey - The query key to look up registered defaults for. + * @returns The merged default options of every registration that matches, or an empty object if + * none match. + * @example + * ```ts + * const defaultOptions = queryClient.getQueryDefaults(['posts']) + * ``` + */ + getQueryDefaults( + queryKey: QueryKey, + ): OmitKeyof, 'queryKey'> { + return this.#queryDefaults.get(queryKey, this.#queryCache.config.queryKey) + } + + /** + * Sets default options for mutations whose mutation key partially matches the given + * `mutationKey`. As with {@link QueryClient#setQueryDefaults}, the order of registration + * matters when several registered defaults match the same mutation key. + * @param mutationKey - The mutation key that mutation keys are partially matched against. + * @param options - The default options applied to matching mutations. + * @see {@link QueryClient#getMutationDefaults} + * @example + * ```ts + * queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost }) + * ``` + */ + setMutationDefaults< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, + >( + mutationKey: MutationKey, + options: OmitKeyof< + MutationObserverOptions, + 'mutationKey' + >, + ): void { + this.#mutationDefaults.set( + mutationKey, + options, + this.#mutationCache.config.mutationKey, + ) + } + + /** + * Returns the default options registered for mutations whose mutation key partially matches + * the given `mutationKey`, via {@link QueryClient#setMutationDefaults}. If multiple registered + * defaults match, they are merged together in registration order. + * @param mutationKey - The mutation key to look up registered defaults for. + * @returns The merged default options of every registration that matches, or an empty object if + * none match. + * @example + * ```ts + * const defaultOptions = queryClient.getMutationDefaults(['addPost']) + * ``` + */ + getMutationDefaults( + mutationKey: MutationKey, + ): OmitKeyof, 'mutationKey'> { + return this.#mutationDefaults.get( + mutationKey, + this.#mutationCache.config.mutationKey, + ) + } + + /** + * Called by framework adapters (e.g. inside `useQuery`) to resolve the options passed by the + * caller into their final, defaulted form: merging the client's own `defaultOptions.queries`, + * then `queryClient.setQueryDefaults` for the given `queryKey`, then the caller's options on + * top. A no-op if the options are already defaulted (`_defaulted: true`). + * @param options - The query options passed by the caller. + * @returns The defaulted options, with `queryHash` and dependent defaults (e.g. + * `refetchOnReconnect`) filled in. + */ + defaultQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, + >( + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + ): DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > { + if (options._defaulted) { + return options as DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > + } + + const queryDefaults = this.getQueryDefaults(options.queryKey) + const defaultedOptions = { + ...this.#defaultOptions.queries, + ...queryDefaults, + ...options, + _defaulted: true, + } + + if (defaultedOptions.queryFn === defaultQueryFn) { + defaultedOptions.queryFn = + 'queryFn' in queryDefaults + ? queryDefaults.queryFn + : this.#defaultOptions.queries?.queryFn + } + + if (!defaultedOptions.queryHash) { + defaultedOptions.queryHash = hashKeyByOptions( + defaultedOptions.queryKey, + this.#queryCache.config.queryKey, + ) + } + + // dependent default values + if (defaultedOptions.refetchOnReconnect === undefined) { + defaultedOptions.refetchOnReconnect = + defaultedOptions.networkMode !== 'always' + } + if (defaultedOptions.throwOnError === undefined) { + defaultedOptions.throwOnError = !!defaultedOptions.suspense + } + + if (!defaultedOptions.networkMode && defaultedOptions.persister) { + defaultedOptions.networkMode = 'offlineFirst' + } + + if (defaultedOptions.queryFn === skipToken) { + defaultedOptions.enabled = false + } + + return defaultedOptions as DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > + } + + /** + * The mutation counterpart of {@link QueryClient#defaultQueryOptions}. Called by framework + * adapters (e.g. inside `useMutation`) to merge the client's `defaultOptions.mutations`, then + * `queryClient.setMutationDefaults` for the given `mutationKey`, then the caller's options on + * top. A no-op if the options are already defaulted (`_defaulted: true`). + * @param options - The mutation options passed by the caller. + * @returns The defaulted options. + */ + defaultMutationOptions>( + options?: T, + ): T { + if (options?._defaulted) { + return options + } + return { + ...this.#defaultOptions.mutations, + ...(options?.mutationKey && + this.getMutationDefaults(options.mutationKey)), + ...options, + _defaulted: true, + } as T + } + + /** + * Clears both the query cache and the mutation cache this client is connected to. + * This clears their garbage collection timers and cancels in-flight query fetches. + * Running mutations continue to execute. + * @example + * ```ts + * import { QueryClient } from '@tanstack/react-query-no-core' + * + * const queryClient = new QueryClient() + * queryClient.clear() + * ``` + */ + clear(): void { + this.#queryCache.clear() + this.#mutationCache.clear() + } +} diff --git a/packages/react-query-no-core/src/runtime/queryObserver.ts b/packages/react-query-no-core/src/runtime/queryObserver.ts new file mode 100644 index 00000000000..0f3861f4112 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/queryObserver.ts @@ -0,0 +1,1034 @@ +import { isServer as isServerEnvironment } from './environmentManager' +import { focusManager } from './focusManager' +import { notifyManager } from './notifyManager' +import { fetchState } from './query' +import { Subscribable } from './subscribable' +import { timeoutManager } from './timeoutManager' +import { + isValidTimeout, + noop, + replaceData, + resolveQueryValue, + shallowEqualObjects, + timeUntilStale, +} from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + ObserverFetchOptions, + ProjectionFailure, + QueryObserverListener, + QueryObserverResultReader, +} from '@tanstack/query-types/bindings' +import type { Query, QueryState } from './query' +import type { QueryClient } from './queryClient' +import type { QueryRuntime } from './runtimeBinding' +import type { ManagedTimerId } from './timeoutManager' +import type { + DefaultError, + DefaultedQueryObserverOptions, + PlaceholderDataFunction, + QueryKey, + QueryObserverBaseResult, + QueryObserverOptionsBase, + QueryObserverResult, + RefetchOptions, +} from './types' + +export type QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +> = Shared.QueryObserverResultContext< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +> + +export type ObserverOptionsInput< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = Shared.ObserverOptionsInput< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +> + +/** + * A `QueryObserver` watches a single query in the `QueryCache` and computes a + * `QueryObserverResult` from its state, recomputing and notifying subscribers + * whenever the underlying query (or the observer's options) changes. It is + * the primitive that framework adapters (e.g. `useQuery`) build their hooks + * on top of, but it can also be used directly to observe and switch between + * queries outside of any framework. + * @example + * ```ts + * const observer = new QueryObserver(queryClient, { + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * const unsubscribe = observer.subscribe((result) => { + * console.log(result.data) + * }) + * ``` + */ +export class QueryObserver< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends Subscribable> { + #client: QueryClient + #currentQuery: Query = undefined! + #currentQueryInitialState: QueryState = undefined! + #currentResult: QueryObserverResult = undefined! + #resultContext: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + > = {} + // This property keeps track of the last query with defined data. + // It will be used to pass the previous data and query to the placeholder function between renders. + #lastQueryWithDefinedData?: Query + #staleTimeoutId?: ManagedTimerId + #refetchIntervalId?: ManagedTimerId + #currentRefetchInterval?: number | false + #trackedProps = new Set() + + constructor( + client: QueryClient, + public options: ObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ) { + super() + + this.#client = client + + this.bindMethods() + this.setOptions(options) + } + + /** + * Binds the methods of the result (`refetch`) to the observer, so they keep working when destructured + * from it. Subclasses override it to bind their own result methods as well. + */ + protected bindMethods(): void { + this.refetch = this.refetch.bind(this) + } + + protected override onSubscribe(): void { + if (this.listeners.size === 1) { + this.#currentQuery.addObserver(this) + + if (shouldFetchOnMount(this.#currentQuery, this.options)) { + this.#executeFetch() + } else { + this.updateResult() + } + + this.#updateTimers() + } + } + + protected override onUnsubscribe(): void { + if (!this.hasListeners()) { + this.destroy() + } + } + + /** + * Returns whether the observed query is currently stale and configured + * (via the `refetchOnReconnect` option) to refetch when the network + * reconnects. + * @returns `true` if the observer should refetch the query on reconnect. + */ + shouldFetchOnReconnect(): boolean { + return shouldFetchOn( + this.#currentQuery, + this.options, + this.options.refetchOnReconnect, + ) + } + + /** + * Returns whether the observed query is currently stale and configured + * (via the `refetchOnWindowFocus` option) to refetch when the window + * regains focus. + * @returns `true` if the observer should refetch the query on window focus. + */ + shouldFetchOnWindowFocus(): boolean { + return shouldFetchOn( + this.#currentQuery, + this.options, + this.options.refetchOnWindowFocus, + ) + } + + /** + * Stops observing the current query: clears all listeners, cancels the + * stale and refetch-interval timers, and removes this observer from the + * query it was observing. + */ + destroy(): void { + this.listeners = new Set() + this.#clearStaleTimeout() + this.#clearRefetchInterval() + this.#currentQuery.removeObserver(this) + } + + /** + * Updates the observer's options. This will re-resolve the query being + * observed (switching to a different query if the `queryKey` changed), + * trigger a fetch if the new options require one and the observer has + * subscribers, recompute the current result, and reschedule the stale and + * refetch-interval timers as needed. + * @param options - The new observer options. They are defaulted with {@link + * QueryClient#defaultQueryOptions} before being applied. + * @throws {Error} If `enabled` is neither a boolean nor a function. + * @example + * ```ts + * observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) }) + * // later: switch to a different query, reusing the same observer + * observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) }) + * ``` + */ + setOptions( + options: ObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ): void { + const prevOptions = this.options + const prevQuery = this.#currentQuery + + this.options = this.#client.defaultQueryOptions(options) + + if ( + this.options.enabled !== undefined && + typeof this.options.enabled !== 'boolean' && + typeof this.options.enabled !== 'function' && + typeof resolveQueryValue(this.options.enabled, this.#currentQuery) !== + 'boolean' + ) { + throw new Error( + 'Expected enabled to be a boolean or a callback that returns a boolean', + ) + } + + this.#updateQuery() + this.#currentQuery.setOptions(this.options) + + if ( + prevOptions._defaulted && + !shallowEqualObjects(this.options, prevOptions) + ) { + this.#client.getQueryCache().notify({ + type: 'observerOptionsUpdated', + query: this.#currentQuery, + observer: this, + }) + } + + const mounted = this.hasListeners() + + // Fetch if there are subscribers + if ( + mounted && + shouldFetchOptionally( + this.#currentQuery, + prevQuery, + this.options, + prevOptions, + ) + ) { + this.#executeFetch() + } + + // Update result + this.updateResult() + + // Update stale interval if needed + if ( + mounted && + (this.#currentQuery !== prevQuery || + resolveQueryValue(this.options.enabled, this.#currentQuery) !== + resolveQueryValue(prevOptions.enabled, this.#currentQuery) || + resolveQueryValue(this.options.staleTime, this.#currentQuery) !== + resolveQueryValue(prevOptions.staleTime, this.#currentQuery)) + ) { + this.#updateStaleTimeout() + } + + const nextRefetchInterval = this.#computeRefetchInterval() + + // Update refetch interval if needed + if ( + mounted && + (this.#currentQuery !== prevQuery || + resolveQueryValue(this.options.enabled, this.#currentQuery) !== + resolveQueryValue(prevOptions.enabled, this.#currentQuery) || + nextRefetchInterval !== this.#currentRefetchInterval) + ) { + this.#updateRefetchInterval(nextRefetchInterval) + } + } + + /** + * Creates a result reader that captures the supplied query options. + * Reads cache the complete result locally and retain its reference while its + * fields are unchanged. They do not update this observer's committed result, + * options, or selection state. Missing queries are built in the query cache. + * Call `commit` after the render commits to apply the options and reuse the + * reader's computation. An abandoned reader needs no cleanup. + * @param options - The defaulted options used to read and commit the query result. + * @returns A reader with local snapshot and computation caches. + */ + createResultReader( + options: DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ): QueryObserverResultReader> { + const readerOptions = { ...options } + const { select, structuralSharing } = readerOptions + const context = { ...this.#resultContext } + let result = this.#currentResult + + const getSnapshot = () => { + const query = this.#client + .getQueryCache() + .build(this.#client, readerOptions) + const { selection, selected } = this.#resultContext + const input = query.state.data + + // A query update may already have selected this data. + if ( + input !== undefined && + select && + shallowEqualObjects( + { input, select, structuralSharing }, + selection?.key, + ) + ) { + context.selection = selection + context.selected = selected + } + + const nextResult = this.createResult( + query, + readerOptions, + context, + result, + ) + if (!shallowEqualObjects(nextResult, result)) { + result = nextResult + } + return result + } + + return { + getSnapshot, + commit: () => { + // Reuse selections computed since the last read. + getSnapshot() + this.#resultContext = { ...context } + this.setOptions(readerOptions) + }, + } + } + + /** + * Returns the most recently computed `QueryObserverResult` for the + * observed query. This is a point-in-time read; to be notified of updates + * as they happen, subscribe to the observer instead (its inherited + * `subscribe` method). + * @returns The observer's latest result. + * @example + * ```ts + * const result = observer.getCurrentResult() + * console.log(result.status, result.data) + * ``` + */ + getCurrentResult(): QueryObserverResult { + return this.#currentResult + } + + /** + * Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via + * {@link QueryObserver#trackProp} (and an optional `onPropTracked` callback). Used by framework + * adapters when `notifyOnChangeProps` is not set, to implement its default "only re-render on + * properties you actually read" behavior. + * @param result - The result to wrap. + * @param onPropTracked - Called with the name of each property that is read. + * @returns A proxy of `result` that tracks property reads. + */ + trackResult( + result: QueryObserverResult, + onPropTracked?: (key: keyof QueryObserverResult) => void, + ): QueryObserverResult { + return new Proxy(result, { + get: (target, key) => { + this.trackProp(key as keyof QueryObserverResult) + onPropTracked?.(key as keyof QueryObserverResult) + return Reflect.get(target, key) + }, + }) + } + + /** + * Records that the given `QueryObserverResult` property was read, so a subsequent update only + * notifies this observer if a tracked property actually changed. Normally called indirectly via + * {@link QueryObserver#trackResult}'s proxy; exposed directly for adapters that track property + * access themselves (e.g. through their own reactivity system) instead of via the proxy. + * @param key - The name of the property that was read. + */ + trackProp(key: keyof QueryObserverResult) { + this.#trackedProps.add(key) + } + + /** + * Returns the `Query` instance this observer is currently observing. + * @returns The observed query. + */ + getCurrentQuery(): Query { + return this.#currentQuery + } + + /** + * Refetches the observed query and returns a promise that resolves with + * the resulting `QueryObserverResult`. + * @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling + * it, and `throwOnError` to `true` to reject when the refetch fails. + * @returns A promise that resolves with the result after the refetch. + * @example + * ```ts + * const result = await observer.refetch({ cancelRefetch: false }) + * console.log(result.data) + * ``` + */ + refetch( + options: RefetchOptions = {}, + ): Promise> { + return this.fetch(options) + } + + /** + * 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 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 observer.fetchOptimistic({ + * queryKey: ['posts', 2], + * queryFn: () => fetchPost(2), + * }) + * console.log(result.data) + * ``` + */ + fetchOptimistic( + options: ObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + ): Promise> { + const defaultedOptions = this.#client.defaultQueryOptions(options) + + const query = this.#client + .getQueryCache() + .build(this.#client, defaultedOptions) + + const cached = Promise.withResolvers>() + const unsubscribe = this.#client.getQueryCache().subscribe((event) => { + if ( + event.type === 'updated' && + event.query.queryHash === query.queryHash && + query.state.data !== undefined + ) { + unsubscribe() + cached.resolve(this.createResult(query, defaultedOptions)) + } + }) + + return Promise.race([ + query + .fetch(defaultedOptions) + .then(() => { + const result = this.createResult(query, defaultedOptions) + // Resolve the cache wait when the fetch succeeds. + cached.resolve(result) + return result + }) + .finally(unsubscribe), + cached.promise, + ]) + } + + /** + * Fetches the observed query and updates the result once the fetch settles. Used by `refetch` and, + * in `InfiniteQueryObserver`, to fetch more pages. + * @param fetchOptions - Options for this fetch. `cancelRefetch` defaults to `true`. + * @returns A promise that resolves with the updated result. + */ + protected fetch( + fetchOptions: ObserverFetchOptions, + ): Promise> { + return this.#executeFetch({ + ...fetchOptions, + cancelRefetch: fetchOptions.cancelRefetch ?? true, + }).then(() => { + this.updateResult() + return this.#currentResult + }) + } + + #executeFetch( + fetchOptions?: Omit, + ): Promise { + // Make sure we reference the latest query as the current one might have been removed + this.#updateQuery() + + // Fetch + let promise: Promise = this.#currentQuery.fetch( + this.options, + fetchOptions, + ) + + if (!fetchOptions?.throwOnError) { + promise = promise.catch(noop) + } + + return promise + } + + #shouldScheduleTimer(timeout: unknown): timeout is number { + return ( + !isServerEnvironment() && + resolveQueryValue(this.options.enabled, this.#currentQuery) !== false && + isValidTimeout(timeout) + ) + } + + #updateStaleTimeout(): void { + this.#clearStaleTimeout() + const staleTime = resolveQueryValue( + this.options.staleTime, + this.#currentQuery, + ) + + if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) { + return + } + + const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime) + + // The timeout is sometimes triggered 1 ms before the stale time expiration. + // To mitigate this issue we always add 1 ms to the timeout. + const timeout = time + 1 + + this.#staleTimeoutId = timeoutManager.setTimeout(() => { + if (!this.#currentResult.isStale) { + this.updateResult() + } + }, timeout) + } + + #computeRefetchInterval() { + return ( + resolveQueryValue(this.options.refetchInterval, this.#currentQuery) ?? + false + ) + } + + #updateRefetchInterval(nextInterval: number | false): void { + this.#clearRefetchInterval() + + this.#currentRefetchInterval = nextInterval + + if ( + this.#currentRefetchInterval === 0 || + !this.#shouldScheduleTimer(this.#currentRefetchInterval) + ) { + return + } + + this.#refetchIntervalId = timeoutManager.setInterval(() => { + if ( + this.options.refetchIntervalInBackground || + focusManager.isFocused() + ) { + this.#executeFetch() + } + }, this.#currentRefetchInterval) + } + + #updateTimers(): void { + this.#updateStaleTimeout() + this.#updateRefetchInterval(this.#computeRefetchInterval()) + } + + #clearStaleTimeout(): void { + if (this.#staleTimeoutId !== undefined) { + timeoutManager.clearTimeout(this.#staleTimeoutId) + this.#staleTimeoutId = undefined + } + } + + #clearRefetchInterval(): void { + if (this.#refetchIntervalId !== undefined) { + timeoutManager.clearInterval(this.#refetchIntervalId) + this.#refetchIntervalId = undefined + } + } + + #resolvePlaceholder( + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + previousResultData: TData | undefined, + context = this.#resultContext, + ) { + const { placeholderData, structuralSharing } = options + const memo = context.placeholder + const previousQuery = this.#lastQueryWithDefinedData + const previousState = previousQuery?.state + const key = { + placeholderData, + structuralSharing, + previousQuery, + previousState, + previousOptions: previousQuery?.options, + } + if (shallowEqualObjects(key, memo?.key)) { + return memo + } + + let failure: ProjectionFailure | undefined + let input: TQueryData | undefined + let sourceQuery: typeof previousQuery + if (typeof placeholderData === 'function') { + try { + input = ( + placeholderData as unknown as PlaceholderDataFunction< + TQueryFnData, + TError, + TQueryData, + TQueryKey + > + )(previousState?.data, previousQuery) + } catch (error) { + failure = { error: error as TError, errorUpdatedAt: Date.now() } + } + if (previousState?.data !== undefined) { + sourceQuery = previousQuery + } + } else { + input = placeholderData + } + + if (input !== undefined) { + input = replaceData( + previousResultData, + input as unknown, + options, + ) as TQueryData + } + return input !== undefined || failure + ? { key, input, sourceQuery, failure } + : undefined + } + + /** + * Computes the result for a query and options from the query's state, applying `select`, + * `placeholderData`, and the derived flags. Subclasses override it to add their own fields. + * @param query - The query to compute the result for. + * @param options - The observer options to compute the result with. + * @param context - The selection and placeholder state reused between computations. + * @param prevResult - The previous result used for structural sharing. + * @returns The computed result. + */ + protected createResult( + query: Query, + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + context = this.#resultContext, + prevResult = this.#currentResult as + | QueryObserverResult + | undefined, + ): QueryObserverResult { + const prevQuery = this.#currentQuery + const prevOptions = this.options + const queryChange = query !== prevQuery + const queryInitialState = queryChange + ? query.state + : this.#currentQueryInitialState + + const { state } = query + const fetchOptimistically = + options._optimisticResults && + (this.hasListeners() + ? shouldFetchOptionally(query, prevQuery, options, prevOptions) + : shouldFetchOnMount(query, options)) + const newState = fetchOptimistically + ? { ...state, ...fetchState(state.data, query.options) } + : state + const fetchStatus = + options._optimisticResults === 'isRestoring' + ? 'idle' + : newState.fetchStatus + const selectedQuery = context.selected?.query + if (selectedQuery && selectedQuery.state.data === undefined) { + context.selected = undefined + // Keep a cached error stable, but a successful selection needs its data. + if (!context.selection?.failure) { + context.selection = undefined + } + } + + const { placeholderData, select, structuralSharing } = options + if ( + newState.data === undefined && + newState.status === 'pending' && + placeholderData !== undefined + ) { + context.placeholder = this.#resolvePlaceholder( + options, + prevResult?.data, + context, + ) + } else { + context.placeholder = undefined + } + + const placeholder = context.placeholder + const input = placeholder ? placeholder.input : newState.data + if (!select || input === undefined) { + context.selection = undefined + } else { + const key = { input, select, structuralSharing } + if (!shallowEqualObjects(key, context.selection?.key)) { + try { + const data = replaceData(prevResult?.data, select(input), options) + context.selected = { + data, + query: placeholder ? placeholder.sourceQuery : query, + } + context.selection = { key } + } catch (error) { + context.selection = { + key, + failure: { + error: error as TError, + errorUpdatedAt: Date.now(), + }, + } + } + } + } + + const failure = placeholder?.failure ?? context.selection?.failure + const data = context.selection + ? context.selected?.data + : (input as unknown as TData | undefined) + const isPlaceholderData = + placeholder !== undefined && input !== undefined && !failure + const { error, errorUpdatedAt } = failure ?? newState + const status = failure + ? 'error' + : isPlaceholderData + ? 'success' + : newState.status + const isFetching = fetchStatus === 'fetching' + const isPending = status === 'pending' + const isError = status === 'error' + + const isLoading = isPending && isFetching + const hasData = data !== undefined + + const result: QueryObserverBaseResult = { + status, + fetchStatus, + isPending, + isSuccess: status === 'success', + isError, + isLoading, + data, + dataUpdatedAt: newState.dataUpdatedAt, + error, + errorUpdatedAt, + failureCount: newState.fetchFailureCount, + failureReason: newState.fetchFailureReason, + errorUpdateCount: newState.errorUpdateCount, + isFetched: query.isFetched(), + isFetchedAfterMount: + newState.dataUpdateCount > queryInitialState.dataUpdateCount || + newState.errorUpdateCount > queryInitialState.errorUpdateCount, + isFetching, + isRefetching: isFetching && !isPending, + isLoadingError: isError && !hasData, + isPaused: fetchStatus === 'paused', + isPlaceholderData, + isRefetchError: isError && hasData, + isStale: isStale(query, options), + refetch: this.refetch, + isEnabled: resolveQueryValue(options.enabled, query) !== false, + } + + const nextResult = result as QueryObserverResult + + return nextResult + } + + /** + * Recomputes and stores the current result from the current query/options, notifying listeners + * if it changed. Framework adapters call this right after subscribing to make sure no query + * update was missed in the gap between creating the observer and subscribing to it. + */ + updateResult(): void { + const prevResult = this.#currentResult as + | QueryObserverResult + | undefined + + const nextResult = this.createResult(this.#currentQuery, this.options) + + if (this.#currentQuery.state.data !== undefined) { + this.#lastQueryWithDefinedData = this.#currentQuery + } + + // Only notify and update result if something has changed + if (shallowEqualObjects(nextResult, prevResult)) { + return + } + + this.#currentResult = nextResult + + const shouldNotifyListeners = (): boolean => { + if (!prevResult) { + return true + } + + const { notifyOnChangeProps } = this.options + + if ( + notifyOnChangeProps === 'all' || + (notifyOnChangeProps !== 'none' && !this.#trackedProps.size) + ) { + return true + } + + if ( + this.options.throwOnError && + this.#currentResult.error !== prevResult.error + ) { + return true + } + + if (notifyOnChangeProps === 'none') { + return false + } + + for (const key of this.#trackedProps) { + if (this.#currentResult[key] !== prevResult[key]) { + return true + } + } + return false + } + + const notifyListeners = shouldNotifyListeners() + + notifyManager.batch(() => { + // First, trigger the listeners + if (notifyListeners) { + this.listeners.forEach((listener) => { + listener(this.#currentResult) + }) + } + + // Then the cache listeners + this.#client.getQueryCache().notify({ + query: this.#currentQuery, + type: 'observerResultsUpdated', + }) + }) + } + + #updateQuery(): void { + const query = this.#client.getQueryCache().build(this.#client, this.options) + + if (query === this.#currentQuery) { + return + } + + const prevQuery = this.#currentQuery as + | Query + | undefined + this.#currentQuery = query + this.#currentQueryInitialState = query.state + + if (this.hasListeners()) { + prevQuery?.removeObserver(this) + query.addObserver(this) + } + } + + /** + * Updates the observer's result when the observed query changes, and reschedules its timers if it + * has listeners. + * @internal + */ + onQueryUpdate(): void { + this.updateResult() + + if (this.hasListeners()) { + this.#updateTimers() + } + } +} + +/** + * Checks whether a query has no data yet and should do its initial load when an observer mounts. + * @param query - The query to check. + * @param options - The observer options. + * @returns `true` if the query is enabled, has no data, and isn't in an error state with + * `retryOnMount: false`. + */ +function shouldLoadOnMount( + query: Query, + options: QueryObserverOptionsBase, +): boolean { + return ( + resolveQueryValue(options.enabled, query) !== false && + query.state.data === undefined && + !( + query.state.status === 'error' && + resolveQueryValue(options.retryOnMount, query) === false + ) + ) +} + +/** + * Checks whether a query should fetch when an observer mounts: either for its initial load, or + * because it has data and `refetchOnMount` asks for a refetch. + * @param query - The query to check. + * @param options - The observer options. + * @returns `true` if the query should fetch on mount. + */ +function shouldFetchOnMount( + query: Query, + options: QueryObserverOptionsBase, +): boolean { + return ( + shouldLoadOnMount(query, options) || + (query.state.data !== undefined && + shouldFetchOn(query, options, options.refetchOnMount)) + ) +} + +/** + * Checks whether a query should fetch for a `refetchOnMount`, `refetchOnWindowFocus`, or + * `refetchOnReconnect` option. + * @param query - The query to check. + * @param options - The observer options. + * @param field - The value of the option to check. + * @returns `true` if the query is enabled, not static, and the option is `'always'`, or is not + * `false` and the query is stale. + */ +function shouldFetchOn( + query: Query, + options: QueryObserverOptionsBase, + field: (typeof options)['refetchOnMount'] & + (typeof options)['refetchOnWindowFocus'] & + (typeof options)['refetchOnReconnect'], +) { + if ( + resolveQueryValue(options.enabled, query) !== false && + resolveQueryValue(options.staleTime, query) !== 'static' + ) { + const value = resolveQueryValue(field, query) + + return value === 'always' || (value !== false && isStale(query, options)) + } + return false +} + +/** + * Checks whether a query should fetch after the observer's options change. + * @param query - The query observed with the new options. + * @param prevQuery - The query observed with the previous options. + * @param options - The new observer options. + * @param prevOptions - The previous observer options. + * @returns `true` if the query changed or was disabled before, it isn't a suspense query in an + * error state, and it is stale. + */ +function shouldFetchOptionally( + query: Query, + prevQuery: Query, + options: QueryObserverOptionsBase, + prevOptions: QueryObserverOptionsBase, +): boolean { + return ( + (query !== prevQuery || + resolveQueryValue(prevOptions.enabled, query) === false) && + (!options.suspense || query.state.status !== 'error') && + isStale(query, options) + ) +} + +/** + * Checks whether a query is stale for the given observer options. + * @param query - The query to check. + * @param options - The observer options, whose `enabled` and `staleTime` are used. + * @returns `true` if the query is enabled and its data is stale for `staleTime`. + */ +function isStale( + query: Query, + options: QueryObserverOptionsBase, +): boolean { + return ( + resolveQueryValue(options.enabled, query) !== false && + query.isStaleByTime(resolveQueryValue(options.staleTime, query)) + ) +} + +export type { QueryObserverResultReader } from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/removable.ts b/packages/react-query-no-core/src/runtime/removable.ts new file mode 100644 index 00000000000..d6356c73845 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/removable.ts @@ -0,0 +1,65 @@ +import { isServer as isServerEnvironment } from './environmentManager' +import { timeoutManager } from './timeoutManager' +import { isValidTimeout } from './utils' +import type { ManagedTimerId } from './timeoutManager' + +/** + * The base class for cache entries that are garbage collected once nothing is using them — + * `Query` and `Mutation` both extend it. `gcTime` controls how long an unused entry is kept. + */ +export abstract class Removable { + gcTime!: number + #gcTimeout?: ManagedTimerId + + /** + * Clears the pending garbage collection timeout, so the entry is no longer scheduled for removal. + * A subclass may override this to release what it holds on to as well — `Query` also cancels any + * in-flight fetch. + */ + destroy(): void { + this.clearGcTimeout() + } + + /** + * Schedules the entry to be removed from its cache after `gcTime`, replacing any timeout scheduled + * before. Nothing is scheduled if `gcTime` is `Infinity`. + */ + protected scheduleGc(): void { + this.clearGcTimeout() + + if (isValidTimeout(this.gcTime)) { + this.#gcTimeout = timeoutManager.setTimeout(() => { + this.optionalRemove() + }, this.gcTime) + } + } + + /** + * Updates `gcTime`, keeping the longest one seen so far. Without a value, it defaults to 5 minutes + * on the client and `Infinity` on the server. + * @param newGcTime - The `gcTime` from the latest options, if any. + */ + protected updateGcTime(newGcTime: number | undefined): void { + // Default to 5 minutes (Infinity for server-side) if no gcTime is set + this.gcTime = Math.max( + this.gcTime || 0, + newGcTime ?? (isServerEnvironment() ? Infinity : 5 * 60 * 1000), + ) + } + + /** + * Cancels the scheduled removal, if there is one. + */ + protected clearGcTimeout() { + if (this.#gcTimeout !== undefined) { + timeoutManager.clearTimeout(this.#gcTimeout) + this.#gcTimeout = undefined + } + } + + /** + * Called when the garbage collection timeout fires. Subclasses remove the entry from its cache + * unless it is still in use, e.g. because it has observers. + */ + protected abstract optionalRemove(): void +} diff --git a/packages/react-query-no-core/src/runtime/retryer.ts b/packages/react-query-no-core/src/runtime/retryer.ts new file mode 100644 index 00000000000..5ac6a5eece1 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/retryer.ts @@ -0,0 +1,241 @@ +import { isServer as isServerEnvironment } from './environmentManager' +import { focusManager } from './focusManager' +import { onlineManager } from './onlineManager' +import { noop, sleep } from './utils' +import type { + Retryer, + RetryerConfig, + RetryerStatus, +} from '@tanstack/query-types/bindings' +import type { CancelOptions, DefaultError, NetworkMode } from './types' + +/** + * Applies exponential backoff with jitter. The base delay starts at 1 second + * and doubles for each retry, up to 30 seconds. + * @param failureCount - The number of previous failures. Starts at 0 for the first retry. + * @returns A random delay from 80% to 100% of the base delay, in milliseconds. + */ +function defaultRetryDelay(failureCount: number) { + const baseDelay = Math.min(1000 * 2 ** failureCount, 30000) + const maxJitter = baseDelay * 0.2 + return baseDelay - Math.floor(Math.random() * (maxJitter + 1)) +} + +/** + * Checks whether a fetch can run for the given network mode. + * @param networkMode - The `networkMode` option. Defaults to `'online'`. + * @returns `true` if the network mode is not `'online'`, or if it is and the client is online. + */ +export function canFetch(networkMode: NetworkMode | undefined): boolean { + return (networkMode ?? 'online') === 'online' + ? onlineManager.isOnline() + : true +} + +/** + * The error thrown by a `Retryer` (and surfaced to `query.promise`/`mutation`) when a fetch is cancelled, e.g. via + * `query.cancel()`. `revert`, if `true`, tells the caller to restore the state the query was in before the fetch + * started instead of surfacing the error. `silent`, if `true`, tells the caller to suppress this error and instead + * resolve with the promise of the fetch that triggered the cancellation. + * @example + * ```ts + * query.cancel() + * + * try { + * await query.promise + * } catch (error) { + * if (error instanceof CancelledError) { + * // the fetch was cancelled, e.g. via `query.cancel()` + * } + * } + * ``` + */ +export class CancelledError extends Error { + revert?: boolean + silent?: boolean + constructor(options?: CancelOptions) { + super('CancelledError') + this.revert = options?.revert + this.silent = options?.silent + } +} + +/** + * Creates a retryer, which runs a function and retries it on failure according to the `retry` and + * `retryDelay` options. It pauses while the network mode doesn't allow fetching or `canRun` returns + * `false`, and can be cancelled. Queries and mutations use it to run their `queryFn` and + * `mutationFn`. + * @param config - The function to run, the retry options, and the callbacks for failures, pausing, + * continuing, and cancellation. + * @returns The retryer, whose `promise` settles with the result of the function. + */ +export function createRetryer( + config: RetryerConfig, +): Retryer { + let isRetryCancelled = false + let failureCount = 0 + let continueFn: ((value?: unknown) => void) | undefined + let status: RetryerStatus = 'pending' + const { + promise, + resolve: promiseResolve, + reject: promiseReject, + } = Promise.withResolvers() + promise.catch(noop) + + const isResolved = () => status !== 'pending' + + const cancel = (cancelOptions?: CancelOptions): void => { + if (!isResolved()) { + const error = new CancelledError(cancelOptions) as TError + reject(error) + + config.onCancel?.(error) + } + } + const cancelRetry = () => { + isRetryCancelled = true + } + + const continueRetry = () => { + isRetryCancelled = false + } + + const canContinue = () => + focusManager.isFocused() && + (config.networkMode === 'always' || onlineManager.isOnline()) && + config.canRun() + + const canStart = () => canFetch(config.networkMode) && config.canRun() + + const resolve = (value: any) => { + if (!isResolved()) { + continueFn?.() + status = 'resolved' + promiseResolve(value) + } + } + + const reject = (value: any) => { + if (!isResolved()) { + continueFn?.() + status = 'rejected' + promiseReject(value) + } + } + + const pause = (canResume: () => boolean) => { + return new Promise((continueResolve) => { + continueFn = (value) => { + if (isResolved() || canResume()) { + continueResolve(value) + } + } + config.onPause?.() + }).then(() => { + continueFn = undefined + if (!isResolved()) { + config.onContinue?.() + } + }) + } + + // Create loop function + const run = () => { + // Do nothing if already resolved + if (isResolved()) { + return + } + + let promiseOrValue: any + + // we can re-use config.initialPromise on the first call of run() + const initialPromise = + failureCount === 0 ? config.initialPromise : undefined + + // Execute query + try { + promiseOrValue = initialPromise ?? config.fn() + } catch (error) { + promiseOrValue = Promise.reject(error) + } + + Promise.resolve(promiseOrValue) + .then(resolve) + .catch((error) => { + // Stop if the fetch is already resolved + if (isResolved()) { + return + } + + // Do we need to retry the request? + const retry = config.retry ?? (isServerEnvironment() ? 0 : 3) + const retryDelay = config.retryDelay ?? defaultRetryDelay + const delay = + typeof retryDelay === 'function' + ? retryDelay(failureCount, error) + : retryDelay + const shouldRetry = + retry === true || + (typeof retry === 'number' && failureCount < retry) || + (typeof retry === 'function' && retry(failureCount, error)) + + if (isRetryCancelled || !shouldRetry) { + // We are done if the query does not need to be retried + reject(error) + return + } + + failureCount++ + + // Notify on fail + config.onFail?.(failureCount, error) + + // Delay + sleep(delay) + // Pause if the document is not visible or when the device is offline + .then(() => { + return isResolved() || canContinue() + ? undefined + : pause(canContinue) + }) + .then(() => { + if (isRetryCancelled) { + reject(error) + } else { + run() + } + }) + }) + } + + return { + promise, + status: () => status, + cancel, + continue: () => { + continueFn?.() + return promise + }, + cancelRetry, + continueRetry, + canStart, + start: () => { + // Start loop + if (canStart()) { + run() + } else { + // Waiting to start (e.g. queued behind a scope) does not depend on focus, + // only on the same conditions that allow starting in the first place + pause(canStart).then(run) + } + return promise + }, + } +} + +export type { + Retryer, + RetryValue, + RetryDelayValue, +} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/runtimeBinding.ts b/packages/react-query-no-core/src/runtime/runtimeBinding.ts new file mode 100644 index 00000000000..26f50dded36 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/runtimeBinding.ts @@ -0,0 +1,49 @@ +import type { RuntimeBinding } from '@tanstack/query-types/bindings' +import type { Mutation } from './mutation' +import type { MutationCache } from './mutationCache' +import type { MutationObserver } from './mutationObserver' +import type { Query } from './query' +import type { QueryCache } from './queryCache' +import type { QueryClient } from './queryClient' +import type { QueryObserver } from './queryObserver' +import type { QueryKey } from './types' + +/** Binds shared option and callback types to the concrete classes in this runtime. */ +export interface QueryRuntime extends RuntimeBinding { + QueryClient: QueryClient + QueryCache: QueryCache + MutationCache: MutationCache + Query: this['args'] extends [ + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryKey extends QueryKey, + ] + ? Query + : never + Mutation: this['args'] extends [ + infer TData, + infer TError, + infer TVariables, + infer TOnMutateResult, + ] + ? Mutation + : never + QueryObserver: this['args'] extends [ + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryData, + infer TQueryKey extends QueryKey, + ] + ? QueryObserver + : never + MutationObserver: this['args'] extends [ + infer TData, + infer TError, + infer TVariables, + infer TOnMutateResult, + ] + ? MutationObserver + : never +} diff --git a/packages/react-query-no-core/src/runtime/streamedQuery.ts b/packages/react-query-no-core/src/runtime/streamedQuery.ts new file mode 100644 index 00000000000..6efb1dbfcdd --- /dev/null +++ b/packages/react-query-no-core/src/runtime/streamedQuery.ts @@ -0,0 +1,112 @@ +import { addConsumeAwareSignal, fetchSignal } from './utils' +import type * as Shared from '@tanstack/query-types/bindings' +import type { QueryRuntime } from './runtimeBinding' +import type { OmitKeyof, QueryFunction, QueryKey } from './types' +import type { FetchSignalContext } from './utils' + +type StreamedQueryParams< + TQueryFnData, + TData, + TQueryKey extends QueryKey, +> = Shared.StreamedQueryParams + +/** + * Creates a query function that streams data from an `AsyncIterable`. + * By default, the query collects chunks into an array in the order they arrive. + * If there is no cached data, the first chunk moves the query from `pending` to `success`. + * If the stream ends without producing any chunks, the query uses the cached data or + * the initial value. With a `'replace'` refetch, it uses the initial value. + * The query's `fetchStatus` stays `fetching` while the stream is active. + * Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`. + * If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes. + * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional + * `refetchMode`, `reducer`, and `initialValue` options. + * @returns A query function to pass as `queryFn`. + * @example + * ```ts + * await queryClient.query({ + * queryKey: ['data'], + * queryFn: streamedQuery({ + * streamFn: fetchDataInChunks, + * }), + * }) + * ``` + */ +export function streamedQuery< + TQueryFnData = unknown, + TData = Array, + TQueryKey extends QueryKey = QueryKey, +>({ + streamFn, + refetchMode = 'reset', + reducer = (items, chunk) => + [...(items as Array), chunk] as TData, + initialValue = [] as TData, +}: StreamedQueryParams): QueryFunction< + TData, + TQueryKey +> { + return async (context) => { + const signalContext: FetchSignalContext = context + const signal = signalContext[fetchSignal] + if (signal?.aborted) { + return initialValue + } + + const query = context.client + .getQueryCache() + .find({ queryKey: context.queryKey, exact: true }) + const isRefetch = !!query && query.isFetched() + if (isRefetch && refetchMode === 'reset') { + query.setState({ + ...query.resetState, + fetchStatus: 'fetching', + }) + } + + let result = initialValue + + let cancelled = false as boolean + const streamFnContext = addConsumeAwareSignal< + OmitKeyof + >( + { + client: context.client, + meta: context.meta, + queryKey: context.queryKey, + pageParam: context.pageParam, + }, + () => context.signal, + () => (cancelled = true), + signal, + ) + + const isStreamInactive = () => cancelled || signal?.aborted === true + const stream = await streamFn(streamFnContext) + + const isReplaceRefetch = isRefetch && refetchMode === 'replace' + + for await (const chunk of stream) { + if (isStreamInactive()) { + break + } + + if (isReplaceRefetch) { + // don't append to the cache directly when replace-refetching + result = reducer(result, chunk) + } else { + context.client.setQueryData(context.queryKey, (prev) => + reducer(prev === undefined ? initialValue : prev, chunk), + ) + } + } + + // finalize result: replace-refetching needs to write to the cache + if (isReplaceRefetch && !isStreamInactive()) { + context.client.setQueryData(context.queryKey, result) + } + + const data = context.client.getQueryData(context.queryKey) + return data === undefined ? initialValue : data + } +} diff --git a/packages/react-query-no-core/src/runtime/subscribable.ts b/packages/react-query-no-core/src/runtime/subscribable.ts new file mode 100644 index 00000000000..8b40e3ce868 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/subscribable.ts @@ -0,0 +1,65 @@ +/** + * The base class behind everything in Query that you can subscribe to: `QueryCache`, `MutationCache`, + * the observers, and the `FocusManager`/`OnlineManager` behind `focusManager` and `onlineManager`. + * Subclasses decide what a listener receives and when it is called. + */ +export class Subscribable< + // oxlint-disable-next-line typescript/no-unsafe-function-type -- also accepts construct signatures and functions with extra properties, which a call signature would reject + TListener extends Function, +> { + protected listeners = new Set() + + constructor() { + this.subscribe = this.subscribe.bind(this) + } + + /** + * Registers a listener to be called on every update this object notifies about. Returns a function + * that removes the listener again — call it to stop listening. The base class never drops a listener + * on its own, though some subclasses clear all of theirs in `destroy()`. + * @param listener - Called on each update, with whatever the subclass passes to its subscribers. + * @returns A function that removes the listener. + * @example + * ```ts + * const unsubscribe = subscribable.subscribe(() => { + * // react to the update + * }) + * + * unsubscribe() + * ``` + */ + subscribe(listener: TListener): () => void { + this.listeners.add(listener) + + this.onSubscribe() + + return () => { + this.listeners.delete(listener) + this.onUnsubscribe() + } + } + + /** + * Returns `true` while at least one listener is registered, `false` once they have all unsubscribed. + * @returns `true` if at least one listener is registered. + */ + hasListeners(): boolean { + return this.listeners.size > 0 + } + + /** + * Called after a listener is added. Does nothing here; subclasses override it, e.g. to start + * tracking what they observe once the first listener subscribes. + */ + protected onSubscribe(): void { + // Do nothing + } + + /** + * Called after a listener is removed. Does nothing here; subclasses override it, e.g. to clean up + * once the last listener unsubscribes. + */ + protected onUnsubscribe(): void { + // Do nothing + } +} diff --git a/packages/react-query-no-core/src/runtime/timeoutManager.ts b/packages/react-query-no-core/src/runtime/timeoutManager.ts new file mode 100644 index 00000000000..8788938f522 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/timeoutManager.ts @@ -0,0 +1,223 @@ +import type { + ManagedTimerId, + SystemTimerId, + TimeoutCallback, + TimeoutProvider, +} from '@tanstack/query-types/bindings' + +export const defaultTimeoutProvider: TimeoutProvider = { + // We need the wrapper function syntax below instead of direct references to + // global setTimeout etc. + // + // BAD: `setTimeout: setTimeout` + // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)` + // + // If we use direct references here, then anything that wants to spy on or + // replace the global setTimeout (like tests) won't work since we'll already + // have a hard reference to the original implementation at the time when this + // file was imported. + setTimeout: (callback, delay) => setTimeout(callback, delay), + clearTimeout: (timeoutId) => + clearTimeout(timeoutId as SystemTimerId | undefined), + + setInterval: (callback, delay) => setInterval(callback, delay), + clearInterval: (intervalId) => + clearInterval(intervalId as SystemTimerId | undefined), +} + +/** + * Allows customization of how timeouts are created. + * + * `@tanstack/react-query-no-core` makes liberal use of timeouts to implement `staleTime` + * and `gcTime`. The default TimeoutManager provider uses the platform's global + * `setTimeout` implementation, which is known to have scalability issues with + * thousands of timeouts on the event loop. + * + * If you hit this limitation, consider providing a custom TimeoutProvider that + * coalesces timeouts. + */ +export class TimeoutManager implements Omit { + // We cannot have TimeoutManager as we must instantiate it with a concrete + // type at app boot; and if we leave that type, then any new timer provider + // would need to support the default provider's concrete timer ID, which is + // infeasible across environments. + // + // We settle for type safety for the TimeoutProvider type, and accept that + // this class is unsafe internally to allow for extension. + #provider: TimeoutProvider = defaultTimeoutProvider + #providerCalled = false + + /** + * `setTimeoutProvider` can be used to set a custom implementation of the + * `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval` functions, + * called a `TimeoutProvider`. + * + * This may be useful if you notice event loop performance issues with + * thousands of queries. A custom TimeoutProvider could also support timer + * delays longer than the global `setTimeout` maximum delay value of about + * 24 days. + * + * It is important to call `setTimeoutProvider` before creating a + * QueryClient or queries, so that the same provider is used consistently + * for all timers in the application, since different TimeoutProviders + * cannot cancel each others' timers. + * @param provider - The `TimeoutProvider` to use for all timers from now on. + * @example + * ```ts + * import { timeoutManager, QueryClient } from '@tanstack/react-query-no-core' + * import { CustomTimeoutProvider } from './CustomTimeoutProvider' + * + * timeoutManager.setTimeoutProvider(new CustomTimeoutProvider()) + * + * export const queryClient = new QueryClient() + * ``` + */ + setTimeoutProvider( + provider: TimeoutProvider, + ): void { + if (process.env.NODE_ENV !== 'production') { + if (this.#providerCalled && provider !== this.#provider) { + // After changing providers, `clearTimeout` will not work as expected for + // timeouts from the previous provider. + // + // Since they may allocate the same timeout ID, clearTimeout may cancel an + // arbitrary different timeout, or unexpected no-op. + // + // We could protect against this by mixing the timeout ID bits + // deterministically with some per-provider bits. + // + // We could internally queue `setTimeout` calls to `TimeoutManager` until + // some API call to set the initial provider. + console.error( + `[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`, + { previous: this.#provider, provider }, + ) + } + } + + this.#provider = provider + if (process.env.NODE_ENV !== 'production') { + this.#providerCalled = false + } + } + + /** + * `setTimeout` schedules a callback to run after approximately `delay` + * milliseconds, like the global `setTimeout` function. The callback can be + * canceled with `clearTimeout`. + * + * It returns a timer ID, which may be a number or an object that can be + * coerced to a number via `Symbol.toPrimitive`. + * @param callback - The function to call when the timeout elapses. + * @param delay - The time to wait before calling `callback`, in milliseconds. + * @returns The timer ID, to pass to {@link TimeoutManager#clearTimeout}. + * @example + * ```ts + * import { timeoutManager } from '@tanstack/react-query-no-core' + * + * const timeoutId = timeoutManager.setTimeout( + * () => console.log('ran at:', new Date()), + * 1000, + * ) + * + * const timeoutIdNumber: number = Number(timeoutId) + * ``` + */ + setTimeout(callback: TimeoutCallback, delay: number): ManagedTimerId { + if (process.env.NODE_ENV !== 'production') { + this.#providerCalled = true + } + return this.#provider.setTimeout(callback, delay) + } + + /** + * `clearTimeout` cancels a timeout callback scheduled with `setTimeout`, + * like the global `clearTimeout` function. It should be called with a + * timer ID returned by `setTimeout`. + * @param timeoutId - The timer ID returned by `setTimeout`, or `undefined`. + * @example + * ```ts + * import { timeoutManager } from '@tanstack/react-query-no-core' + * + * const timeoutId = timeoutManager.setTimeout( + * () => console.log('ran at:', new Date()), + * 1000, + * ) + * + * timeoutManager.clearTimeout(timeoutId) + * ``` + */ + clearTimeout(timeoutId: ManagedTimerId | undefined): void { + this.#provider.clearTimeout(timeoutId) + } + + /** + * `setInterval` schedules a callback to be called approximately every + * `delay` milliseconds, like the global `setInterval` function. + * + * Like `setTimeout`, it returns a timer ID, which may be a number or an + * object that can be coerced to a number via `Symbol.toPrimitive`. + * @param callback - The function to call on every interval. + * @param delay - The time between calls, in milliseconds. + * @returns The timer ID, to pass to {@link TimeoutManager#clearInterval}. + * @example + * ```ts + * import { timeoutManager } from '@tanstack/react-query-no-core' + * + * const intervalId = timeoutManager.setInterval( + * () => console.log('ran at:', new Date()), + * 1000, + * ) + * ``` + */ + setInterval(callback: TimeoutCallback, delay: number): ManagedTimerId { + if (process.env.NODE_ENV !== 'production') { + this.#providerCalled = true + } + return this.#provider.setInterval(callback, delay) + } + + /** + * `clearInterval` can be used to cancel an interval, like the global + * `clearInterval` function. It should be called with an interval ID + * returned by `setInterval`. + * @param intervalId - The timer ID returned by `setInterval`, or `undefined`. + * @example + * ```ts + * import { timeoutManager } from '@tanstack/react-query-no-core' + * + * const intervalId = timeoutManager.setInterval( + * () => console.log('ran at:', new Date()), + * 1000, + * ) + * + * timeoutManager.clearInterval(intervalId) + * ``` + */ + clearInterval(intervalId: ManagedTimerId | undefined): void { + this.#provider.clearInterval(intervalId) + } +} + +/** + * Singleton instance of {@link TimeoutManager}, used throughout TanStack Query to schedule and cancel timers. + */ +export const timeoutManager = new TimeoutManager() + +/** + * In many cases code wants to delay to the next event loop tick; this is not + * mediated by {@link timeoutManager}. + * + * This function is provided to make auditing the `tanstack/query-core` for + * incorrect use of system `setTimeout` easier. + * @param callback - The function to call on the next event loop tick. + */ +export function systemSetTimeoutZero(callback: TimeoutCallback): void { + setTimeout(callback, 0) +} + +export type { + TimeoutCallback, + ManagedTimerId, + TimeoutProvider, +} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/types.ts b/packages/react-query-no-core/src/runtime/types.ts new file mode 100644 index 00000000000..67aa6619cf5 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/types.ts @@ -0,0 +1,456 @@ +import type * as Shared from '@tanstack/query-types/bindings' +import type { + DefaultError, + InfiniteData, + QueryKey, + UnsetMarker as unsetMarkerType, + dataTagErrorSymbol as dataTagErrorSymbolType, + dataTagSymbol as dataTagSymbolType, +} from '@tanstack/query-types/bindings' +import type { QueryRuntime } from './runtimeBinding' + +export const dataTagSymbol: dataTagSymbolType = Symbol.for( + '@tanstack/query/dataTagSymbol', +) as dataTagSymbolType +/** + * The type of the `dataTagSymbol` key, under which a {@link DataTag} stores its data type. + */ +export type dataTagSymbol = typeof dataTagSymbol +export const dataTagErrorSymbol: dataTagErrorSymbolType = Symbol.for( + '@tanstack/query/dataTagErrorSymbol', +) as dataTagErrorSymbolType +/** + * The type of the `dataTagErrorSymbol` key, under which a {@link DataTag} stores its error type. + */ +export type dataTagErrorSymbol = typeof dataTagErrorSymbol +export const unsetMarker: unsetMarkerType = Symbol.for( + '@tanstack/query/unsetMarker', +) as unsetMarkerType + +export type QueryFunction< + T = unknown, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.QueryFunction + +export type StaleTimeFunction< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = Shared.StaleTimeFunction< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey +> + +export type QueryBooleanOption< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = Shared.QueryBooleanOption< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey +> + +export type QueryPersister< + T = unknown, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.QueryPersister + +export type QueryFunctionContext< + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.QueryFunctionContext + +// oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes every function-like value, including constructors, from the value branch + +export type PlaceholderDataFunction< + TQueryFnData = unknown, + TError = DefaultError, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = Shared.PlaceholderDataFunction< + QueryRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey +> + +export type QueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.QueryOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> + +export type ThrowOnError< + TQueryFnData, + TError, + TQueryData, + TQueryKey extends QueryKey, +> = Shared.ThrowOnError< + QueryRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey +> + +export type QueryObserverOptionsBase< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.QueryObserverOptionsBase< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> + +export type QueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.QueryObserverOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> + +export type DefaultedQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.DefaultedQueryObserverOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> + +export type InfiniteQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = Shared.InfiniteQueryObserverOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> + +export type DefaultedInfiniteQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = Shared.DefaultedInfiniteQueryObserverOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> + +export type QueryExecuteOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = Shared.QueryExecuteOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> + +export type InfiniteQueryExecuteOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = Shared.InfiniteQueryExecuteOptions< + QueryRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> + +export type InvalidateQueryFilters = + Shared.InvalidateQueryFilters + +export type RefetchQueryFilters = + Shared.RefetchQueryFilters + +export type MutationFunctionContext = + Shared.MutationFunctionContext + +export type MutationFunction< + TData = unknown, + TVariables = unknown, +> = Shared.MutationFunction + +export type MutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationOptions< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutationObserverOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationObserverOptions< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutateOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutateOptions< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutateFunctionRest< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutateFunctionRest< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutateFunction< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutateFunction< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutationObserverBaseResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationObserverBaseResult< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutationObserverIdleResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationObserverIdleResult< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutationObserverLoadingResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationObserverLoadingResult< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutationObserverErrorResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationObserverErrorResult< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutationObserverSuccessResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationObserverSuccessResult< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type MutationObserverResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Shared.MutationObserverResult< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +export type QueryClientConfig = Shared.QueryClientConfig + +export type DefaultOptions = Shared.DefaultOptions< + QueryRuntime, + TError +> + +export type { + NonUndefinedGuard, + DistributiveOmit, + OmitKeyof, + Override, + Register, + DefaultError, + QueryKey, + 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, + QueryObserverResult, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverPendingResult, + InfiniteQueryObserverLoadingResult, + InfiniteQueryObserverLoadingErrorResult, + InfiniteQueryObserverRefetchErrorResult, + InfiniteQueryObserverSuccessResult, + InfiniteQueryObserverPlaceholderResult, + DefinedInfiniteQueryObserverResult, + InfiniteQueryObserverResult, + MutationKey, + MutationStatus, + MutationScope, + MutationMeta, + CancelOptions, + SetDataOptions, + NotifyEventType, + NotifyEvent, +} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/utils.ts b/packages/react-query-no-core/src/runtime/utils.ts new file mode 100644 index 00000000000..2ffd6135e6a --- /dev/null +++ b/packages/react-query-no-core/src/runtime/utils.ts @@ -0,0 +1,748 @@ +import { timeoutManager } from './timeoutManager' +import type * as Shared from '@tanstack/query-types/bindings' +import type { + DefaultQueryFn, + DefaultQueryFn as defaultQueryFnType, + FetchSignal as fetchSignalType, + SkipToken, + SkipToken as skipTokenType, + Updater, +} from '@tanstack/query-types/bindings' +import type { Mutation } from './mutation' +import type { FetchOptions, Query } from './query' +import type { QueryRuntime } from './runtimeBinding' +import type { + CacheKeyConfig, + DefaultError, + EqualityFn, + MutationKey, + QueryFunction, + QueryKey, + QueryOptions, +} from './types' + +export type QueryFilters = + Shared.QueryFilters + +export type MutationFilters< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> = Shared.MutationFilters< + QueryRuntime, + TData, + TError, + TVariables, + TOnMutateResult +> + +// UTILS + +/** + * A function that does nothing. + */ +export function noop(): void +export function noop(): undefined +export function noop() {} + +/** + * Resolves an {@link Updater}: calls it with `input` if it is a function, otherwise returns it as + * is. + * @param updater - The new value, or a function that receives `input` and returns the new value. + * @param input - The current value, passed to `updater` if it is a function. + * @returns The new value. + */ +export function functionalUpdate( + updater: Updater, + input: TInput, +): TOutput { + return typeof updater === 'function' + ? (updater as (_: TInput) => TOutput)(input) + : updater +} + +/** + * Checks whether a value can be used as a timeout: a non-negative, finite number. + * @param value - The value to check. + * @returns `true` if `value` is a number that is `>= 0` and not `Infinity`. + */ +export function isValidTimeout(value: unknown): value is number { + return typeof value === 'number' && value >= 0 && value !== Infinity +} + +/** + * Calculates how long until data updated at `updatedAt` becomes stale. + * @param updatedAt - The timestamp, in milliseconds, at which the data was last updated. + * @param staleTime - The time, in milliseconds, after which data is considered stale. Defaults to + * `0`. + * @returns The remaining time in milliseconds, or `0` if the data is already stale. + */ +export function timeUntilStale(updatedAt: number, staleTime?: number): number { + return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0) +} + +/** + * Resolves an option that can be given either as a value or as a function of the query, such as + * `staleTime`. + * @param value - The option value, or a function that receives `query` and returns the value. + * @param query - The query passed to `value` if it is a function. + * @returns The resolved value, or `undefined` if `value` is `undefined`. + */ +export function resolveQueryValue< + TValue, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + value: + | undefined + | TValue + | ((query: Query) => TValue), + query: Query, +): TValue | undefined { + return typeof value === 'function' + ? ( + value as ( + query: Query, + ) => TValue + )(query) + : value +} + +/** + * Checks whether a query matches the given {@link QueryFilters}. + * Every filter that is specified must match; filters that are left unspecified are ignored. + * @param filters - The filters to check the query against. + * @param query - The query to check. + * @param keyConfig - The cache configuration for key comparison and hashing. + * @returns `true` if the query matches every specified filter. + * @example + * ```ts + * const queryCache = queryClient.getQueryCache() + * + * const matchingQueries = queryCache + * .getAll() + * .filter((query) => matchQuery({ queryKey: ['posts'] }, query)) + * ``` + */ +export function matchQuery( + filters: QueryFilters, + query: Query, + keyConfig?: CacheKeyConfig, +): boolean { + const { + type = 'all', + exact, + fetchStatus, + predicate, + queryKey, + stale, + } = filters + + if (queryKey) { + if (exact) { + if (query.queryHash !== hashKeyByOptions(queryKey, keyConfig)) { + return false + } + } else if ( + !partialMatchKey(query.queryKey, queryKey, keyConfig?.equalityFn) + ) { + return false + } + } + + if (type !== 'all') { + const isActive = query.isActive() + if (type === 'active' && !isActive) { + return false + } + if (type === 'inactive' && isActive) { + return false + } + } + + if (typeof stale === 'boolean' && query.isStale() !== stale) { + return false + } + + if (fetchStatus && fetchStatus !== query.state.fetchStatus) { + return false + } + + if (predicate && !predicate(query)) { + return false + } + + return true +} + +/** + * Checks whether a mutation matches the given {@link MutationFilters}. + * Every filter that is specified must match; filters that are left unspecified are ignored. + * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match. + * @param filters - The filters to check the mutation against. + * @param mutation - The mutation to check. + * @param keyConfig - The cache configuration for key comparison and hashing. + * @returns `true` if the mutation matches every specified filter. + * @example + * ```ts + * const mutationCache = queryClient.getMutationCache() + * + * const matchingMutations = mutationCache + * .getAll() + * .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation)) + * ``` + */ +export function matchMutation( + filters: MutationFilters, + mutation: Mutation, + keyConfig?: CacheKeyConfig, +): boolean { + const { exact, status, predicate, mutationKey } = filters + if (mutationKey) { + if (!mutation.options.mutationKey) { + return false + } + if (exact) { + if ( + hashKeyByOptions(mutation.options.mutationKey, keyConfig) !== + hashKeyByOptions(mutationKey, keyConfig) + ) { + return false + } + } else if ( + !partialMatchKey( + mutation.options.mutationKey, + mutationKey, + keyConfig?.equalityFn, + ) + ) { + return false + } + } + + if (status && mutation.state.status !== status) { + return false + } + + if (predicate && !predicate(mutation)) { + return false + } + + return true +} + +/** + * Hashes a cache key with the cache's `hashFn`, falling back to {@link hashKey}. + * @param cacheKey - The query or mutation key to hash. + * @param keyConfig - The cache configuration that may provide a custom `hashFn`. + * @returns The hash, a string that identifies the key in the cache. + */ +export function hashKeyByOptions< + TCacheKey extends ReadonlyArray = ReadonlyArray, +>( + cacheKey: TCacheKey, + keyConfig: CacheKeyConfig | undefined, +): string { + const hashFn = keyConfig?.hashFn ?? hashKey + return hashFn(cacheKey) +} + +/** + * Default query & mutation keys hash function. + * Hashes the value into a stable hash. + * @param queryKey - The query or mutation key to hash. + * @returns The stable hash of the key, as a JSON string. + * @example + * ```ts + * // Object keys are sorted, so key order doesn't affect the hash: + * hashKey(['todos', { page: 1, filter: 'done' }]) // === '["todos",{"filter":"done","page":1}]' + * ``` + */ +export function hashKey(queryKey: QueryKey | MutationKey): string { + return JSON.stringify(queryKey, (_, val) => + isPlainObject(val) + ? Object.keys(val) + .sort() + .reduce((result, key) => { + result[key] = val[key] + return result + }, {} as any) + : val, + ) +} + +const defaultEqualityFn: EqualityFn = (a, b) => a === b + +/** + * Checks if key `b` partially matches with key `a`. + * @param a - The key to check, e.g. a query's own key. + * @param b - The (partial) key to match against `a`. + * @param equalityFn - Compares individual key values. Defaults to strict equality. + * @returns `true` if every array element or object property in `b` matches the one at the same + * position in `a`. + */ +export function partialMatchKey( + a: QueryKey, + b: QueryKey, + equalityFn?: EqualityFn, +): boolean +export function partialMatchKey( + a: unknown, + b: unknown, + equalityFn?: EqualityFn, +): boolean +export function partialMatchKey( + a: any, + b: any, + equalityFn: EqualityFn = defaultEqualityFn, +): boolean { + if (equalityFn(a, b)) { + return true + } + + if (typeof a !== typeof b) { + return false + } + + if (isPlainArray(a) && isPlainArray(b)) { + if (b.length > a.length) return false + for (let i = 0; i < b.length; i++) { + if (!partialMatchKey(a[i], b[i], equalityFn)) { + return false + } + } + return true + } + + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b) + for (const key of bKeys) { + if (!partialMatchKey(a[key], b[key], equalityFn)) { + return false + } + } + return true + } + + return false +} + +/** + * This function returns `a` if `b` is deeply equal. + * If not, it will replace any deeply equal children of `b` with those of `a`. + * This can be used for structural sharing between JSON values for example. + * An optional equality function can be used for custom value types. + * @param a - The previous value, whose deeply equal parts are reused. + * @param b - The new value. + * @param equalityFn - Compares values for structural sharing. Defaults to strict equality. + * @returns `a` if `b` is deeply equal to it, otherwise `b` with its deeply equal parts replaced by + * those of `a`. + */ +export function replaceEqualDeep( + a: unknown, + b: T, + equalityFn?: EqualityFn, +): T +export function replaceEqualDeep( + a: any, + b: any, + equalityFn: EqualityFn = defaultEqualityFn, +): any { + return replaceEqualDeepInternal(a, b, equalityFn, 0) +} + +/** + * Reuses deeply equal values while limiting recursion to 500 levels. + * @param a - The previous value. + * @param b - The new value. + * @param equalityFn - Compares values for structural sharing. + * @param depth - The current recursion depth. + * @returns The new value with deeply equal parts of the previous value reused. + */ +function replaceEqualDeepInternal( + a: any, + b: any, + equalityFn: EqualityFn, + depth: number, +): any { + if (equalityFn(a, b)) { + return a + } + + if (depth > 500) return b + + const array = isPlainArray(a) && isPlainArray(b) + + if (!array && !(isPlainObject(a) && isPlainObject(b))) return b + + const aItems = array ? a : Object.keys(a) + const aSize = aItems.length + const bItems = array ? b : Object.keys(b) + const bSize = bItems.length + const copy: any = array ? new Array(bSize) : {} + + let equalItems = 0 + + for (let i = 0; i < bSize; i++) { + const key: any = array ? i : bItems[i] + const aItem = a[key] + const bItem = b[key] + + if (equalityFn(aItem, bItem)) { + copy[key] = aItem + if (array ? i < aSize : Object.hasOwn(a, key)) equalItems++ + continue + } + + if ( + aItem === null || + bItem === null || + typeof aItem !== 'object' || + typeof bItem !== 'object' + ) { + copy[key] = bItem + continue + } + + const v = replaceEqualDeepInternal(aItem, bItem, equalityFn, depth + 1) + copy[key] = v + if (v === aItem) equalItems++ + } + + return aSize === bSize && equalItems === aSize ? a : copy +} + +/** + * Shallow compare objects. + * @param a - The first object. + * @param b - The second object, or `undefined`. + * @returns `true` if both objects have the same keys, with strictly equal values for each key. + */ +export function shallowEqualObjects>( + a: T, + b: T | undefined, +): boolean { + if (!b || Object.keys(a).length !== Object.keys(b).length) { + return false + } + + for (const key of Object.keys(a)) { + if (!Object.hasOwn(b, key) || a[key] !== b[key]) { + return false + } + } + + return true +} + +/** + * Checks whether a value is an array with no holes and no extra properties. + * @param value - The value to check. + * @returns `true` if `value` is an array whose number of own keys equals its `length`. + */ +export function isPlainArray(value: unknown): value is Array { + return Array.isArray(value) && value.length === Object.keys(value).length +} + +// Copied from: https://github.com/jonschlinkert/is-plain-object +/** + * Checks whether a value is a plain object, e.g. created with an object literal or + * `Object.create(null)`. + * @param o - The value to check. + * @returns `true` if `o` is a plain object. + */ +export function isPlainObject(o: any): o is Record { + if (!hasObjectPrototype(o)) { + return false + } + + // If has no constructor + const objectPrototype = Object.getPrototypeOf(o) + const ctor = objectPrototype?.constructor + if (ctor === undefined) { + return true + } + + if (typeof ctor !== 'function') { + return false + } + + // If has modified prototype + const prot = ctor.prototype + if (!hasObjectPrototype(prot)) { + return false + } + + // If constructor does not have an Object-specific method + if (!prot.hasOwnProperty('isPrototypeOf')) { + return false + } + + // Handles Objects created by Object.create() + if (objectPrototype !== Object.prototype) { + return false + } + + // Most likely a plain Object + return true +} + +/** + * Checks whether a value's `Object.prototype.toString` tag is `[object Object]`. + * @param o - The value to check. + * @returns `true` if the tag is `[object Object]`. + */ +function hasObjectPrototype(o: any): boolean { + return Object.prototype.toString.call(o) === '[object Object]' +} + +/** + * Waits for the given time, using the configured {@link timeoutManager}. + * @param timeout - The time to wait, in milliseconds. + * @returns A promise that resolves after `timeout` milliseconds. + */ +export function sleep(timeout: number): Promise { + return new Promise((resolve) => { + timeoutManager.setTimeout(resolve, timeout) + }) +} + +/** + * Applies a query's `structuralSharing` option when writing new data. + * @param prevData - The previously cached data. + * @param data - The new data. + * @param options - The query options, whose `structuralSharing` decides how the data is merged. + * @returns The result of a custom `structuralSharing` function, `data` with its unchanged parts + * replaced by those of `prevData` by default, or `data` as is if `structuralSharing` is `false`. + * @throws {Error} The error from the default structural sharing, e.g. when the data is not JSON serializable. + * Outside production, it is also logged to the console. + */ +export function replaceData< + TData, + TOptions extends QueryOptions, +>(prevData: TData | undefined, data: TData, options: TOptions): TData { + if (typeof options.structuralSharing === 'function') { + return options.structuralSharing(prevData, data) as TData + } else if (options.structuralSharing !== false) { + if (process.env.NODE_ENV !== 'production') { + try { + return replaceEqualDeep(prevData, data) + } catch (error) { + console.error( + `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`, + ) + + // Prevent the replaceEqualDeep from being called again down below. + throw error + } + } + // Structurally share data between prev and new data if needed + return replaceEqualDeep(prevData, data) + } + return data +} + +/** + * Intended to be passed as a query's `placeholderData` option, for example + * `placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new + * query key is fetching, it keeps displaying the previously fetched data until the new data arrives. + * @param previousData - The data of the previous query key, passed by the observer. + * @returns The previous data, unchanged. + * @example + * ```ts + * new QueryObserver(queryClient, { + * queryKey: ['posts', page], + * queryFn: () => fetchPosts(page), + * placeholderData: keepPreviousData, + * }) + * ``` + */ +export function keepPreviousData( + previousData: T | undefined, +): T | undefined { + return previousData +} + +/** + * Adds an item to one end of a new array. If the result exceeds `max`, removes + * excess items from the opposite end. + * @param items - The current items. + * @param item - The value to add. + * @param max - The maximum number of items to keep. Omit it or use `0` for no limit. + * @param prepend - Pass `true` to add at the start. The default is to add at the end. + * @returns A new array with `item` added. + */ +export function addToArray( + items: Array, + item: T, + max?: number, + prepend?: boolean, +): Array { + const newItems = prepend ? [item, ...items] : [...items, item] + if (max && newItems.length > max) { + return prepend ? newItems.slice(0, max) : newItems.slice(-max) + } + return newItems +} + +/** + * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent + * to `enabled: false`) while preserving full type inference for the query's data. Unlike `enabled: false`, + * a query disabled via `skipToken` cannot be triggered with `refetch`. + * @example + * ```ts + * new QueryObserver(queryClient, { + * queryKey: ['post', postId], + * queryFn: postId != null ? () => fetchPost(postId) : skipToken, + * }) + * ``` + */ +export const skipToken: skipTokenType = Symbol.for( + '@tanstack/query/skipToken', +) as skipTokenType + +/** + * Pass this as `queryFn` to use the query function configured on the client. + * The defaults for the query key take precedence over the client's global query defaults. + * If no query function is configured, a fetch fails with a `Missing queryFn` error. + */ +export const defaultQueryFn: defaultQueryFnType = Symbol.for( + '@tanstack/query/defaultQueryFn', +) as defaultQueryFnType + +/** + * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from + * an `initialPromise`, that promise is returned instead. If there is no usable `queryFn`, the returned + * function rejects with a `Missing queryFn` error. + * @param options - The query options with the `queryFn`, and the `queryHash` used in error messages. + * @param fetchOptions - The fetch options, which may carry an `initialPromise`. + * @returns The function to call for the fetch. + */ +export function ensureQueryFn< + TQueryFnData = unknown, + TQueryKey extends QueryKey = QueryKey, +>( + options: { + queryFn?: + | QueryFunction + | SkipToken + | DefaultQueryFn + queryHash?: string + }, + fetchOptions?: FetchOptions, +): QueryFunction { + if (process.env.NODE_ENV !== 'production') { + if (options.queryFn === skipToken) { + console.error( + `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`, + ) + } + } + + // if we attempt to retry a fetch that was triggered from an initialPromise + // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise + // if an observer has already mounted, we will be able to retry with that queryFn + if (!options.queryFn && fetchOptions?.initialPromise) { + return () => fetchOptions.initialPromise! + } + + if ( + !options.queryFn || + options.queryFn === skipToken || + options.queryFn === defaultQueryFn + ) { + return () => + Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`)) + } + + return options.queryFn +} + +/** + * Resolves a `throwOnError` option to a boolean. + * If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller, + * additional context such as the query or mutation) and its result is returned, allowing the throwing + * behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined` + * resolves to `false`). + * @param throwOnError - The `throwOnError` option: a boolean, a function that decides per error, or + * `undefined`. + * @param params - The arguments passed to `throwOnError` if it is a function. + * @returns Whether the error should be thrown. + * @example + * ```ts + * const throwOnError = + * query.state.error && typeof options.throwOnError === 'function' + * ? shouldThrowError(options.throwOnError, [query.state.error, query]) + * : options.throwOnError + * ``` + */ +export function shouldThrowError) => boolean>( + throwOnError: boolean | T | undefined, + params: Parameters, +): boolean { + // Allow throwOnError function to override throwing behavior on a per-error basis + if (typeof throwOnError === 'function') { + return throwOnError(...params) + } + + return !!throwOnError +} + +export const fetchSignal: fetchSignalType = Symbol.for( + '@tanstack/query/fetchSignal', +) as fetchSignalType + +/** + * Adds a lazy `signal` getter to an object, such as a query function context. The first time + * `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right + * away if it is already aborted), so cancellation is only tracked when the signal is actually used. + * @param object - The object to add the `signal` property to. + * @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read. + * @param onCancelled - Called when the signal is aborted, if `signal` was read. + * @param internalSignal - The fetch signal to forward without consuming the getter. + * @returns The same object, with the `signal` property added. + */ +export function addConsumeAwareSignal( + object: T, + getSignal: () => AbortSignal, + onCancelled: () => void, + internalSignal?: AbortSignal, +): T & { signal: AbortSignal } { + let consumed = false + let signal: AbortSignal | undefined + + Object.defineProperties(object, { + [fetchSignal]: { value: internalSignal }, + signal: { + enumerable: true, + get: () => { + signal ??= getSignal() + if (consumed) { + return signal + } + + consumed = true + if (signal.aborted) { + onCancelled() + } else { + signal.addEventListener('abort', onCancelled, { once: true }) + } + + return signal + }, + }, + }) + + return object as T & { signal: AbortSignal } +} + +export type { + Updater, + QueryTypeFilter, + SkipToken, + DefaultQueryFn, + FetchSignalContext, +} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/suspense.ts b/packages/react-query-no-core/src/suspense.ts new file mode 100644 index 00000000000..f903592ec0a --- /dev/null +++ b/packages/react-query-no-core/src/suspense.ts @@ -0,0 +1,214 @@ +import { use } from 'react' +import { QueryObserver } from './runtime' +import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import type { + DefaultError, + DefaultedQueryObserverOptions, + Query, + QueryClient, + QueryKey, + QueryObserverResult, +} from './runtime' + +type SuspensePromiseEntry = { + fetchPromise: Promise + promise: Promise + settled: boolean +} + +const suspensePromiseCache = new WeakMap< + Query, + SuspensePromiseEntry +>() + +/** + * Uses the nearest error boundary when the query has no data to show. + * @param _error - The query error. + * @param query - The query that failed. + * @returns Whether the query has no data. + */ +export const defaultThrowOnError = < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + _error: TError, + query: Query, +) => query.state.data === undefined + +/** + * Raises `staleTime` and a numeric `gcTime` to at least 1000ms when `suspense` is enabled, so a + * component that remounts after suspending doesn't refetch right away or find the query garbage + * collected. A `'static'` `staleTime` is kept as is. Mutates the options. + * @param defaultedOptions - The defaulted query options to adjust. + */ +export const ensureSuspenseTimers = ( + defaultedOptions: DefaultedQueryObserverOptions, +) => { + if (defaultedOptions.suspense) { + // Handle staleTime to ensure minimum 1000ms in Suspense mode + // This prevents unnecessary refetching when components remount after suspending + const MIN_SUSPENSE_TIME_MS = 1000 + + const clamp = (value: number | 'static' | undefined) => + value === 'static' + ? value + : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS) + + const originalStaleTime = defaultedOptions.staleTime + defaultedOptions.staleTime = + typeof originalStaleTime === 'function' + ? (...args) => clamp(originalStaleTime(...args)) + : clamp(originalStaleTime) + + if (typeof defaultedOptions.gcTime === 'number') { + defaultedOptions.gcTime = Math.max( + defaultedOptions.gcTime, + MIN_SUSPENSE_TIME_MS, + ) + } + } +} + +/** + * Decides whether a Suspense query needs to fetch during render. + * @param result - The result for this render. + * @param errorResetBoundary - The nearest query error reset boundary. + * @param query - The query to fetch. + * @returns `undefined` to skip the fetch, `false` to fetch in the background, or `true` to suspend. + */ +const shouldSuspend = ( + result: QueryObserverResult, + errorResetBoundary: QueryErrorResetBoundaryValue, + query: Query, +): boolean | undefined => { + if ( + result.isPending || + (query.state.status === 'error' && errorResetBoundary.isReset()) + ) { + return true + } + + if (result.isFetching && result.isPlaceholderData) { + return false + } + + return undefined +} + +/** + * Starts a fetch during render or reuses a promise for an existing fetch. + * @param defaultedOptions - The options of the query. + * @param observer - The observer that starts the fetch. + * @param errorResetBoundary - The nearest query error reset boundary. + * @param query - The query used to key the promise cache. + * @returns A promise that resolves when the fetch settles. + */ +export function getSuspensePromise( + defaultedOptions: DefaultedQueryObserverOptions, + observer: QueryObserver, + errorResetBoundary: QueryErrorResetBoundaryValue, + query: Query, +): Promise { + let entry = suspensePromiseCache.get(query) + if (!entry || entry.settled) { + const fetchPromise = observer.fetchOptimistic(defaultedOptions) + const settle = () => { + pending.settled = true + } + const pending: SuspensePromiseEntry = { + fetchPromise, + // Retry the render when the fetch settles, even on failure. + promise: fetchPromise.then(settle, settle), + settled: false, + } + suspensePromiseCache.set(query, pending) + entry = pending + } + + entry.fetchPromise.catch(() => errorResetBoundary.clearReset()) + return entry.promise +} + +type SuspenseOptions = DefaultedQueryObserverOptions +type SuspenseResult = QueryObserverResult +type SnapshotReader = { getSnapshot: () => T } + +const useReadSuspenseQuery = ( + defaultedOptions: SuspenseOptions, + reader: SnapshotReader, + observer: QueryObserver, + client: QueryClient, + errorResetBoundary: QueryErrorResetBoundaryValue, +) => { + if (!defaultedOptions.suspense) return + + const snapshot = reader.getSnapshot() + const query = client.getQueryCache().build(client, defaultedOptions) + const suspend = shouldSuspend(snapshot, errorResetBoundary, query) + if (suspend === undefined) return + + const promise = getSuspensePromise( + defaultedOptions, + observer, + errorResetBoundary, + query, + ) + if (suspend) { + use(promise) + } +} + +/** Supplies Suspense behavior for one query. */ +export const suspenseQueryPolicy = { + prepare: ensureSuspenseTimers, + readQuery: useReadSuspenseQuery, +} + +const useReadSuspenseQueries = ( + defaultedQueries: Array, + reader: SnapshotReader>, + client: QueryClient, + errorResetBoundary: QueryErrorResetBoundaryValue, +) => { + const snapshot = reader.getSnapshot() + + const suspensePromises = snapshot.map((result, index) => { + const opts = defaultedQueries[index] + + if (!opts?.suspense) { + return undefined + } + + const query = client.getQueryCache().build(client, opts) + const suspend = shouldSuspend(result, errorResetBoundary, query) + + if (suspend === undefined) { + return undefined + } + + const queryObserver = new QueryObserver(client, opts) + const promise = getSuspensePromise( + opts, + queryObserver, + errorResetBoundary, + query, + ) + + return suspend ? promise : undefined + }) + + // Start every fetch before calling use(), because use() suspends immediately. + for (const promise of suspensePromises) { + if (promise) { + use(promise) + } + } +} + +/** Supplies Suspense behavior for parallel queries. */ +export const suspenseQueriesPolicy = { + prepare: ensureSuspenseTimers, + readQueries: useReadSuspenseQueries, +} diff --git a/packages/react-query-no-core/src/types.ts b/packages/react-query-no-core/src/types.ts new file mode 100644 index 00000000000..3304cd4691d --- /dev/null +++ b/packages/react-query-no-core/src/types.ts @@ -0,0 +1,471 @@ +/* istanbul ignore file */ + +import type { + DefaultError, + DefinedInfiniteQueryObserverResult, + DefinedQueryObserverResult, + DistributiveOmit, + InfiniteData, + InfiniteQueryExecuteOptions, + InfiniteQueryObserverOptions, + InfiniteQueryObserverPlaceholderResult, + InfiniteQueryObserverResult, + MutateFunction, + MutationObserverOptions, + MutationObserverResult, + OmitKeyof, + Override, + QueryExecuteOptions, + QueryKey, + QueryObserverOptions, + QueryObserverPlaceholderResult, + QueryObserverResult, + SkipToken, +} from './runtime' + +/** + * {@link UseBaseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseBaseQueryOptions = UseBaseQueryOptions< + any, + any, + any, + any, + any +> +/** + * The options shared by `useQuery` and `useSuspenseQuery`. Extends {@link QueryObserverOptions} from + * `@tanstack/query-core` with the `react-query`-specific `subscribed` option. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryData - The type of the data actually held in the query cache — the input to `select` and + * `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`. + * @template TQueryKey - The type of your `queryKey`. + */ +export interface UseBaseQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends QueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +> { + /** + * Set this to `false` to unsubscribe this observer from updates to the query cache. + * @defaultValue true + */ + subscribed?: boolean +} + +/** + * The options accepted by `usePrefetchQuery` — everything you can pass to `queryClient.query`, with a + * required `queryFn`. Pass `defaultQueryFn` to use the client defaults. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryData - The type of the data actually held in the query cache — the input to `select` and + * `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`. + * @template TQueryKey - The type of your `queryKey`. + */ +export type UsePrefetchQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = DistributiveOmit< + QueryExecuteOptions, + 'queryFn' +> & { + /** + * Pass a query function or `defaultQueryFn` to use the client defaults. Prefetch hooks do not accept `skipToken`. + */ + queryFn: Exclude< + QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >['queryFn'], + SkipToken | undefined + > +} + +/** + * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `queryClient.infiniteQuery`, + * with a required `queryFn`. Pass `defaultQueryFn` to use the client defaults. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params — a prefetch never reads `data` back out, so this + * parameter only matters if you reuse these options elsewhere with `select` applied. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export type UsePrefetchInfiniteQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = DistributiveOmit< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + 'queryFn' +> & { + /** + * Pass a query function or `defaultQueryFn` to use the client defaults. Prefetch hooks do not accept `skipToken`. + */ + queryFn: Exclude< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >['queryFn'], + SkipToken | undefined + > +} + +/** + * {@link UseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseQueryOptions = UseQueryOptions +/** + * The options accepted by `useQuery`. Same as {@link UseBaseQueryOptions}, minus `suspense` (which + * `react-query` derives from which hook you call rather than exposing as an option). + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryKey - The type of your `queryKey`. + */ +export interface UseQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends OmitKeyof< + UseBaseQueryOptions, + 'suspense' +> {} + +/** + * {@link UseSuspenseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseSuspenseQueryOptions = UseSuspenseQueryOptions< + any, + any, + any, + any +> +/** + * Options for a `useSuspenseQuery` call whose data is defined. The options match those of + * {@link UseQueryOptions} except for `throwOnError` and `enabled`. + * Use the other overload for a query function that can be `skipToken`. + * @template TQueryFnData - The type your `queryFn` resolves to. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no + * `select` is used. + * @template TQueryKey - The type of your `queryKey`. + */ +export interface UseSuspenseQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> extends OmitKeyof< + UseQueryOptions, + 'queryFn' | 'enabled' | 'throwOnError' +> { + /** + * The query function. Use `defaultQueryFn` to use the client's configured function. + */ + queryFn: Exclude< + UseQueryOptions['queryFn'], + SkipToken + > +} + +/** + * {@link UseInfiniteQueryOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseInfiniteQueryOptions = UseInfiniteQueryOptions< + any, + any, + any, + any, + any +> +/** + * The options accepted by `useInfiniteQuery`. Extends {@link InfiniteQueryObserverOptions} from + * `@tanstack/query-core` with the `react-query`-specific `subscribed` option, minus `suspense` (which + * `react-query` derives from which hook you call rather than exposing as an option). + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export interface UseInfiniteQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> extends OmitKeyof< + InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + 'suspense' +> { + /** + * Set this to `false` to unsubscribe this observer from updates to the query cache. + * @defaultValue true + */ + subscribed?: boolean +} + +/** + * {@link UseSuspenseInfiniteQueryOptions} with all type parameters set to `any`, useful when the specific types + * aren't relevant, e.g. when accepting options for any query in a helper function. + */ +export type AnyUseSuspenseInfiniteQueryOptions = + UseSuspenseInfiniteQueryOptions +/** + * The options accepted by `useSuspenseInfiniteQuery`. Same as {@link UseInfiniteQueryOptions}, except for + * `enabled` and `throwOnError`. If `placeholderData` provides data, the query can render while the fetch runs. + * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. + * @template TError - The type of errors your `queryFn` may throw. + * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, + * the shape of all fetched pages plus their page params. + * @template TQueryKey - The type of your `queryKey`. + * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. + */ +export interface UseSuspenseInfiniteQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> extends OmitKeyof< + UseInfiniteQueryOptions, + 'queryFn' | 'enabled' | 'throwOnError' +> { + /** + * The query function. Use `defaultQueryFn` to use the client defaults. Use the other overload when the function can be `skipToken`. + */ + queryFn: Exclude< + UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >['queryFn'], + SkipToken + > +} + +/** + * The result of `useQuery` when `initialData` isn't set — `data` may be `undefined` while the query is + * `pending`. Re-exports {@link QueryObserverResult} from `@tanstack/query-core`. `useInfiniteQuery` returns + * {@link UseInfiniteQueryResult} instead. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseBaseQueryResult< + TData = unknown, + TError = DefaultError, +> = QueryObserverResult + +/** + * The result of `useQuery`. Same as {@link UseBaseQueryResult}. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseQueryResult< + TData = unknown, + TError = DefaultError, +> = UseBaseQueryResult + +/** The result of `useSuspenseQuery`, including defined placeholder data when configured. */ +export type UseSuspenseQueryResult = + | DefinedQueryObserverResult + | QueryObserverPlaceholderResult + +/** + * The result of `useQuery` when `initialData` is set. The `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). + * Re-exports {@link DefinedQueryObserverResult} from `@tanstack/query-core`. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type DefinedUseQueryResult< + TData = unknown, + TError = DefaultError, +> = DefinedQueryObserverResult + +/** + * The result of `useInfiniteQuery` when `initialData` isn't set — `data` may be `undefined` while the query is + * `pending`. Re-exports {@link InfiniteQueryObserverResult} from `@tanstack/query-core`. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseInfiniteQueryResult< + TData = unknown, + TError = DefaultError, +> = InfiniteQueryObserverResult + +/** + * The result of `useInfiniteQuery` when `initialData` is set — `data` is never `undefined` (unless a + * `select` changes `TData` to include `undefined`). Re-exports {@link DefinedInfiniteQueryObserverResult} + * from `@tanstack/query-core`. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type DefinedUseInfiniteQueryResult< + TData = unknown, + TError = DefaultError, +> = DefinedInfiniteQueryObserverResult + +/** + * The result of `useSuspenseInfiniteQuery`, including defined placeholder data when configured. + * @template TData - The type `data` ends up as after `select` runs. + * @template TError - The type of errors your `queryFn` may throw. + */ +export type UseSuspenseInfiniteQueryResult< + TData = unknown, + TError = DefaultError, +> = + | DefinedInfiniteQueryObserverResult + | InfiniteQueryObserverPlaceholderResult + +/** + * {@link UseMutationOptions} with all type parameters set to `any`, useful when the specific types aren't + * relevant, e.g. when accepting options for any mutation in a helper function. + */ +export type AnyUseMutationOptions = UseMutationOptions +/** + * The options accepted by `useMutation`. Same as {@link MutationObserverOptions} from `@tanstack/query-core`, + * minus the internal `_defaulted` flag. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export interface UseMutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends OmitKeyof< + MutationObserverOptions, + '_defaulted' +> {} + +/** + * The type of `mutate`, as returned by `useMutation`. Forwards the variables (and an optional per-call + * `onSuccess`/`onError`/`onSettled`) to the underlying `mutate` call. Fire-and-forget — errors are surfaced + * through the mutation result instead of being thrown by `mutate`, unless `throwOnError` makes `useMutation` + * rethrow them. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseMutateFunction< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = ( + ...args: Parameters< + MutateFunction + > +) => void + +/** + * The type of `mutateAsync`, as returned by `useMutation`. Similar to {@link UseMutateFunction}, but returns a + * promise which can be awaited. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseMutateAsyncFunction< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = MutateFunction + +/** + * The result of `useMutation`. Same as {@link MutationObserverResult} from `@tanstack/query-core`, with + * `mutate` narrowed to the fire-and-forget {@link UseMutateFunction} signature, plus the added `mutateAsync`. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseBaseMutationResult< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> = Override< + MutationObserverResult, + { mutate: UseMutateFunction } +> & { + /** + * Similar to `mutate`, but returns a promise which can be awaited. + */ + mutateAsync: UseMutateAsyncFunction< + TData, + TError, + TVariables, + TOnMutateResult + > +} + +/** + * The result of `useMutation`. Same as {@link UseBaseMutationResult}. + * @template TData - The type your mutation function resolves to. + * @template TError - The type of errors your mutation function may throw. + * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. + * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as + * their `onMutateResult` parameter — useful for optimistic-update rollback data. + */ +export type UseMutationResult< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> = UseBaseMutationResult diff --git a/packages/react-query-no-core/src/useBaseQuery.ts b/packages/react-query-no-core/src/useBaseQuery.ts new file mode 100644 index 00000000000..052bd5bb8b5 --- /dev/null +++ b/packages/react-query-no-core/src/useBaseQuery.ts @@ -0,0 +1,146 @@ +'use client' +import * as React from 'react' +import { useIsRestoring } from './IsRestoringProvider' +import { useQueryClient } from './QueryClientProvider' +import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary' +import { + ensurePreventErrorBoundaryRetry, + getHasError, + useClearResetErrorBoundary, +} from './errorBoundaryUtils' +import { useObserverSnapshot } from './useObserverSnapshot' +import type { + QueryClient, + QueryKey, + QueryObserver, + QueryObserverResult, +} from './runtime' +import type { suspenseQueryPolicy } from './suspense' +import type { UseBaseQueryOptions } from './types' + +/** + * Base implementation shared by `useQuery`, `useInfiniteQuery`, `useSuspenseQuery`, and + * `useSuspenseInfiniteQuery`. + * @param options - The options passed to the calling hook. + * @param Observer - The query observer class (`QueryObserver` or + * `InfiniteQueryObserver`). + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest + * context will be used. + * @param suspense - Render policy used by the dedicated Suspense hooks. + * @returns The query result, tracking which properties are read unless `notifyOnChangeProps` is + * set. + * @throws {Error} If `options` is not an object (outside production), or the query error when it should be + * thrown to the nearest error boundary (see `throwOnError`). While suspending, it throws a promise instead. + */ +export function useBaseQuery< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + options: UseBaseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + Observer: typeof QueryObserver, + queryClient?: QueryClient, + suspense?: typeof suspenseQueryPolicy, +): QueryObserverResult { + if (process.env.NODE_ENV !== 'production') { + if (typeof options !== 'object' || Array.isArray(options)) { + throw new Error( + 'Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object', + ) + } + } + + const isRestoring = useIsRestoring() + const errorResetBoundary = useQueryErrorResetBoundary() + const client = useQueryClient(queryClient) + const defaultedOptions = client.defaultQueryOptions({ + ...options, + suspense: !!suspense, + }) + + const query = client + .getQueryCache() + .get( + defaultedOptions.queryHash, + ) + + if (process.env.NODE_ENV !== 'production') { + if (!defaultedOptions.queryFn) { + console.error( + `[${defaultedOptions.queryHash}]: No query function was provided or configured in the query defaults. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`, + ) + } + } + + const subscribed = options.subscribed !== false + + // Make sure results are optimistically set in fetching state before subscribing or updating options + defaultedOptions._optimisticResults = isRestoring + ? 'isRestoring' + : subscribed + ? 'optimistic' + : undefined + + suspense?.prepare(defaultedOptions) + ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query) + useClearResetErrorBoundary(errorResetBoundary) + + const [observer] = React.useState( + () => + new Observer( + client, + defaultedOptions, + ), + ) + + const reader = observer.createResultReader(defaultedOptions) + + suspense?.readQuery( + defaultedOptions, + reader, + observer, + client, + errorResetBoundary, + ) + + const result = useObserverSnapshot( + observer, + reader, + !isRestoring && subscribed, + refreshQuery, + ) + + // Handle error boundary + if ( + getHasError({ + result, + errorResetBoundary, + throwOnError: defaultedOptions.throwOnError, + query, + suspense: defaultedOptions.suspense, + }) + ) { + throw result.error + } + + // Handle result property usage tracking + return !defaultedOptions.notifyOnChangeProps + ? observer.trackResult(result) + : result +} + +/** + * Refreshes the query after the observer subscribes. + * @param observer - The observer that was subscribed. + */ +function refreshQuery(observer: Pick): void { + observer.updateResult() +} diff --git a/packages/react-query-no-core/src/useInfiniteQuery.ts b/packages/react-query-no-core/src/useInfiniteQuery.ts new file mode 100644 index 00000000000..6ab4fde4fb3 --- /dev/null +++ b/packages/react-query-no-core/src/useInfiniteQuery.ts @@ -0,0 +1,364 @@ +'use client' +import { InfiniteQueryObserver } from './runtime' +import { useBaseQuery } from './useBaseQuery' +import type { + DefinedInitialDataInfiniteOptions, + UndefinedInitialDataInfiniteOptions, +} from './infiniteQueryOptions' +import type { + DefaultError, + InfiniteData, + QueryClient, + QueryKey, + QueryObserver, +} from './runtime' +import type { + DefinedUseInfiniteQueryResult, + UseInfiniteQueryOptions, + UseInfiniteQueryResult, +} from './types' + +/** + * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of + * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + * + * This overload is selected when `initialData` is known to be defined. + * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` known to be defined. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`, + * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and + * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default + * `InfiniteData` shape. + * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default + * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user + * actions, or add conditions like `hasNextPage && !isFetching`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @example + * ```tsx + * import { useInfiniteQuery } from '@tanstack/react-query-no-core' + * + * function Projects() { + * // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the + * // list stays visible alongside the error. + * const { data, isError, error } = useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * initialData: { pages: [], pageParams: [] }, + * }) + * + * return ( + *
+ * {isError ? Error: {error.message} : null} + *
    + * {data.pages.map((page) => page.projects.map((p) =>
  • {p.name}
  • ))} + *
+ *
+ * ) + * } + * ``` + */ +export function useInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): DefinedUseInfiniteQueryResult + +/** + * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of + * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`, + * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and + * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default + * `InfiniteData` shape. + * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default + * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user + * actions, or add conditions like `hasNextPage && !isFetching`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @example + * Fetching the next page from a "Load More" button click: + * ```tsx + * import { useInfiniteQuery } from '@tanstack/react-query-no-core' + * + * function Projects() { + * const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = + * useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + * <> + *
    + * {data.pages.map((page) => + * page.projects.map((project) =>
  • {project.name}
  • ), + * )} + *
+ * + * + * ) + * } + * ``` + * @example + * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a + * sentinel element after the list: + * ```tsx + * import { useInfiniteQuery } from '@tanstack/react-query-no-core' + * import { useEffect, useRef } from 'react' + * + * function Projects() { + * const { + * data, + * isPending, + * isError, + * error, + * fetchNextPage, + * hasNextPage, + * isFetching, + * isFetchingNextPage, + * } = useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * const sentinelRef = useRef(null) + * + * useEffect(() => { + * const sentinel = sentinelRef.current + * if (sentinel == null || !hasNextPage || isFetching) return + * + * const observer = new IntersectionObserver(([entry]) => { + * if (entry?.isIntersecting) fetchNextPage() + * }) + * observer.observe(sentinel) + * + * return () => observer.disconnect() + * }, [hasNextPage, isFetching, fetchNextPage]) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + * <> + *
    + * {data.pages.map((page) => + * page.projects.map((project) =>
  • {project.name}
  • ), + * )} + *
+ *
{isFetchingNextPage ? 'Loading more...' : null}
+ * + * ) + * } + * ``` + */ +export function useInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): UseInfiniteQueryResult + +/** + * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of + * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. + * @param options - The {@link UseInfiniteQueryOptions} to use — everything you can pass to `useInfiniteQuery`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`, + * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and + * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default + * `InfiniteData` shape. + * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default + * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user + * actions, or add conditions like `hasNextPage && !isFetching`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @example + * Fetching the next page from a "Load More" button click: + * ```tsx + * import { useInfiniteQuery } from '@tanstack/react-query-no-core' + * + * function Projects() { + * const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = + * useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + * <> + *
    + * {data.pages.map((page) => + * page.projects.map((project) =>
  • {project.name}
  • ), + * )} + *
+ * + * + * ) + * } + * ``` + * @example + * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a + * sentinel element after the list: + * ```tsx + * import { useInfiniteQuery } from '@tanstack/react-query-no-core' + * import { useEffect, useRef } from 'react' + * + * function Projects() { + * const { + * data, + * isPending, + * isError, + * error, + * fetchNextPage, + * hasNextPage, + * isFetching, + * isFetchingNextPage, + * } = useInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * const sentinelRef = useRef(null) + * + * useEffect(() => { + * const sentinel = sentinelRef.current + * if (sentinel == null || !hasNextPage || isFetching) return + * + * const observer = new IntersectionObserver(([entry]) => { + * if (entry?.isIntersecting) fetchNextPage() + * }) + * observer.observe(sentinel) + * + * return () => observer.disconnect() + * }, [hasNextPage, isFetching, fetchNextPage]) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + * <> + *
    + * {data.pages.map((page) => + * page.projects.map((project) =>
  • {project.name}
  • ), + * )} + *
+ *
{isFetchingNextPage ? 'Loading more...' : null}
+ * + * ) + * } + * ``` + * @example + * A query that's disabled, type safe, until `postId` is set — pass `skipToken` as `queryFn` + * instead of setting `enabled: false`: + * ```tsx + * import { skipToken, useInfiniteQuery } from '@tanstack/react-query-no-core' + * + * function Comments({ postId }: { postId: string | undefined }) { + * // Use `isLoading`, not `isPending`, so the loading state doesn't show while the query is disabled. + * const { data, isLoading, isError, error } = useInfiniteQuery({ + * queryKey: ['post', postId, 'comments'], + * queryFn: + * postId != null + * ? ({ pageParam }) => fetchComments(postId, pageParam) + * : skipToken, + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * if (postId == null) return 'Select a post' + * if (isLoading) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
    + * {data?.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} + *
+ * ) + * } + * ``` + */ +export function useInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): UseInfiniteQueryResult + +export function useInfiniteQuery( + options: UseInfiniteQueryOptions, + queryClient?: QueryClient, +) { + return useBaseQuery( + options, + InfiniteQueryObserver as typeof QueryObserver, + queryClient, + ) +} diff --git a/packages/react-query-no-core/src/useIsFetching.ts b/packages/react-query-no-core/src/useIsFetching.ts new file mode 100644 index 00000000000..db39fc9ab5a --- /dev/null +++ b/packages/react-query-no-core/src/useIsFetching.ts @@ -0,0 +1,56 @@ +'use client' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import { notifyManager } from './runtime' +import type { QueryClient, QueryFilters } from './runtime' + +/** + * The `useIsFetching` hook returns the `number` of the queries that your application is loading or fetching in + * the background (useful for app-wide loading indicators). + * @param filters - The {@link QueryFilters} to narrow down the matched queries. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns Will be the `number` of the queries that your application is currently loading or fetching in the + * background. + * @example + * ```tsx + * import { useIsFetching } from '@tanstack/react-query-no-core' + * + * function PostsFetchingIndicator() { + * // How many queries matching the posts prefix are fetching? + * const isFetchingPosts = useIsFetching({ queryKey: ['posts'] }) + * + * return isFetchingPosts ? Refreshing posts... : null + * } + * ``` + * @example + * A global loading indicator for any query fetching in the background, not just the ones on screen: + * ```tsx + * import { useIsFetching } from '@tanstack/react-query-no-core' + * + * function GlobalLoadingIndicator() { + * const isFetching = useIsFetching() + * + * return isFetching ? ( + *
Queries are fetching in the background...
+ * ) : null + * } + * ``` + */ +export function useIsFetching( + filters?: Omit, + queryClient?: QueryClient, +): number { + const client = useQueryClient(queryClient) + const queryCache = client.getQueryCache() + + return React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => + queryCache.subscribe(notifyManager.batchCalls(onStoreChange)), + [queryCache], + ), + () => client.isFetching(filters), + () => client.isFetching(filters), + ) +} diff --git a/packages/react-query-no-core/src/useMutation.ts b/packages/react-query-no-core/src/useMutation.ts new file mode 100644 index 00000000000..e0f6adfe1bd --- /dev/null +++ b/packages/react-query-no-core/src/useMutation.ts @@ -0,0 +1,241 @@ +'use client' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import { + MutationObserver, + noop, + notifyManager, + shouldThrowError, +} from './runtime' +import type { DefaultError, QueryClient } from './runtime' +import type { + UseMutateFunction, + UseMutationOptions, + UseMutationResult, +} from './types' + +// HOOK + +/** + * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. + * `useMutation` is the hook for that. + * @param options - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second + * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared + * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks + * fire only for the latest call you've made, and only while the component is still mounted — unmounting before + * the mutation settles removes the subscription and prevents them from firing. + * @throws {Error} The mutation error, when `throwOnError` is `true` or returns `true` for it, so that it is + * thrown to the nearest error boundary. + * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites, or to look + * the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`). + * @example + * ```tsx + * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core' + * + * function AddTodo() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + * }) + * + * return ( + * + * ) + * } + * ``` + * @example + * Rendering the mutation's own state, rather than just firing it off: + * ```tsx + * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core' + * + * function AddTodo() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + * }) + * + * return ( + *
+ * {addMutation.isPending ? ( + * 'Adding todo...' + * ) : ( + * <> + * {addMutation.isError ? ( + *
An error occurred: {addMutation.error.message}
+ * ) : null} + * + * + * )} + *
+ * ) + * } + * ``` + * @example + * Optimistic update via `onMutate`, rolling back on `onError`: + * ```tsx + * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core' + * + * function AddTodo() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onMutate: async (newTodo) => { + * await queryClient.cancelQueries({ queryKey: ['todos'] }) + * const previousTodos = queryClient.getQueryData>(['todos']) + * + * queryClient.setQueryData>(['todos'], (old) => [ + * ...(old ?? []), + * newTodo, + * ]) + * + * // Passed to `onError` as `onMutateResult` if the mutation fails. + * return { previousTodos } + * }, + * onError: (_err, _newTodo, onMutateResult) => { + * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos) + * }, + * onSettled: () => { + * queryClient.invalidateQueries({ queryKey: ['todos'] }) + * }, + * }) + * + * return ( + * + * ) + * } + * ``` + * @example + * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a + * promise per call instead, so you can wait for all of them when they succeed: + * ```tsx + * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core' + * + * function AddTodos() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + * }) + * + * async function handleAddAll(todos: Array) { + * try { + * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo))) + * } catch (error) { + * console.error('Failed to add todos:', error) + * } + * } + * + * return ( + * + * ) + * } + * ``` + * @example + * If some of the mutations above can fail independently of the others, and you want to know which ones + * did — rather than losing that information the moment the first one rejects — swap `Promise.all` for + * `Promise.allSettled`: + * ```tsx + * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core' + * + * function AddTodos() { + * const queryClient = useQueryClient() + * + * const addMutation = useMutation({ + * mutationFn: addTodo, + * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + * }) + * + * async function handleAddAll(todos: Array) { + * const addResults = await Promise.allSettled( + * todos.map((todo) => addMutation.mutateAsync(todo)), + * ) + * + * addResults.forEach((addResult, index) => { + * if (addResult.status === 'rejected') { + * console.error(`Failed to add "${todos[index]}":`, addResult.reason) + * } + * }) + * } + * + * return ( + * + * ) + * } + * ``` + */ +export function useMutation< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + options: UseMutationOptions, + queryClient?: QueryClient, +): UseMutationResult { + const client = useQueryClient(queryClient) + + const [observer] = React.useState( + () => + new MutationObserver( + client, + options, + ), + ) + + React.useEffect(() => { + observer.setOptions(options) + }, [observer, options]) + + const result = React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => + observer.subscribe(notifyManager.batchCalls(onStoreChange)), + [observer], + ), + () => observer.getCurrentResult(), + () => observer.getCurrentResult(), + ) + + const mutate = React.useCallback< + UseMutateFunction + >( + ( + ...args: Parameters< + UseMutateFunction + > + ) => { + observer.mutate(args[0] as TVariables, args[1]).catch(noop) + }, + [observer], + ) + + if ( + result.error && + shouldThrowError(observer.options.throwOnError, [result.error]) + ) { + throw result.error + } + + return { ...result, mutate, mutateAsync: result.mutate } +} diff --git a/packages/react-query-no-core/src/useMutationState.ts b/packages/react-query-no-core/src/useMutationState.ts new file mode 100644 index 00000000000..16851724d31 --- /dev/null +++ b/packages/react-query-no-core/src/useMutationState.ts @@ -0,0 +1,205 @@ +'use client' +import * as React from 'react' +import { useQueryClient } from './QueryClientProvider' +import { notifyManager, replaceEqualDeep } from './runtime' +import type { + Mutation, + MutationCache, + MutationFilters, + MutationState, + QueryClient, +} from './runtime' + +/** + * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending` + * (useful for app-wide loading indicators). + * @param filters - The {@link MutationFilters} to narrow down the matched mutations. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns Will be the `number` of the mutations that your application currently has `pending`. + * @example + * ```tsx + * import { useIsMutating } from '@tanstack/react-query-no-core' + * + * function PostsMutatingIndicator() { + * // How many mutations matching the posts prefix are in progress? + * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] }) + * + * return isMutatingPosts ? Saving posts... : null + * } + * ``` + */ +export function useIsMutating( + filters?: Omit, + queryClient?: QueryClient, +): number { + const client = useQueryClient(queryClient) + return useMutationState( + { filters: { ...filters, status: 'pending' } }, + client, + ).length +} + +type MutationTypeFromResult = [TResult] extends [ + MutationState< + infer TData, + infer TError, + infer TVariables, + infer TOnMutateResult + >, +] + ? Mutation + : Mutation + +type MutationStateOptions< + TResult = MutationState, + TMutation extends Mutation = + MutationTypeFromResult, +> = { + filters?: MutationFilters + select?: (mutation: TMutation) => TResult +} + +/** + * Creates snapshot getters that share equal selected results across renders. + * A new getter is created on each render. Each getter caches its snapshot until the matching mutations + * or their states change. + * @returns A factory for snapshot getters with a shared result cache. + */ +function createSnapshotFactory< + TResult = MutationState, + TMutation extends Mutation = + MutationTypeFromResult, +>() { + let previousResult: Array | undefined + + return ( + mutationCache: MutationCache, + options: MutationStateOptions, + ) => { + let inputs: Array = [] + let snapshot: Array | undefined + + return (): Array => { + const mutations = mutationCache.findAll(options.filters) + const nextInputs = mutations.flatMap((mutation) => [ + mutation, + mutation.state, + ]) + + if ( + !snapshot || + nextInputs.length !== inputs.length || + nextInputs.some((input, index) => !Object.is(input, inputs[index])) + ) { + inputs = nextInputs + snapshot = replaceEqualDeep( + previousResult, + mutations.map( + (mutation): TResult => + (options.select + ? options.select(mutation as TMutation) + : mutation.state) as TResult, + ), + ) + previousResult = snapshot + } + + return snapshot + } + } +} + +/** + * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass + * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation + * state. + * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the + * mutation state. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns Will be an Array of whatever `select` returns for each matching mutation. + * @example + * Get all variables of all running mutations: + * ```tsx + * import { useMutationState } from '@tanstack/react-query-no-core' + * + * function PendingPosts() { + * const pendingVariables = useMutationState({ + * filters: { status: 'pending' }, + * select: (mutation) => mutation.state.variables, + * }) + * + * return <>{pendingVariables.length} posts saving... + * } + * ``` + * @example + * Get all data for specific mutations via the `mutationKey`: + * ```tsx + * import { useMutation, useMutationState } from '@tanstack/react-query-no-core' + * + * const mutationKey = ['posts'] + * + * function Posts() { + * // Some mutation that we want to get the state for + * const mutation = useMutation({ + * mutationKey, + * mutationFn: createPosts, + * }) + * + * const savedPosts = useMutationState({ + * // this mutation key needs to match the mutation key of the given mutation (see above) + * filters: { mutationKey, status: 'success' }, + * select: (mutation) => mutation.state.data, + * }) + * + * return ( + * + * ) + * } + * ``` + * @example + * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new + * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the + * last item that `useMutationState` returns to get the latest successful invocation: + * ```tsx + * import { useMutationState } from '@tanstack/react-query-no-core' + * + * function LatestPost() { + * const savedPosts = useMutationState({ + * filters: { mutationKey: ['posts'], status: 'success' }, + * select: (mutation) => mutation.state.data, + * }) + * + * const latestSavedPost = savedPosts[savedPosts.length - 1] + * + * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'} + * } + * ``` + */ +export function useMutationState< + TResult = MutationState, + TMutation extends Mutation = + MutationTypeFromResult, +>( + options: MutationStateOptions = {}, + queryClient?: QueryClient, +): Array { + const mutationCache = useQueryClient(queryClient).getMutationCache() + const [createSnapshot] = React.useState(() => + createSnapshotFactory(), + ) + const getSnapshot = createSnapshot(mutationCache, options) + + return React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => + mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)), + [mutationCache], + ), + getSnapshot, + getSnapshot, + ) +} diff --git a/packages/react-query-no-core/src/useObserverSnapshot.ts b/packages/react-query-no-core/src/useObserverSnapshot.ts new file mode 100644 index 00000000000..b02245410f1 --- /dev/null +++ b/packages/react-query-no-core/src/useObserverSnapshot.ts @@ -0,0 +1,43 @@ +'use client' +import * as React from 'react' +import { notifyManager } from './runtime/notifyManager' +import { noop } from './runtime/utils' +import type { QueryObserverResultReader } from './runtime/queryObserver' + +interface ObserverStore { + subscribe: (listener: () => void) => () => void +} + +/** + * Commits a reader and subscribes React to its cached snapshots. + * @param observer - The observer that owns the subscription. + * @param reader - The reader scoped to the current render options. + * @param subscribed - Whether this render subscribes to updates. + * @param refresh - Includes updates that occurred before the subscription started. + * @returns The current snapshot. + */ +export function useObserverSnapshot( + observer: TObserver, + reader: QueryObserverResultReader, + subscribed: boolean, + refresh: (observer: TObserver) => void, +): TResult { + React.useEffect(() => { + reader.commit() + }, [reader]) + + return React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => { + const unsubscribe = subscribed + ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) + : noop + refresh(observer) + return unsubscribe + }, + [observer, subscribed, refresh], + ), + reader.getSnapshot, + reader.getSnapshot, + ) +} diff --git a/packages/react-query-no-core/src/usePrefetchInfiniteQuery.tsx b/packages/react-query-no-core/src/usePrefetchInfiniteQuery.tsx new file mode 100644 index 00000000000..666ebf60f2d --- /dev/null +++ b/packages/react-query-no-core/src/usePrefetchInfiniteQuery.tsx @@ -0,0 +1,72 @@ +import { useQueryClient } from './QueryClientProvider' +import { noop } from './runtime' +import type { + DefaultError, + InfiniteData, + QueryClient, + QueryKey, +} from './runtime' +import type { UsePrefetchInfiniteQueryOptions } from './types' + +/** + * `usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render, + * before a suspense boundary that wraps a component that uses `useSuspenseInfiniteQuery`. You can pass + * everything to `usePrefetchInfiniteQuery` that you can pass to `queryClient.infiniteQuery`, though + * `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required. Pass `defaultQueryFn` to use the client defaults. + * + * `getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages, + * as well as pageParam information, and should return a single variable that will be passed to your query + * function as `context.pageParam`. Return `undefined` or `null` to indicate there is no next page available. + * + * The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left + * over from a previous attempt — so calling this on every render is cheap and won't refetch data that's + * already there or already in flight. + * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `queryClient.infiniteQuery`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @example + * ```tsx + * import { Suspense } from 'react' + * import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/react-query-no-core' + * + * const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function App() { + * // Fire the prefetch during render, before the suspense boundary below. + * usePrefetchInfiniteQuery(projectsOptions) + * + * return ( + * Loading projects...}> + * + * + * ) + * } + * ``` + */ +export function usePrefetchInfiniteQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UsePrefetchInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): void { + const client = useQueryClient(queryClient) + + if (!client.getQueryState(options.queryKey)) { + void client.infiniteQuery(options).catch(noop) + } +} diff --git a/packages/react-query-no-core/src/usePrefetchQuery.tsx b/packages/react-query-no-core/src/usePrefetchQuery.tsx new file mode 100644 index 00000000000..8b5971d51de --- /dev/null +++ b/packages/react-query-no-core/src/usePrefetchQuery.tsx @@ -0,0 +1,59 @@ +import { useQueryClient } from './QueryClientProvider' +import { noop } from './runtime' +import type { DefaultError, QueryClient, QueryKey } from './runtime' +import type { UsePrefetchQueryOptions } from './types' + +/** + * `usePrefetchQuery` does not return anything, it should be used just to fire a prefetch during render, before + * a suspense boundary that wraps a component that uses `useSuspenseQuery`. You can pass everything to + * `usePrefetchQuery` that you can pass to `queryClient.query`, though `queryKey` is always required, and + * `queryFn` is required. Pass `defaultQueryFn` to use the client defaults. + * + * The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left + * over from a previous attempt — so calling this on every render is cheap and won't refetch data that's + * already there or already in flight. + * @param options - The {@link UsePrefetchQueryOptions} to use — everything you can pass to `queryClient.query`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @example + * ```tsx + * import { Suspense } from 'react' + * import { usePrefetchQuery } from '@tanstack/react-query-no-core' + * + * function App() { + * // Fire the prefetch during render, before the suspense boundary below. + * usePrefetchQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * return ( + * Loading posts...}> + * + * + * ) + * } + * ``` + */ +export function usePrefetchQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UsePrefetchQueryOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + queryClient?: QueryClient, +): void { + const client = useQueryClient(queryClient) + + if (!client.getQueryState(options.queryKey)) { + void client.query(options).catch(noop) + } +} diff --git a/packages/react-query-no-core/src/useQueries.ts b/packages/react-query-no-core/src/useQueries.ts new file mode 100644 index 00000000000..b855434a110 --- /dev/null +++ b/packages/react-query-no-core/src/useQueries.ts @@ -0,0 +1,480 @@ +'use client' +import * as React from 'react' +import { useIsRestoring } from './IsRestoringProvider' +import { useQueryClient } from './QueryClientProvider' +import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary' +import { + ensurePreventErrorBoundaryRetry, + getHasError, + useClearResetErrorBoundary, +} from './errorBoundaryUtils' +import { QueriesObserver } from './runtime/queriesObserver' +import { useObserverSnapshot } from './useObserverSnapshot' +import type { + DefaultError, + OmitKeyof, + QueriesObserverOptions, + QueriesPlaceholderDataFunction, + QueryClient, + QueryFunction, + QueryKey, + QueryObserverOptions, + ThrowOnError, +} from './runtime' +import type { suspenseQueriesPolicy } from './suspense' +import type { + DefinedUseQueryResult, + UseQueryOptions, + UseQueryResult, +} from './types' + +// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`. +// `placeholderData` function always gets undefined passed +type UseQueryOptionsForUseQueries< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = OmitKeyof< + UseQueryOptions, + 'placeholderData' | 'subscribed' +> & { + placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction +} + +// Avoid TS depth-limit error in case of large array literal +type MAXIMUM_DEPTH = 20 + +// Widen the type of the symbol to enable type inference even if skipToken is not immutable. +type SkipTokenForUseQueries = symbol + +type GetUseQueryOptionsForUseQueries = + // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData } + T extends { + queryFnData: infer TQueryFnData + error?: infer TError + data: infer TData + } + ? UseQueryOptionsForUseQueries + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? UseQueryOptionsForUseQueries + : T extends { data: infer TData; error?: infer TError } + ? UseQueryOptionsForUseQueries + : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData] + T extends [infer TQueryFnData, infer TError, infer TData] + ? UseQueryOptionsForUseQueries + : T extends [infer TQueryFnData, infer TError] + ? UseQueryOptionsForUseQueries + : T extends [infer TQueryFnData] + ? UseQueryOptionsForUseQueries + : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: (data: any) => infer TData + throwOnError?: ThrowOnError + } + ? UseQueryOptionsForUseQueries< + TQueryFnData, + unknown extends TError ? DefaultError : TError, + unknown extends TData ? TQueryFnData : TData, + TQueryKey + > + : // Fallback + UseQueryOptionsForUseQueries + +// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult +type GetDefinedOrUndefinedQueryResult = T extends { + initialData?: infer TInitialData +} + ? unknown extends TInitialData + ? UseQueryResult + : TInitialData extends TData + ? DefinedUseQueryResult + : TInitialData extends () => infer TInitialDataResult + ? unknown extends TInitialDataResult + ? UseQueryResult + : TInitialDataResult extends TData + ? DefinedUseQueryResult + : UseQueryResult + : UseQueryResult + : UseQueryResult + +type GetUseQueryResult = + // Part 1: responsible for mapping explicit type parameter to function result, if object + T extends { queryFnData: any; error?: infer TError; data: infer TData } + ? GetDefinedOrUndefinedQueryResult + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? GetDefinedOrUndefinedQueryResult + : T extends { data: infer TData; error?: infer TError } + ? GetDefinedOrUndefinedQueryResult + : // Part 2: responsible for mapping explicit type parameter to function result, if tuple + T extends [any, infer TError, infer TData] + ? GetDefinedOrUndefinedQueryResult + : T extends [infer TQueryFnData, infer TError] + ? GetDefinedOrUndefinedQueryResult + : T extends [infer TQueryFnData] + ? GetDefinedOrUndefinedQueryResult + : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: (data: any) => infer TData + throwOnError?: ThrowOnError + } + ? GetDefinedOrUndefinedQueryResult< + T, + unknown extends TData ? TQueryFnData : TData, + unknown extends TError ? DefaultError : TError + > + : // Fallback + UseQueryResult + +/** + * The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's + * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements — past that, a tuple falls + * back to a single homogeneous options type. + * + * An opaque array (e.g. `unknown[]`) is returned as-is; a non-tuple array whose element type structurally + * matches a query options object is mapped per-element instead, still inferring each entry individually; any + * other non-tuple array — one whose element type doesn't match the expected options shape — falls back to + * that same homogeneous options type too. + * @template T - The type of the `queries` array as written at the call site. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type QueriesOptions< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseQueryOptionsForUseQueries] + : T extends [infer Head, ...infer Tails] + ? QueriesOptions< + [...Tails], + [...TResults, GetUseQueryOptionsForUseQueries], + [...TDepth, 1] + > + : ReadonlyArray extends T + ? T + : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type! + // use this to infer the param types in the case of Array.map() argument + T extends Array< + UseQueryOptionsForUseQueries< + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryKey + > + > + ? Array< + UseQueryOptionsForUseQueries< + TQueryFnData, + TError, + TData, + TQueryKey + > + > + : // Fallback + Array + +/** + * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each + * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped + * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a + * single homogeneous {@link UseQueryResult} type. + * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type QueriesResults< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseQueryResult] + : T extends [infer Head, ...infer Tails] + ? QueriesResults< + [...Tails], + [...TResults, GetUseQueryResult], + [...TDepth, 1] + > + : { [K in keyof T]: GetUseQueryResult } + +type UseQueriesInput, TCombinedResult> = { + /** + * An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and + * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and + * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData` + * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function. + */ + queries: + | readonly [...QueriesOptions] + | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries }] + /** + * Use this to combine the results of the queries into a single value. The result will be structurally + * shared to be as referentially stable as possible. + */ + combine?: (result: QueriesResults) => TCombinedResult + /** + * Set this to `false` to unsubscribe this observer from updates to the query cache. + * @defaultValue true + */ + subscribed?: boolean +} + +/** + * The `useQueries` hook can be used to fetch a variable number of queries. + * + * The `queries` key accepts an array with query option objects mostly identical to `useQuery` — the top-level + * `subscribed` option isn't accepted per query (see `placeholderData` below for another difference). A custom + * `QueryClient` is supplied once, as `useQueries`' own top-level second argument, rather than per query. + * + * Having the same query key more than once in the array of query objects may cause some data to be shared + * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired + * structure. + * + * The `combine` option can be used to combine the results of the queries into a single value. The result will + * be structurally shared to be as referentially stable as possible. + * @param options - The `queries` array to run, and the optional `combine` and `subscribed` options. + * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context + * will be used. + * @returns The combined result. Without `combine`, this is an array with all the query results, in the same + * order as the input. When `combine` is provided, this is the value returned by `combine` instead. + * @throws {Error} The error of the first query that should be thrown to the nearest error boundary (see + * `throwOnError`). While suspending, it throws a promise instead. + * @remarks The `combine` function only re-runs if it changed referentially, or if any of the query results + * changed. An inlined `combine` function, as shown in the example below, therefore runs on every render — wrap + * it in `useCallback`, or extract it to a stable function reference if it doesn't have any dependencies, to + * avoid that. + * + * Unlike `useQuery`, `useQueries` cannot infer the `data` argument of an _inline_ `select` from its sibling + * `queryFn`. Because `useQueries` infers the type of the whole `queries` array at once, the `select` parameter + * of a query object written inline cannot be contextually typed from that same object's `queryFn`, so it falls + * back to `unknown` — a [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate + * the `select` parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in + * a single object _before_ it reaches `useQueries`, to work around this — see the example below. The same + * limitation applies to {@link useSuspenseQueries}. + * + * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from + * previously rendered queries, because the number of queries can differ between renders. + * @example + * ```tsx + * import { useQueries } from '@tanstack/react-query-no-core' + * + * function Posts({ ids }: { ids: Array }) { + * const postQueries = useQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * staleTime: Infinity, + * })), + * }) + * + * return ( + *
    + * {postQueries.map((query, index) => { + * if (query.isPending) return
  • Loading...
  • + * if (query.isError) return
  • Error: {query.error.message}
  • + * return
  • {query.data.title}
  • + * })} + *
+ * ) + * } + * ``` + * @example + * Combining results into a single value: + * ```tsx + * import { useQueries } from '@tanstack/react-query-no-core' + * + * function Posts({ ids }: { ids: Array }) { + * const { data, isPending, isError } = useQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * })), + * combine: (postQueries) => { + * return { + * data: postQueries.map((query) => query.data), + * isPending: postQueries.some((query) => query.isPending), + * isError: postQueries.some((query) => query.isError), + * } + * }, + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return 'Error loading posts' + * + * return ( + *
    + * {data.map((post) => ( + *
  • {post?.title}
  • + * ))} + *
+ * ) + * } + * ``` + * @example + * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding + * `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is + * resolved before it reaches `useQueries`: + * ```tsx + * import { queryOptions, useQueries } from '@tanstack/react-query-no-core' + * + * const postOptions = (id: number) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function PostTitle({ id }: { id: number }) { + * const [{ data: broken }] = useQueries({ + * queries: [ + * { + * ...postOptions(id), + * // ❌ `data` is `unknown` here + * select: (data) => data.title, + * }, + * ], + * }) + * + * const [{ data: fixed }] = useQueries({ + * queries: [ + * queryOptions({ + * ...postOptions(id), + * // ✅ `data` is `Post` + * select: (data) => data.title, + * }), + * ], + * }) + * + * return

{fixed}

+ * } + * ``` + */ +export function useQueries< + T extends Array, + TCombinedResult = QueriesResults, +>( + options: UseQueriesInput, + queryClient?: QueryClient, +): TCombinedResult { + return useBaseQueries(options, queryClient) +} + +/** + * Reads and subscribes to multiple queries. The dedicated Suspense hook can + * supply a render-time policy. + * @param options - The queries, combiner, and subscription setting. + * @param queryClient - The client to use in place of the nearest provider. + * @param suspense - The policy that prepares and reads queries during render. + * @returns The individual query results or the combined result. + * @throws {Error} The first query error configured to reach the error boundary. + */ +export function useBaseQueries< + T extends Array, + TCombinedResult = QueriesResults, +>( + { queries, ...options }: UseQueriesInput, + queryClient?: QueryClient, + suspense?: typeof suspenseQueriesPolicy, +): TCombinedResult { + const client = useQueryClient(queryClient) + const isRestoring = useIsRestoring() + const errorResetBoundary = useQueryErrorResetBoundary() + const subscribed = options.subscribed !== false + + const defaultedQueries = React.useMemo( + () => + queries.map((opts) => { + const defaultedOptions = client.defaultQueryOptions({ + ...opts, + suspense: !!suspense, + } as QueryObserverOptions) + + // Make sure the results are already in fetching state before subscribing or updating options + defaultedOptions._optimisticResults = isRestoring + ? 'isRestoring' + : subscribed + ? 'optimistic' + : undefined + + return defaultedOptions + }), + [queries, client, isRestoring, subscribed, suspense], + ) + + defaultedQueries.forEach((queryOptions) => { + suspense?.prepare(queryOptions) + const query = client.getQueryCache().get(queryOptions.queryHash) + ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query) + }) + + useClearResetErrorBoundary(errorResetBoundary) + + const [observer] = React.useState( + () => + new QueriesObserver( + client, + defaultedQueries, + options as QueriesObserverOptions, + ), + ) + + const reader = observer.createResultReader( + defaultedQueries, + options as QueriesObserverOptions, + ) + suspense?.readQueries(defaultedQueries, reader, client, errorResetBoundary) + + const results = useObserverSnapshot( + observer, + reader, + !isRestoring && subscribed, + refreshQueries, + ) + + const firstErrorResult = results.find((result, index) => { + const query = defaultedQueries[index] + return ( + query && + getHasError({ + result, + errorResetBoundary, + throwOnError: query.throwOnError, + query: client.getQueryCache().get(query.queryHash), + suspense: query.suspense, + }) + ) + }) + + if (firstErrorResult) { + throw firstErrorResult.error + } + + return reader.combineResult(results) +} + +/** + * Refreshes each query after the group subscribes. + * @param observer - The observer that was subscribed. + */ +function refreshQueries(observer: Pick): void { + observer + .getObservers() + .forEach((queryObserver) => queryObserver.updateResult()) +} diff --git a/packages/react-query-no-core/src/useQuery.ts b/packages/react-query-no-core/src/useQuery.ts new file mode 100644 index 00000000000..445cc456f59 --- /dev/null +++ b/packages/react-query-no-core/src/useQuery.ts @@ -0,0 +1,297 @@ +'use client' +import { QueryObserver } from './runtime' +import { useBaseQuery } from './useBaseQuery' +import type { + DefinedInitialDataOptions, + UndefinedInitialDataOptions, +} from './queryOptions' +import type { DefaultError, QueryClient, QueryKey } from './runtime' +import type { + DefinedUseQueryResult, + UseQueryOptions, + UseQueryResult, +} from './types' + +/** + * This overload is selected when `initialData` is known to be defined, so the resulting `data` is typed as never + * `undefined` (unless a `select` changes `TData` to include `undefined`). At runtime, `data` is still `undefined` + * if `select` throws on its first call. + * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The current query result, typed so that `status` is `success` or `error` (`status` never + * resolves to `pending` in this overload's type, since `initialData` guarantees data upfront). `status` is + * `error` if the query has an error from a fetch that failed after its retries or if `select` threw, and + * `success` otherwise. `isSuccess`/`isError` are derived booleans for convenience. + * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`. + * @example + * ```tsx + * import { useQuery } from '@tanstack/react-query-no-core' + * + * function Posts() { + * // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, + * // so the list stays visible alongside the error. + * const { data, isError, error } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * initialData: [], + * }) + * + * return ( + *
+ * {isError ? Error: {error.message} : null} + *
    + * {data.map((post) =>
  • {post.title}
  • )} + *
+ *
+ * ) + * } + * ``` + */ +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: DefinedInitialDataOptions, + queryClient?: QueryClient, +): DefinedUseQueryResult + +/** + * This overload is selected when `initialData` is omitted, may be `undefined`, or is a function that may + * return `undefined`, so the resulting `data` can be `undefined`. + * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The current query result. `status` is `error` if the query has an error from a fetch that failed + * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns + * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError` + * are derived booleans for convenience. + * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`. + * @example + * ```tsx + * import { useQuery } from '@tanstack/react-query-no-core' + * + * function Posts() { + * const { status, data, error, isFetching } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * if (status === 'pending') return 'Loading...' + * if (status === 'error') return Error: {error.message} + * + * return ( + *
+ *
    + * {data.map((post) => ( + *
  • {post.title}
  • + * ))} + *
+ *
{isFetching ? 'Background Updating...' : ' '}
+ *
+ * ) + * } + * ``` + * @example + * The same query, checking `isPending`/`isError` instead of `status` — pick whichever reads better to you: + * ```tsx + * import { useQuery } from '@tanstack/react-query-no-core' + * + * function Posts() { + * const { isPending, isError, data, error } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
    + * {data.map((post) =>
  • {post.title}
  • )} + *
+ * ) + * } + * ``` + */ +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UndefinedInitialDataOptions, + queryClient?: QueryClient, +): UseQueryResult + +/** + * Fallback overload for options whose `initialData` presence isn't statically known — for example, an + * object typed as {@link UseQueryOptions} rather than an object literal. Prefer one of the other overloads + * when possible, since they infer whether `data` can be `undefined` from `initialData` directly. + * @param options - The {@link UseQueryOptions} to use — everything you can pass to `useQuery`. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The current query result. `status` is `error` if the query has an error from a fetch that failed + * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns + * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError` + * are derived booleans for convenience. + * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`. + * @example + * ```tsx + * import { useQuery } from '@tanstack/react-query-no-core' + * + * function Posts() { + * const { status, data, error, isFetching } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * if (status === 'pending') return 'Loading...' + * if (status === 'error') return Error: {error.message} + * + * return ( + *
+ *
    + * {data.map((post) => ( + *
  • {post.title}
  • + * ))} + *
+ *
{isFetching ? 'Background Updating...' : ' '}
+ *
+ * ) + * } + * ``` + * @example + * `select` derives whatever `data` a component needs from the cached value, without changing what's + * actually stored in the cache — the cache still holds the full `Post[]`, but `data` here is a `number`: + * ```tsx + * import { useQuery } from '@tanstack/react-query-no-core' + * + * function PostCount() { + * const { data, isPending, isError, error } = useQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * select: (posts) => posts.length, + * }) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return {data} posts + * } + * ``` + * @example + * A dependent query, only enabled once `postId` is set — use `isLoading`, not `isPending`, so the + * loading state doesn't show while the query is disabled: + * ```tsx + * import { useQuery } from '@tanstack/react-query-no-core' + * + * function Post({ postId }: { postId: number | undefined }) { + * const { data, isLoading, isError, error } = useQuery({ + * queryKey: ['post', postId], + * queryFn: () => fetchPost(postId!), + * enabled: postId != null, + * }) + * + * if (postId == null) return 'Select a post' + * if (isLoading) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data?.title}

+ * } + * ``` + * @example + * The same dependent query, type safe: `skipToken` disables the query without needing the + * non-null assertion above, since `queryFn` is only ever called when `postId` is defined. + * `refetch` doesn't work while `queryFn` is `skipToken` — use `enabled: false` instead if you + * need to trigger the query manually: + * ```tsx + * import { skipToken, useQuery } from '@tanstack/react-query-no-core' + * + * function Post({ postId }: { postId: number | undefined }) { + * const { data, isLoading, isError, error } = useQuery({ + * queryKey: ['post', postId], + * queryFn: postId != null ? () => fetchPost(postId) : skipToken, + * }) + * + * if (postId == null) return 'Select a post' + * if (isLoading) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data?.title}

+ * } + * ``` + * @example + * Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries + * over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was + * fetched rather than from now: + * ```tsx + * import { useQuery, useQueryClient } from '@tanstack/react-query-no-core' + * + * function Post({ postId }: { postId: number }) { + * const queryClient = useQueryClient() + * + * const { data, isError, error } = useQuery({ + * queryKey: ['post', postId], + * queryFn: () => fetchPost(postId), + * initialData: () => + * queryClient + * .getQueryData>(['posts']) + * ?.find((post) => post.id === postId), + * initialDataUpdatedAt: () => + * queryClient.getQueryState(['posts'])?.dataUpdatedAt, + * }) + * + * if (isError) return Error: {error.message} + * + * return

{data?.title}

+ * } + * ``` + * @example + * Paginated data, keeping the previous page's data visible while the next page loads: + * ```tsx + * import { keepPreviousData, useQuery } from '@tanstack/react-query-no-core' + * import { useState } from 'react' + * + * function Posts() { + * const [page, setPage] = useState(0) + * + * const { data, isPlaceholderData, isError, error } = useQuery({ + * queryKey: ['posts', page], + * queryFn: () => fetchPosts(page), + * placeholderData: keepPreviousData, + * }) + * + * if (isError) return Error: {error.message} + * + * return ( + *
+ *
    + * {data?.map((post) =>
  • {post.title}
  • )} + *
+ * + *
+ * ) + * } + * ``` + */ +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UseQueryOptions, + queryClient?: QueryClient, +): UseQueryResult + +export function useQuery(options: UseQueryOptions, queryClient?: QueryClient) { + return useBaseQuery(options, QueryObserver, queryClient) +} diff --git a/packages/react-query-no-core/src/useSuspenseInfiniteQuery.ts b/packages/react-query-no-core/src/useSuspenseInfiniteQuery.ts new file mode 100644 index 00000000000..1c904b86c77 --- /dev/null +++ b/packages/react-query-no-core/src/useSuspenseInfiniteQuery.ts @@ -0,0 +1,184 @@ +'use client' +import { InfiniteQueryObserver, skipToken } from './runtime' +import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' +import { useBaseQuery } from './useBaseQuery' +import type { + DefaultError, + InfiniteData, + OmitKeyof, + QueryClient, + QueryKey, + QueryObserver, +} from './runtime' +import type { + UseInfiniteQueryOptions, + UseInfiniteQueryResult, + UseSuspenseInfiniteQueryOptions, + UseSuspenseInfiniteQueryResult, +} from './types' + +type SkippableSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, + TPageParam, +> = OmitKeyof< + UseInfiniteQueryOptions, + 'enabled' | 'throwOnError' +> + +/** + * The options for `useSuspenseInfiniteQuery` are the same as for `useInfiniteQuery`, except for `throwOnError` + * and `enabled`. + * + * Caveat: cancellation does not work. + * @param options - The {@link UseSuspenseInfiniteQueryOptions} to use — the same options as `useInfiniteQuery`, minus the ones listed above. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns The same object as `useInfiniteQuery`, except that `data` is guaranteed to be defined, + * `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived flags set + * accordingly). + * @remarks Multiple suspenseful query calls in the same component suspend serially, causing a request + * waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until + * then. There's no way to parallelize multiple infinite queries under Suspense. Also keep in mind that + * imperative fetch calls, such as `fetchNextPage`, may interfere with the default refetch behavior, + * resulting in outdated data. Make sure to call these functions only in response to user actions, or add + * conditions like `hasNextPage && !isFetching`. + * @see {@link useInfiniteQuery} for the non-Suspense version of this hook. + * @example + * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is + * required around ``. A failed background refetch instead continues to render the cached data. + * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseInfiniteQuery, + * } from '@tanstack/react-query-no-core' + * + * function Projects() { + * // `data` is guaranteed to be defined here — no `isPending` check needed. + * const { data, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = + * useSuspenseInfiniteQuery({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * return ( + *
+ *
    + * {data.pages.map((page) => + * page.projects.map((project) =>
  • {project.name}
  • ), + * )} + *
+ * + *
+ * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * Loading projects...}> + * + * + *
+ * )} + *
+ * ) + * } + * ``` + */ +export function useSuspenseInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: UseSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): UseSuspenseInfiniteQueryResult + +/** + * A skipped query does not fetch automatically or suspend. Query errors without cached + * data reach the nearest error boundary. + * @param options - The infinite query options. The query function can be `skipToken`. + * @param queryClient - The client to use. Defaults to the client from the nearest context. + * @returns An infinite query result that can be pending and can have undefined data. + */ +export function useSuspenseInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: SkippableSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): UseInfiniteQueryResult + +export function useSuspenseInfiniteQuery< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +>( + options: SkippableSuspenseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + queryClient?: QueryClient, +): UseInfiniteQueryResult { + const skipped = options.queryFn === skipToken + + return useBaseQuery( + { + ...options, + enabled: !skipped, + throwOnError: defaultThrowOnError, + }, + InfiniteQueryObserver as typeof QueryObserver, + queryClient, + skipped ? undefined : suspenseQueryPolicy, + ) as UseInfiniteQueryResult +} diff --git a/packages/react-query-no-core/src/useSuspenseQueries.ts b/packages/react-query-no-core/src/useSuspenseQueries.ts new file mode 100644 index 00000000000..4d655752ef7 --- /dev/null +++ b/packages/react-query-no-core/src/useSuspenseQueries.ts @@ -0,0 +1,548 @@ +'use client' +import { skipToken } from './runtime' +import { defaultThrowOnError, suspenseQueriesPolicy } from './suspense' +import { useBaseQueries } from './useQueries' +import type { + DefaultError, + OmitKeyof, + QueriesPlaceholderDataFunction, + QueryClient, + QueryFunction, + QueryKey, + ThrowOnError, +} from './runtime' +import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types' + +// `placeholderData` functions in useQueries never receive previous query data. +type UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = OmitKeyof< + UseSuspenseQueryOptions, + 'placeholderData' +> & { + placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction +} + +// Avoid TS depth-limit error in case of large array literal +type MAXIMUM_DEPTH = 20 + +// Widen the type of the symbol to enable type inference even if skipToken is not immutable. +type SkipTokenForUseQueries = symbol + +type GetUseSuspenseQueryOptions = + // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData } + T extends { + queryFnData: infer TQueryFnData + error?: infer TError + data: infer TData + } + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : T extends { data: infer TData; error?: infer TError } + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData] + T extends [infer TQueryFnData, infer TError, infer TData] + ? UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TError, + TData + > + : T extends [infer TQueryFnData, infer TError] + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : T extends [infer TQueryFnData] + ? UseSuspenseQueryOptionsForUseSuspenseQueries + : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: (data: any) => infer TData + throwOnError?: ThrowOnError + } + ? UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TError, + TData, + TQueryKey + > + : T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + throwOnError?: ThrowOnError + } + ? UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TError, + TQueryFnData, + TQueryKey + > + : // Fallback + UseSuspenseQueryOptionsForUseSuspenseQueries + +type GetUseSuspenseQueryResult = + // Part 1: responsible for mapping explicit type parameter to function result, if object + T extends { queryFnData: any; error?: infer TError; data: infer TData } + ? UseSuspenseQueryResult + : T extends { queryFnData: infer TQueryFnData; error?: infer TError } + ? UseSuspenseQueryResult + : T extends { data: infer TData; error?: infer TError } + ? UseSuspenseQueryResult + : // Part 2: responsible for mapping explicit type parameter to function result, if tuple + T extends [any, infer TError, infer TData] + ? UseSuspenseQueryResult + : T extends [infer TQueryFnData, infer TError] + ? UseSuspenseQueryResult + : T extends [infer TQueryFnData] + ? UseSuspenseQueryResult + : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided + T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + select?: (data: any) => infer TData + throwOnError?: ThrowOnError + } + ? UseSuspenseQueryResult< + unknown extends TData ? TQueryFnData : TData, + unknown extends TError ? DefaultError : TError + > + : T extends { + queryFn?: + | QueryFunction + | SkipTokenForUseQueries + throwOnError?: ThrowOnError + } + ? UseSuspenseQueryResult< + TQueryFnData, + unknown extends TError ? DefaultError : TError + > + : // Fallback + UseSuspenseQueryResult + +/** + * The `queries` array accepted by `useSuspenseQueries`. Recursively unwraps each tuple element so every + * entry's `queryFn`/`select` are inferred individually, up to 20 elements — past that, a tuple falls back to + * a single homogeneous {@link UseSuspenseQueryOptions} type. + * + * An opaque array (e.g. `unknown[]`) is returned as-is; a non-tuple array whose element type structurally + * matches a query options object is mapped per-element instead, still inferring each entry individually; any + * other non-tuple array — one whose element type doesn't match the expected options shape — falls back to + * that same homogeneous options type too. + * @template T - The type of the `queries` array as written at the call site. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type SuspenseQueriesOptions< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseSuspenseQueryOptions] + : T extends [infer Head, ...infer Tails] + ? SuspenseQueriesOptions< + [...Tails], + [...TResults, GetUseSuspenseQueryOptions], + [...TDepth, 1] + > + : Array extends T + ? T + : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type! + // use this to infer the param types in the case of Array.map() argument + T extends Array< + UseSuspenseQueryOptionsForUseSuspenseQueries< + infer TQueryFnData, + infer TError, + infer TData, + infer TQueryKey + > + > + ? Array< + UseSuspenseQueryOptionsForUseSuspenseQueries< + TQueryFnData, + TError, + TData, + TQueryKey + > + > + : // Fallback + Array + +/** + * The result type returned by `useSuspenseQueries`, when no `combine` is provided. Mirrors + * {@link SuspenseQueriesOptions}: each tuple element's result type is inferred individually, up to 20 elements. + * A non-tuple array is mapped per-element instead, still inferring each entry individually; only past 20 + * elements does this fall back to a single homogeneous {@link UseSuspenseQueryResult} type. + * @template T - The type of the `queries` array, as inferred by {@link SuspenseQueriesOptions}. + * @template TResults - The internal accumulator that this type builds during recursion. It is not meant + * to be set explicitly. + * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not + * meant to be set explicitly. + */ +export type SuspenseQueriesResults< + T extends Array, + TResults extends Array = [], + TDepth extends ReadonlyArray = [], +> = TDepth['length'] extends MAXIMUM_DEPTH + ? Array + : T extends [] + ? [] + : T extends [infer Head] + ? [...TResults, GetUseSuspenseQueryResult] + : T extends [infer Head, ...infer Tails] + ? SuspenseQueriesResults< + [...Tails], + [...TResults, GetUseSuspenseQueryResult], + [...TDepth, 1] + > + : { [K in keyof T]: GetUseSuspenseQueryResult } + +/** + * The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed` + * option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`. + * @param options - The `queries` array to run in Suspense, and an optional `combine` function. + * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context + * will be used. + * @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be + * defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived + * flags set accordingly). + * + * Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone + * stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid + * this, make sure to set a high enough `staleTime`. Cancellation does not work. + * @example + * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is + * required around ``. A failed background refetch instead continues to render the cached data. + * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-no-core' + * + * function Posts({ ids }: { ids: Array }) { + * // Every result is guaranteed to be defined — no per-query `isPending` check needed. + * const postQueries = useSuspenseQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * })), + * }) + * + * return ( + *
    + * {postQueries.map((query) => ( + *
  • {query.data.title}
  • + * ))} + *
+ * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * Loading posts...}> + * + * + *
+ * )} + *
+ * ) + * } + * ``` + * @example + * Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so + * they fetch in parallel rather than suspending one after another: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-no-core' + * + * function Dashboard() { + * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({ + * queries: [ + * { queryKey: ['users'], queryFn: fetchUsers }, + * { queryKey: ['teams'], queryFn: fetchTeams }, + * { queryKey: ['projects'], queryFn: fetchProjects }, + * ], + * }) + * + * return ( + *
+ * + * + * + *
+ * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * Loading dashboard...}> + * + * + *
+ * )} + *
+ * ) + * } + * ``` + * @example + * `combine`s the results into a single boolean, so `Refresh` only re-renders when that boolean changes, + * not on every individual query update. This overload is the only one that accepts `combine`: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-no-core' + * + * function Refresh() { + * const anyFetching = useSuspenseQueries({ + * queries: [ + * { queryKey: ['users'], queryFn: fetchUsers }, + * { queryKey: ['teams'], queryFn: fetchTeams }, + * ], + * combine: (results) => results.some((result) => result.isFetching), + * }) + * + * return anyFetching ? Refreshing… : null + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * Loading dashboard...}> + * + * + *
+ * )} + *
+ * ) + * } + * ``` + */ +export function useSuspenseQueries< + T extends Array, + TCombinedResult = SuspenseQueriesResults, +>( + options: { + /** + * An array with query option objects identical to `useSuspenseQuery`. + */ + queries: + | readonly [...SuspenseQueriesOptions] + | readonly [...{ [K in keyof T]: GetUseSuspenseQueryOptions }] + /** + * Use this to combine the results of the queries into a single value. The result will be structurally + * shared to be as referentially stable as possible. + */ + combine?: (result: SuspenseQueriesResults) => TCombinedResult + }, + queryClient?: QueryClient, +): TCombinedResult + +/** + * The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed` + * option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`. + * @param options - The `queries` array to run in Suspense, and an optional `combine` function. + * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context + * will be used. + * @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be + * defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived + * flags set accordingly). + * + * Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone + * stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid + * this, make sure to set a high enough `staleTime`. Cancellation does not work. + * @example + * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is + * required around ``. A failed background refetch instead continues to render the cached data. + * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-no-core' + * + * function Posts({ ids }: { ids: Array }) { + * // Every result is guaranteed to be defined — no per-query `isPending` check needed. + * const postQueries = useSuspenseQueries({ + * queries: ids.map((id) => ({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * })), + * }) + * + * return ( + *
    + * {postQueries.map((query) => ( + *
  • {query.data.title}
  • + * ))} + *
+ * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * Loading posts...}> + * + * + *
+ * )} + *
+ * ) + * } + * ``` + * @example + * Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so + * they fetch in parallel rather than suspending one after another: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { + * QueryErrorResetBoundary, + * useSuspenseQueries, + * } from '@tanstack/react-query-no-core' + * + * function Dashboard() { + * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({ + * queries: [ + * { queryKey: ['users'], queryFn: fetchUsers }, + * { queryKey: ['teams'], queryFn: fetchTeams }, + * { queryKey: ['projects'], queryFn: fetchProjects }, + * ], + * }) + * + * return ( + *
+ * + * + * + *
+ * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * Loading dashboard...}> + * + * + *
+ * )} + *
+ * ) + * } + * ``` + */ +export function useSuspenseQueries< + T extends Array, + TCombinedResult = SuspenseQueriesResults, +>( + options: { + /** + * An array with query option objects identical to `useSuspenseQuery`. + */ + queries: readonly [...SuspenseQueriesOptions] + /** + * Use this to combine the results of the queries into a single value. The result will be structurally + * shared to be as referentially stable as possible. + */ + combine?: (result: SuspenseQueriesResults) => TCombinedResult + }, + queryClient?: QueryClient, +): TCombinedResult + +export function useSuspenseQueries(options: any, queryClient?: QueryClient) { + return useBaseQueries( + { + ...options, + queries: options.queries.map((query: any) => { + if (process.env.NODE_ENV !== 'production') { + if (query.queryFn === skipToken) { + console.error('skipToken is not allowed for useSuspenseQueries') + } + } + + return { + ...query, + throwOnError: defaultThrowOnError, + enabled: true, + } + }), + }, + queryClient, + suspenseQueriesPolicy, + ) +} diff --git a/packages/react-query-no-core/src/useSuspenseQuery.ts b/packages/react-query-no-core/src/useSuspenseQuery.ts new file mode 100644 index 00000000000..2a65d67ca5a --- /dev/null +++ b/packages/react-query-no-core/src/useSuspenseQuery.ts @@ -0,0 +1,145 @@ +'use client' +import { QueryObserver, skipToken } from './runtime' +import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' +import { useBaseQuery } from './useBaseQuery' +import type { DefaultError, OmitKeyof, QueryClient, QueryKey } from './runtime' +import type { + UseQueryOptions, + UseQueryResult, + UseSuspenseQueryOptions, + UseSuspenseQueryResult, +} from './types' + +type SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, +> = OmitKeyof< + UseQueryOptions, + 'enabled' | 'throwOnError' +> + +/** + * Runs a query with Suspense. The options match those of `useQuery` except for `throwOnError` and `enabled`. + * + * Caveat: cancellation does not work. + * @param options - The {@link UseSuspenseQueryOptions} for a query that always runs. + * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will + * be used. + * @returns A result with data of type `TData` and a status of `success` or `error`. + * @remarks Multiple `useSuspenseQuery` calls in the same component suspend serially, causing a request + * waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until then. + * Use {@link useSuspenseQueries} instead when you have more than one suspenseful query in a component, so they + * fetch in parallel. + * @example + * The query error is thrown if the fetch fails and no cached data exists yet, so an error boundary is + * required around ``. A failed background refetch instead continues to render the cached data. + * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: + * ```tsx + * import { Suspense } from 'react' + * import { ErrorBoundary } from 'react-error-boundary' + * import { QueryErrorResetBoundary, useSuspenseQuery } from '@tanstack/react-query-no-core' + * + * function Posts() { + * // `data` is guaranteed to be defined here — no `isPending` check needed. + * const { data, isFetching } = useSuspenseQuery({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * }) + * + * return ( + *
+ *

Posts {isFetching ? '(refreshing...)' : null}

+ *
    + * {data.map((post) => ( + *
  • {post.title}
  • + * ))} + *
+ *
+ * ) + * } + * + * function App() { + * return ( + * + * {({ reset }) => ( + * ( + *
+ * There was an error! + * + *
+ * )} + * > + * Loading posts...}> + * + * + *
+ * )} + *
+ * ) + * } + * ``` + */ +export function useSuspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UseSuspenseQueryOptions, + queryClient?: QueryClient, +): UseSuspenseQueryResult + +/** + * Pass `skipToken` as `queryFn` to skip the query. While skipped, the query can read cached data + * but does not fetch automatically or suspend. Query errors without cached data reach the nearest error boundary. + * Pass a query function to resume normal Suspense behavior. + * @param options - Options for a query that can be skipped. + * @param queryClient - The client to use. Defaults to the client from the nearest context. + * @returns A result whose data can be undefined and whose status can be `pending`. + */ +export function useSuspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey + >, + queryClient?: QueryClient, +): UseQueryResult + +export function useSuspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey + >, + queryClient?: QueryClient, +): UseQueryResult { + const skipped = options.queryFn === skipToken + + return useBaseQuery( + { + ...options, + enabled: !skipped, + throwOnError: defaultThrowOnError, + }, + QueryObserver, + queryClient, + skipped ? undefined : suspenseQueryPolicy, + ) +} diff --git a/packages/react-query-no-core/tsconfig.json b/packages/react-query-no-core/tsconfig.json new file mode 100644 index 00000000000..4ad3357ad95 --- /dev/null +++ b/packages/react-query-no-core/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "outDir": "./dist-ts", + "rootDir": ".", + "jsx": "react-jsx" + }, + "include": [ + "src", + "test-setup.ts", + "*.config.ts", + "*.config.js", + "package.json" + ] +} diff --git a/packages/react-query-no-core/tsconfig.legacy.json b/packages/react-query-no-core/tsconfig.legacy.json new file mode 100644 index 00000000000..20f2156d95b --- /dev/null +++ b/packages/react-query-no-core/tsconfig.legacy.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "jsx": "react-jsx", + "outDir": "./dist-ts/legacy" + }, + "include": ["src"], + "exclude": ["src/__tests__"] +} diff --git a/packages/react-query-no-core/tsconfig.prod.json b/packages/react-query-no-core/tsconfig.prod.json new file mode 100644 index 00000000000..2bb29fdf02a --- /dev/null +++ b/packages/react-query-no-core/tsconfig.prod.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "incremental": false, + "composite": false, + "rootDir": "../../" + }, + "include": ["src"], + "exclude": ["src/__tests__"] +} diff --git a/packages/react-query-no-core/tsdown.config.ts b/packages/react-query-no-core/tsdown.config.ts new file mode 100644 index 00000000000..f5cddcb4317 --- /dev/null +++ b/packages/react-query-no-core/tsdown.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'tsdown' +import { getTsdownConfig } from './root.tsdown.config.js' + +export default defineConfig({ + ...getTsdownConfig({ entry: ['src/index.ts'] }), + // Keep React client directives on the hooks and providers that own them. + unbundle: true, +}) diff --git a/packages/react-query/src/__tests__/mutationOptions.test.tsx b/packages/react-query/src/__tests__/mutationOptions.test.tsx index be363462832..4cc045f532c 100644 --- a/packages/react-query/src/__tests__/mutationOptions.test.tsx +++ b/packages/react-query/src/__tests__/mutationOptions.test.tsx @@ -1,8 +1,7 @@ -import { QueryClient } from '@tanstack/query-core' import { createKey, sleep } from '@tanstack/query-test-utils' import { fireEvent } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { useIsMutating, useMutation, useMutationState } from '..' +import { QueryClient, useIsMutating, useMutation, useMutationState } from '..' import { mutationOptions } from '../mutationOptions' import { renderWithClient } from './utils' import type { UseMutationOptions } from '../types' diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 65452fc2569..c2447abf304 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7258,6 +7258,28 @@ importers: specifier: ^6.0.3 version: 6.0.3 + integrations/react/bundle-size: + dependencies: + '@tanstack/react-query': + specifier: workspace:* + version: link:../../../packages/react-query + '@tanstack/react-query-no-core': + specifier: workspace:* + version: link:../../../packages/react-query-no-core + '@tanstack/react-query-no-core-pluggable': + specifier: workspace:* + version: link:../../../packages/react-query-no-core-pluggable + react: + specifier: 'catalog:' + version: 19.3.1 + react-dom: + specifier: 'catalog:' + version: 19.3.1(react@19.3.1) + devDependencies: + vite: + specifier: ^8.3.8 + version: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) + integrations/react/next-14: dependencies: '@tanstack/react-query': @@ -7347,9 +7369,21 @@ importers: integrations/react/nodenext: dependencies: + '@tanstack/query-core': + specifier: workspace:* + version: link:../../../packages/query-core + '@tanstack/query-types': + specifier: workspace:* + version: link:../../../packages/query-types '@tanstack/react-query': specifier: workspace:* version: link:../../../packages/react-query + '@tanstack/react-query-no-core': + specifier: workspace:* + version: link:../../../packages/react-query-no-core + '@tanstack/react-query-no-core-pluggable': + specifier: workspace:* + version: link:../../../packages/react-query-no-core-pluggable devDependencies: '@types/react': specifier: ^19.3.0 @@ -7997,6 +8031,10 @@ importers: version: 17.4.0(@babel/preset-env@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(supports-color@10.2.2) packages/query-core: + dependencies: + '@tanstack/query-types': + specifier: workspace:* + version: link:../query-types devDependencies: '@tanstack/query-test-utils': specifier: workspace:* @@ -8074,6 +8112,12 @@ importers: specifier: 'catalog:' version: 6.0.3 + packages/query-types: + devDependencies: + typescript: + specifier: 'catalog:' + version: 6.0.3 + packages/react-query: dependencies: '@tanstack/query-core': @@ -8178,6 +8222,62 @@ importers: specifier: 'catalog:' version: 6.0.3 + packages/react-query-no-core: + dependencies: + '@tanstack/query-types': + specifier: workspace:* + version: link:../query-types + devDependencies: + '@eslint-react/eslint-plugin': + specifier: 'catalog:' + version: 5.28.8(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3) + '@types/react': + specifier: ^19.3.0 + version: 19.3.0 + eslint-plugin-react-hooks: + specifier: 'catalog:' + version: 7.1.1(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2) + react: + specifier: 'catalog:' + version: 19.3.1 + typescript: + specifier: 'catalog:' + version: 6.0.3 + + packages/react-query-no-core-pluggable: + dependencies: + '@tanstack/query-types': + specifier: workspace:* + version: link:../query-types + devDependencies: + '@eslint-react/eslint-plugin': + specifier: 'catalog:' + version: 5.28.8(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3) + '@testing-library/react': + specifier: 'catalog:' + version: 16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + '@testing-library/react-render-stream': + specifier: ^2.0.2 + version: 2.0.2(@jest/globals@30.3.0(supports-color@10.2.2))(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(expect@30.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(supports-color@10.2.2) + '@types/react': + specifier: ^19.3.0 + version: 19.3.0 + '@vitejs/plugin-react': + specifier: 'catalog:' + version: 6.2.1(babel-plugin-react-compiler@1.0.0)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + eslint-plugin-react-hooks: + specifier: 'catalog:' + version: 7.1.1(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2) + react: + specifier: 'catalog:' + version: 19.3.1 + react-dom: + specifier: 'catalog:' + version: 19.3.1(react@19.3.1) + typescript: + specifier: 'catalog:' + version: 6.0.3 + packages/react-query-persist-client: dependencies: '@tanstack/query-persist-client-core': diff --git a/scripts/react-query-compat.config.ts b/scripts/react-query-compat.config.ts new file mode 100644 index 00000000000..dcd25642d5d --- /dev/null +++ b/scripts/react-query-compat.config.ts @@ -0,0 +1,34 @@ +import { basename, join, resolve } from 'node:path' +import { defineConfig } from 'vitest/config' +import core from '../packages/query-core/vite.config.ts' +import react from '../packages/react-query/vite.config.ts' + +const adapter = process.env.REACT_QUERY_COMPAT_ADAPTER! +const suite = basename(resolve(process.cwd(), '../..')) +const isReact = suite === 'react-query' + +const base = isReact ? react : core + +export default defineConfig({ + ...base, + resolve: { + ...base.resolve, + alias: { '@tanstack/query-core': join(adapter, 'src/runtime/index.ts') }, + }, + test: { + ...base.test, + name: `${basename(adapter)}/${suite}`, + // Override the relative paths inherited from the upstream project. + setupFiles: isReact + ? [resolve(import.meta.dirname, '../packages/react-query/test-setup.ts')] + : [], + coverage: { + ...base.test?.coverage, + include: [ + join(adapter, isReact ? 'src/*.{ts,tsx}' : 'src/runtime/**/*.ts'), + ], + reportsDirectory: join(adapter, 'coverage', suite), + allowExternal: true, + }, + }, +}) diff --git a/scripts/test-react-query-compat.mjs b/scripts/test-react-query-compat.mjs new file mode 100644 index 00000000000..52d7bd0510a --- /dev/null +++ b/scripts/test-react-query-compat.mjs @@ -0,0 +1,91 @@ +// Run the original runtime and type suites against each adapter. The temporary +// projects preserve the suites' relative imports without duplicating test cases. +import { execFileSync } from 'node:child_process' +import { + cpSync, + mkdirSync, + mkdtempSync, + readdirSync, + rmSync, + writeFileSync, +} from 'node:fs' +import { createRequire } from 'node:module' +import { basename, join, relative, resolve, sep } from 'node:path' + +const adapter = process.cwd() +const repository = resolve(import.meta.dirname, '..') +const require = createRequire(import.meta.url) +const core = join(adapter, 'src/runtime/index.ts') +const pluggable = basename(adapter) === 'react-query-no-core-pluggable' +const fixture = join(adapter, 'tests/compat-client.ts') +function importPath(from, to) { + return './' + relative(from, to).split(sep).join('/') +} + +for (const suite of ['query-core', 'react-query']) { + const upstream = join(repository, 'packages', suite) + const cache = join(upstream, '.cache') + mkdirSync(cache, { recursive: true }) + const project = mkdtempSync(join(cache, 'compat-')) + try { + const source = join(project, 'src') + const implementation = + suite === 'query-core' + ? join(adapter, 'src/runtime') + : join(adapter, 'src') + cpSync(join(upstream, 'src/__tests__'), join(source, '__tests__'), { + recursive: true, + }) + + if (pluggable && suite === 'query-core') { + const tests = join(source, '__tests__') + writeFileSync( + join(tests, 'clientOptions.ts'), + `export type { AdapterClientOptions } from '${importPath(tests, fixture)}'\n`, + ) + } + + for (const file of readdirSync(implementation, { withFileTypes: true })) { + if (!file.isFile() || !/\.tsx?$/.test(file.name)) continue + const target = importPath(source, join(implementation, file.name)) + let exports = `export * from '${target}'\n` + if (pluggable && ['index.ts', 'queryClient.ts'].includes(file.name)) { + const client = importPath(source, fixture) + exports += `export { QueryClient } from '${client}'\n` + } + writeFileSync(join(source, file.name), exports) + } + + const setup = join(repository, 'packages/react-query/test-setup.ts') + const tsconfig = { + extends: join(adapter, 'tsconfig.json'), + compilerOptions: { + rootDir: repository, + composite: false, + incremental: false, + emitDeclarationOnly: false, + noEmit: true, + paths: { '@tanstack/query-core': [core] }, + }, + include: suite === 'react-query' ? ['src', setup] : ['src'], + } + writeFileSync(join(project, 'tsconfig.json'), JSON.stringify(tsconfig)) + execFileSync( + process.execPath, + [ + join(require.resolve('vitest/package.json'), '../vitest.mjs'), + 'run', + '--config', + join(import.meta.dirname, 'react-query-compat.config.ts'), + ...process.argv.slice(2), + ], + { + cwd: project, + stdio: 'inherit', + env: { ...process.env, REACT_QUERY_COMPAT_ADAPTER: adapter }, + }, + ) + } finally { + rmSync(project, { recursive: true, force: true }) + } +} From e5573d6b44e6702674508a75216df06ddd687661 Mon Sep 17 00:00:00 2001 From: Jonghyeon Ko Date: Fri, 27 Nov 2026 19:34:28 +0900 Subject: [PATCH 02/11] test(react-query): exercise all six measured apps in Chromium --- .github/workflows/react-query-bundle-size.yml | 6 + integrations/react/bundle-size/README.md | 11 ++ .../react/bundle-size/browser/apps.test.js | 48 +++++ integrations/react/bundle-size/measure.mjs | 31 ++- integrations/react/bundle-size/package.json | 10 +- .../bundle-size/vitest.browser.config.js | 17 ++ pnpm-lock.yaml | 181 ++++++++++++++++-- 7 files changed, 283 insertions(+), 21 deletions(-) create mode 100644 integrations/react/bundle-size/browser/apps.test.js create mode 100644 integrations/react/bundle-size/vitest.browser.config.js diff --git a/.github/workflows/react-query-bundle-size.yml b/.github/workflows/react-query-bundle-size.yml index b5ccaef0704..5b8e3b12bbd 100644 --- a/.github/workflows/react-query-bundle-size.yml +++ b/.github/workflows/react-query-bundle-size.yml @@ -43,6 +43,12 @@ jobs: 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 exec playwright install --with-deps --only-shell chromium + - name: Exercise production apps in Chromium + working-directory: integrations/react/bundle-size + run: pnpm run test:browser comment: if: github.event.pull_request.head.repo.full_name == github.repository needs: measure diff --git a/integrations/react/bundle-size/README.md b/integrations/react/bundle-size/README.md index d95d0412680..cfebd71372c 100644 --- a/integrations/react/bundle-size/README.md +++ b/integrations/react/bundle-size/README.md @@ -10,3 +10,14 @@ pnpm --filter @tanstack/query-integration-react-bundle-size run measure ``` The report at `integrations/react/bundle-size/dist/report.md` shows total emitted JavaScript bytes and the sum of individually compressed chunks for gzip and Brotli. Each percentage uses the original adapter’s application size for that workload as its denominator. Serve a directory under `dist//` to try the built app. + +Run the six production app scenarios 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/browser/apps.test.js b/integrations/react/bundle-size/browser/apps.test.js new file mode 100644 index 00000000000..b55101473da --- /dev/null +++ b/integrations/react/bundle-size/browser/apps.test.js @@ -0,0 +1,48 @@ +import { afterEach, describe, expect, it } from 'vitest' + +const adapters = [ + 'react-query', + 'react-query-no-core', + 'react-query-no-core-pluggable', +] + +async function openApp(scenario, adapter) { + const frame = document.createElement('iframe') + frame.title = adapter + frame.src = `/${scenario}/${adapter}/index.html` + document.body.append(frame) + await expect + .poll(() => frame.contentDocument?.querySelector('li')?.textContent) + .toContain('Middlemarch') + return frame.contentDocument +} + +afterEach(() => { + document.querySelector('iframe')?.remove() + localStorage.removeItem('bookmark') +}) + +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', + ) + more.click() + await expect.poll(() => app.querySelectorAll('li').length).toBe(4) + const third = app.querySelectorAll('li')[2] + expect(third.textContent).toContain('Villette') + third.querySelector('button').click() + await expect + .poll(() => app.body.textContent) + .toContain('Bookmarked: Villette') + expect(localStorage.getItem('bookmark')).toBe('Villette') + }) +}) diff --git a/integrations/react/bundle-size/measure.mjs b/integrations/react/bundle-size/measure.mjs index 832a2cf0819..e1b8647b82f 100644 --- a/integrations/react/bundle-size/measure.mjs +++ b/integrations/react/bundle-size/measure.mjs @@ -48,16 +48,39 @@ async function measure(packageName, screen) { if (!chunks.some((chunk) => chunk.isEntry)) { throw new Error(`Missing browser entry chunk for ${packageName}`) } + const modules = chunks.flatMap((chunk) => + Object.entries(chunk.modules) + .filter(([, module]) => module.renderedLength > 0) + .map(([id]) => id), + ) + if ( + modules.some((id) => + /\/(?:packages|node_modules\/@tanstack)\/query-types\//.test(id), + ) + ) { + throw new Error( + `${packageName} shipped runtime code from @tanstack/query-types`, + ) + } if ( packageName !== baseline && - chunks.some((chunk) => - Object.keys(chunk.modules).some((id) => - /\/(?:packages|node_modules\/@tanstack)\/query-core\//.test(id), - ), + modules.some((id) => + /\/(?:packages|node_modules\/@tanstack)\/query-core\//.test(id), ) ) { throw new Error(`${packageName} bundled @tanstack/query-core`) } + if ( + packageName === pluggable && + screen === 'query' && + modules.some((id) => + /\/runtime\/(mutation|mutationCache|infiniteQueryBehavior)\.js$/.test(id), + ) + ) { + throw new Error( + 'The query-only client bundled an optional plugin implementation', + ) + } const sizes = { raw: 0, gzip: 0, brotli: 0 } for (const chunk of chunks) { diff --git a/integrations/react/bundle-size/package.json b/integrations/react/bundle-size/package.json index 08a97f91b07..a2dd970377e 100644 --- a/integrations/react/bundle-size/package.json +++ b/integrations/react/bundle-size/package.json @@ -3,7 +3,9 @@ "private": true, "type": "module", "scripts": { - "measure": "node measure.mjs" + "measure": "node measure.mjs", + "test:browser": "vitest run --config vitest.browser.config.js", + "test:browser:ui": "vitest --watch --ui --config vitest.browser.config.js" }, "dependencies": { "@tanstack/react-query": "workspace:*", @@ -13,6 +15,10 @@ "react-dom": "catalog:" }, "devDependencies": { - "vite": "^8.3.8" + "@vitest/browser-playwright": "5.0.5", + "@vitest/ui": "5.0.5", + "playwright": "1.65.1", + "vite": "^8.3.8", + "vitest": "^5.0.5" } } diff --git a/integrations/react/bundle-size/vitest.browser.config.js b/integrations/react/bundle-size/vitest.browser.config.js new file mode 100644 index 00000000000..df04aa0d4ad --- /dev/null +++ b/integrations/react/bundle-size/vitest.browser.config.js @@ -0,0 +1,17 @@ +import { playwright } from '@vitest/browser-playwright' +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + root: import.meta.dirname, + // Serve the six measured apps from disk, including their production JS chunks. + publicDir: 'dist', + test: { + include: ['browser/*.test.js'], + browser: { + enabled: true, + headless: true, + provider: playwright(), + instances: [{ browser: 'chromium' }], + }, + }, +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c2447abf304..6d2631c6732 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -406,7 +406,7 @@ importers: version: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) vitest: specifier: ^5.0.5 - version: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + version: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) examples/angular/auto-refetching: dependencies: @@ -7276,9 +7276,21 @@ importers: specifier: 'catalog:' version: 19.3.1(react@19.3.1) devDependencies: + '@vitest/browser-playwright': + specifier: 5.0.5 + version: 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.5) + '@vitest/ui': + specifier: 5.0.5 + version: 5.0.5(vitest@5.0.5) + playwright: + specifier: 1.65.1 + version: 1.65.1 vite: specifier: ^8.3.8 version: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) + vitest: + specifier: ^5.0.5 + version: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) integrations/react/next-14: dependencies: @@ -7808,7 +7820,7 @@ importers: version: 5.1.4(supports-color@10.2.2)(typescript@6.0.3)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) vitest: specifier: ^5.0.5 - version: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + version: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) zone.js: specifier: ^0.16.0 version: 0.16.1 @@ -8106,7 +8118,7 @@ importers: dependencies: vitest: specifier: ^5.0.5 - version: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + version: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) devDependencies: typescript: specifier: 'catalog:' @@ -9772,6 +9784,9 @@ packages: resolution: {integrity: sha512-eBREGwDHRPHtdsg44t071GE2KRDEuJrf0J2uT5/qvJPB2+pfPZOKlx93dMZOFkE7QW5G0JWoczySD7a01Jf0iw==} engines: {node: ^22.18.0 || >=24.11.0} + '@blazediff/core@1.10.0': + resolution: {integrity: sha512-AOQff0zgR7cGsZL+4E7hVkmujoPUpm0J9xzWGWZj5wCjd3gmxESXAPfKyuzs93VdpQNFhHlBhfOjrcZ+XTERtQ==} + '@bomb.sh/tab@0.0.19': resolution: {integrity: sha512-dTRfo9Q9B+lbLG3JCu8a/AGQSfD2XXcFcnakQzVjSOX+VvR/s9zpsH8TlqV3iHqazniRn1Ypwd1hcRlXcu/4BA==} hasBin: true @@ -15339,6 +15354,17 @@ packages: vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0 vue: ^3.2.25 || ^3.6.0-rc.10 + '@vitest/browser-playwright@5.0.5': + resolution: {integrity: sha512-lcdThFUUcMV9mGGV1SUiZXPxfjgW4CssA7o3STxzh8WK0tT2r526kc12tZIBRZfoLMwkhxjLmMXkWXONzdsDQw==} + peerDependencies: + playwright: '*' + vitest: 5.0.5 + + '@vitest/browser@5.0.5': + resolution: {integrity: sha512-IDMoZX/iZ8rkilw7weaSgN8tJ7iZ9hUv0wYoKXyiyjWjWFwLSWAY707DcVTgxTYOudWC1E3HA9LYn7kVa9a7uQ==} + peerDependencies: + vitest: 5.0.5 + '@vitest/coverage-istanbul@5.0.5': resolution: {integrity: sha512-nmbE0+e1JSH9kYEoHGp/iKCQq6+TqwvQ4EcH2zKPULOIrY7rPHxDHsipYGGr+0xMDdzCy46F8zj3edz8dsqvdg==} peerDependencies: @@ -15387,9 +15413,20 @@ packages: vite: optional: true + '@vitest/pretty-format@5.0.5': + resolution: {integrity: sha512-24sSdIlMA9DVPXnYiB9siwU0bTd887Y9jX3+vabztCSsvHwo7ipvJ/a2L3Rljw8+2rK1f5fCj3h5U9I/Jsqgbw==} + '@vitest/spy@5.0.5': resolution: {integrity: sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==} + '@vitest/ui@5.0.5': + resolution: {integrity: sha512-dCoGUOdgmCaSB2g+WQ/spPCBkytAWdNUkFSXY4z+eYp2d8JEOY8v0uDRaJTG9qf/kTlTVZ4CuYMYMz/f1HS/qQ==} + peerDependencies: + vitest: 5.0.5 + + '@vitest/utils@5.0.5': + resolution: {integrity: sha512-/rBu7gzLDQI/SC79Tn98b5DwOgaHU/Gt4I9OVeP3YofzNaYtbImRCOJQmT1S6vOJg9gEIlWC+r3QxKkjuSa1nQ==} + '@volar/kit@2.4.28': resolution: {integrity: sha512-cKX4vK9dtZvDRaAzeoUdaAJEew6IdxHNCRrdp5Kvcl6zZOqb6jTOfk3kXkIkG3T7oTFXguEMt5+9ptyqYR84Pg==} peerDependencies: @@ -18058,8 +18095,8 @@ packages: resolution: {integrity: sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==} hasBin: true - flatted@3.4.2: - resolution: {integrity: sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==} + flatted@3.4.4: + resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} flattie@1.1.1: resolution: {integrity: sha512-9UbaD6XdAL97+k/n+N7JwX46K/M6Zc6KcFYskrYL8wbBV/Uyk0CTAMY0VT+qiK5PM7AIc9aTWYtq65U7T+aCNQ==} @@ -20540,6 +20577,16 @@ packages: pkg-types@2.4.0: resolution: {integrity: sha512-07Fys7iVx0X6TcviMOgogM1Lk33ZyqOezMnU79S+kffWqwolG/5W9V8EgQSeYCIfFTYVgssRbnH630Oa2+soBA==} + playwright-core@1.65.1: + resolution: {integrity: sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==} + engines: {node: '>=20'} + hasBin: true + + playwright@1.65.1: + resolution: {integrity: sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==} + engines: {node: '>=20'} + hasBin: true + plist@3.1.0: resolution: {integrity: sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==} engines: {node: '>=10.4.0'} @@ -20552,6 +20599,10 @@ packages: resolution: {integrity: sha512-NCrCHhWmnQklfH4MtJMRjZ2a8c80qXeMlQMv2uVp9ISJMTt562SbGd6n2oq0PaPgKm7Z6pL9E2UlLIhC+SHL3w==} engines: {node: '>=4.0.0'} + pngjs@7.0.0: + resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==} + engines: {node: '>=14.19.0'} + possible-typed-array-names@1.1.0: resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} engines: {node: '>= 0.4'} @@ -23848,7 +23899,7 @@ snapshots: postcss: 8.5.32 rollup: 4.65.1 tailwindcss: 4.3.3 - vitest: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) transitivePeerDependencies: - '@types/node' - '@vitejs/devtools' @@ -23912,7 +23963,7 @@ snapshots: postcss: 8.5.32 rollup: 4.65.1 tailwindcss: 4.3.3 - vitest: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) transitivePeerDependencies: - '@types/node' - '@vitejs/devtools' @@ -25402,6 +25453,8 @@ snapshots: '@babel/helper-string-parser': 8.1.3 '@babel/helper-validator-identifier': 8.0.6 + '@blazediff/core@1.10.0': {} + '@bomb.sh/tab@0.0.19(cac@6.7.14)(citty@0.2.2)': optionalDependencies: cac: 6.7.14 @@ -31945,7 +31998,7 @@ snapshots: svelte: 5.57.1(@typescript-eslint/types@8.72.2) optionalDependencies: vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0) - vitest: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) '@tsconfig/svelte@5.0.8': {} @@ -32657,6 +32710,70 @@ snapshots: vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) vue: 3.5.44(typescript@6.0.3) + '@vitest/browser-playwright@5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vitest@5.0.5)': + dependencies: + '@vitest/browser': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vitest@5.0.5) + '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + playwright: 1.65.1 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + optional: true + + '@vitest/browser-playwright@5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.5)': + dependencies: + '@vitest/browser': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.5) + '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + playwright: 1.65.1 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + + '@vitest/browser@5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vitest@5.0.5)': + dependencies: + '@blazediff/core': 1.10.0 + '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + '@vitest/ui': 5.0.5(vitest@5.0.5) + '@vitest/utils': 5.0.5 + magic-string: 1.4.5 + pngjs: 7.0.0 + sirv: 3.0.2 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + ws: 8.22.1 + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + optional: true + + '@vitest/browser@5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.5)': + dependencies: + '@blazediff/core': 1.10.0 + '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + '@vitest/ui': 5.0.5(vitest@5.0.5) + '@vitest/utils': 5.0.5 + magic-string: 1.4.5 + pngjs: 7.0.0 + sirv: 3.0.2 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) + ws: 8.22.1 + transitivePeerDependencies: + - bufferutil + - msw + - utf-8-validate + - vite + '@vitest/coverage-istanbul@5.0.5(vitest@5.0.5)': dependencies: '@jridgewell/gen-mapping': 0.3.13 @@ -32668,7 +32785,7 @@ snapshots: magicast: 0.5.5 obug: 3.0.0 tinyrainbow: 3.2.0 - vitest: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) '@vitest/eslint-plugin@1.6.28(@typescript-eslint/eslint-plugin@8.72.2(@typescript-eslint/parser@8.72.2(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3)(vitest@5.0.5)': dependencies: @@ -32678,7 +32795,7 @@ snapshots: optionalDependencies: '@typescript-eslint/eslint-plugin': 8.72.2(@typescript-eslint/parser@8.72.2(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3))(eslint@9.39.5(jiti@2.7.0)(supports-color@7.2.0))(supports-color@7.2.0)(typescript@6.0.3) typescript: 6.0.3 - vitest: 5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) transitivePeerDependencies: - supports-color @@ -32722,8 +32839,28 @@ snapshots: msw: 2.15.0(@types/node@24.19.2)(typescript@6.0.3) vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) + '@vitest/pretty-format@5.0.5': + dependencies: + tinyrainbow: 3.2.0 + '@vitest/spy@5.0.5': {} + '@vitest/ui@5.0.5(vitest@5.0.5)': + dependencies: + '@vitest/utils': 5.0.5 + fflate: 0.8.3 + flatted: 3.4.4 + pathe: 2.0.3 + sirv: 3.0.2 + tinyrainbow: 3.2.0 + vitest: 5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + + '@vitest/utils@5.0.5': + dependencies: + '@vitest/pretty-format': 5.0.5 + convert-source-map: 2.0.0 + tinyrainbow: 3.2.0 + '@volar/kit@2.4.28(typescript@6.0.3)': dependencies: '@volar/language-service': 2.4.28(typescript@6.0.3) @@ -36021,12 +36158,12 @@ snapshots: flat-cache@4.0.1: dependencies: - flatted: 3.4.2 + flatted: 3.4.4 keyv: 4.5.4 flat@5.0.2: {} - flatted@3.4.2: {} + flatted@3.4.4: {} flattie@1.1.1: {} @@ -40571,6 +40708,12 @@ snapshots: exsolve: 1.1.3 pathe: 2.0.3 + playwright-core@1.65.1: {} + + playwright@1.65.1: + dependencies: + playwright-core: 1.65.1 + plist@3.1.0: dependencies: '@xmldom/xmldom': 0.8.15 @@ -40581,6 +40724,8 @@ snapshots: pngjs@3.4.0: {} + pngjs@7.0.0: {} + possible-typed-array-names@1.1.0: {} postcss-calc@10.1.1(postcss@8.5.32): @@ -43618,7 +43763,7 @@ snapshots: optionalDependencies: vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) - vitest@5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): + vitest@5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): dependencies: '@types/chai': 5.2.3 '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) @@ -43636,13 +43781,15 @@ snapshots: why-is-node-running: 3.2.1 optionalDependencies: '@types/node': 24.19.2 + '@vitest/browser-playwright': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vitest@5.0.5) '@vitest/coverage-istanbul': 5.0.5(vitest@5.0.5) + '@vitest/ui': 5.0.5(vitest@5.0.5) jsdom: 27.4.0(supports-color@10.2.2) transitivePeerDependencies: - msw optional: true - vitest@5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)): + vitest@5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@10.2.2))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)): dependencies: '@types/chai': 5.2.3 '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) @@ -43660,12 +43807,14 @@ snapshots: why-is-node-running: 3.2.1 optionalDependencies: '@types/node': 24.19.2 + '@vitest/browser-playwright': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.0.5) '@vitest/coverage-istanbul': 5.0.5(vitest@5.0.5) + '@vitest/ui': 5.0.5(vitest@5.0.5) jsdom: 27.4.0(supports-color@10.2.2) transitivePeerDependencies: - msw - vitest@5.0.5(@types/node@24.19.2)(@vitest/coverage-istanbul@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): + vitest@5.0.5(@types/node@24.19.2)(@vitest/browser-playwright@5.0.5)(@vitest/coverage-istanbul@5.0.5)(@vitest/ui@5.0.5)(jsdom@27.4.0(supports-color@7.2.0))(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)): dependencies: '@types/chai': 5.2.3 '@vitest/mocker': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) @@ -43683,7 +43832,9 @@ snapshots: why-is-node-running: 3.2.1 optionalDependencies: '@types/node': 24.19.2 + '@vitest/browser-playwright': 5.0.5(msw@2.15.0(@types/node@24.19.2)(typescript@6.0.3))(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0))(vitest@5.0.5) '@vitest/coverage-istanbul': 5.0.5(vitest@5.0.5) + '@vitest/ui': 5.0.5(vitest@5.0.5) jsdom: 27.4.0(supports-color@7.2.0) transitivePeerDependencies: - msw From b33f01118c274fe8ae9f3f272900314309f10fc6 Mon Sep 17 00:00:00 2001 From: Jonghyeon Ko Date: Fri, 27 Nov 2026 19:48:13 +0900 Subject: [PATCH 03/11] feat(react-query): opt into polling per query instead of per client --- .changeset/react-query-standalone-adapters.md | 2 +- integrations/react/bundle-size/README.md | 4 +- .../react/bundle-size/browser/apps.test.js | 23 ++ integrations/react/bundle-size/measure.mjs | 46 +++- integrations/react/bundle-size/src/client.js | 3 - integrations/react/bundle-size/src/main.jsx | 5 +- .../react/bundle-size/src/numeric-interval.js | 1 + .../react/bundle-size/src/paginated.jsx | 43 ++-- .../bundle-size/src/pluggable-interval.js | 3 + .../react/bundle-size/src/plugin-client.js | 5 - .../react/bundle-size/src/polling.jsx | 65 +++++ .../bundle-size/vitest.browser.config.js | 2 +- knip.config.ts | 4 +- .../query-core/src/__tests__/clientOptions.ts | 2 - .../src/__tests__/queryClient.test-d.tsx | 5 +- .../src/__tests__/queryObserver.test-d.tsx | 10 +- .../src/__tests__/queryObserver.test.tsx | 19 +- packages/query-core/src/hydration.ts | 6 +- packages/query-core/src/index.ts | 1 + packages/query-core/src/mutationCache.ts | 7 +- packages/query-core/src/query.ts | 8 +- packages/query-core/src/queryCache.ts | 8 +- packages/query-core/src/queryObserver.ts | 6 +- packages/query-core/src/runtimeBinding.ts | 63 +++-- packages/query-core/src/types.ts | 104 +++++--- packages/query-core/src/utils.ts | 14 +- packages/query-test-utils/package.json | 3 +- packages/query-test-utils/src/polling.ts | 7 + packages/query-types/README.md | 27 ++ packages/query-types/src/binding.ts | 98 ++++++-- packages/query-types/src/contracts.ts | 233 +++++++++++++++--- packages/query-types/src/focusManager.ts | 6 +- packages/query-types/src/hydration.ts | 8 +- packages/query-types/src/index.ts | 157 ++++++++---- .../query-types/src/infiniteQueryObserver.ts | 12 +- packages/query-types/src/mutation.ts | 24 +- packages/query-types/src/mutationCache.ts | 24 +- packages/query-types/src/mutationObserver.ts | 4 +- packages/query-types/src/notifyManager.ts | 18 +- packages/query-types/src/onlineManager.ts | 6 +- packages/query-types/src/queriesObserver.ts | 17 +- packages/query-types/src/query.ts | 30 ++- packages/query-types/src/queryCache.ts | 27 +- packages/query-types/src/queryClient.ts | 11 +- packages/query-types/src/queryObserver.ts | 8 +- packages/query-types/src/retryer.ts | 6 +- packages/query-types/src/streamedQuery.ts | 15 +- packages/query-types/src/timeoutManager.ts | 4 +- packages/query-types/src/types.ts | 23 +- packages/query-types/src/utils.ts | 11 +- .../react-query-no-core-pluggable/README.md | 32 ++- .../package.json | 10 +- .../src/__tests__/plugins.test.ts | 80 ------ .../src/__tests__/refetchInterval.test-d.ts | 57 +++++ .../src/__tests__/refetchInterval.test.ts | 151 ++++++++++++ .../src/runtime/clientFeatures.ts | 40 --- .../src/runtime/hydration.ts | 18 +- .../src/runtime/index.ts | 5 +- .../src/runtime/mutationCache.ts | 2 + .../src/runtime/mutationObserver.ts | 10 +- .../src/runtime/plugins.ts | 24 -- .../src/runtime/query.ts | 40 ++- .../src/runtime/queryCache.ts | 3 + .../src/runtime/queryClient.ts | 51 ++-- .../src/runtime/queryObserver.ts | 69 ++---- .../src/runtime/refetchInterval.ts | 95 +++++++ .../src/runtime/runtimeBinding.ts | 74 +++--- .../src/runtime/types.ts | 52 +++- .../src/runtime/utils.ts | 17 +- .../src/useBaseQuery.ts | 41 ++- .../src/useObserverSnapshot.ts | 43 ++++ .../src/useQueries.ts | 43 ++-- .../test-setup.ts | 16 -- .../tests/compat-client.ts | 15 -- .../tests/compat-polling.ts | 6 + .../tsconfig.json | 9 +- .../vite.config.ts | 33 --- .../src/runtime/hydration.ts | 2 + .../react-query-no-core/src/runtime/index.ts | 1 + .../src/runtime/mutationCache.ts | 2 + .../react-query-no-core/src/runtime/query.ts | 8 +- .../src/runtime/queryCache.ts | 3 + .../src/runtime/queryObserver.ts | 2 + .../src/runtime/runtimeBinding.ts | 66 +++-- .../react-query-no-core/src/runtime/types.ts | 47 +++- .../react-query-no-core/src/runtime/utils.ts | 17 +- .../src/__tests__/mutationOptions.test.tsx | 3 +- .../usePrefetchInfiniteQuery.test-d.tsx | 3 +- .../src/__tests__/usePrefetchQuery.test-d.tsx | 3 +- .../src/__tests__/useQuery.test.tsx | 8 +- .../src/__tests__/useSuspenseQuery.test.tsx | 3 +- pnpm-lock.yaml | 12 - scripts/react-query-compat.config.ts | 10 +- scripts/test-react-query-compat.mjs | 25 +- 94 files changed, 1591 insertions(+), 898 deletions(-) delete mode 100644 integrations/react/bundle-size/src/client.js create mode 100644 integrations/react/bundle-size/src/numeric-interval.js create mode 100644 integrations/react/bundle-size/src/pluggable-interval.js delete mode 100644 integrations/react/bundle-size/src/plugin-client.js create mode 100644 integrations/react/bundle-size/src/polling.jsx delete mode 100644 packages/query-core/src/__tests__/clientOptions.ts create mode 100644 packages/query-test-utils/src/polling.ts create mode 100644 packages/query-types/README.md delete mode 100644 packages/react-query-no-core-pluggable/src/__tests__/plugins.test.ts create mode 100644 packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test-d.ts create mode 100644 packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/clientFeatures.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/plugins.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/refetchInterval.ts create mode 100644 packages/react-query-no-core-pluggable/src/useObserverSnapshot.ts delete mode 100644 packages/react-query-no-core-pluggable/test-setup.ts delete mode 100644 packages/react-query-no-core-pluggable/tests/compat-client.ts create mode 100644 packages/react-query-no-core-pluggable/tests/compat-polling.ts delete mode 100644 packages/react-query-no-core-pluggable/vite.config.ts diff --git a/.changeset/react-query-standalone-adapters.md b/.changeset/react-query-standalone-adapters.md index bb67c7e3652..c7ac4c1120e 100644 --- a/.changeset/react-query-standalone-adapters.md +++ b/.changeset/react-query-standalone-adapters.md @@ -5,4 +5,4 @@ '@tanstack/react-query-no-core-pluggable': minor --- -Add experimental ESM React Query adapters with an integrated query runtime. The pluggable adapter lets applications opt in to mutations and infinite queries per client. All three runtimes share their TypeScript definitions through `@tanstack/query-types`. +Add experimental ESM React Query adapters with an integrated query runtime. The pluggable adapter provides optional polling through the `refetchInterval` option factory. All three runtimes share their TypeScript definitions through `@tanstack/query-types`. diff --git a/integrations/react/bundle-size/README.md b/integrations/react/bundle-size/README.md index cfebd71372c..8a2e64d190f 100644 --- a/integrations/react/bundle-size/README.md +++ b/integrations/react/bundle-size/README.md @@ -1,6 +1,6 @@ # React Query app bundle size -This workspace builds two browser apps against each adapter’s public package entry point. The read-only app fetches a book list. The paginated app fetches additional pages and saves bookmarks in browser storage. All three builds of each app include React and React DOM. The paginated pluggable build registers the mutation and infinite-query plugins. +This workspace builds three browser apps against each adapter’s public package entry point. The read-only app fetches a book list. 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 all four regular and suspense query hooks. All builds include React and React DOM and use the default client. The original and standalone adapters accept a numeric interval. The pluggable adapter imports its interval scheduler through the `refetchInterval` option helper. The benchmark checks that only the polling build of that adapter includes the scheduler. Run from the repository root after installing the workspace dependencies: @@ -11,7 +11,7 @@ pnpm --filter @tanstack/query-integration-react-bundle-size run measure The report at `integrations/react/bundle-size/dist/report.md` shows total emitted JavaScript bytes and the sum of individually compressed chunks for gzip and Brotli. Each percentage uses the original adapter’s application size for that workload as its denominator. Serve a directory under `dist//` to try the built app. -Run the six production app scenarios in Chromium after measuring: +Run the nine production app scenarios in Chromium after measuring: ```sh cd integrations/react/bundle-size diff --git a/integrations/react/bundle-size/browser/apps.test.js b/integrations/react/bundle-size/browser/apps.test.js index b55101473da..307b717d6df 100644 --- a/integrations/react/bundle-size/browser/apps.test.js +++ b/integrations/react/bundle-size/browser/apps.test.js @@ -45,4 +45,27 @@ describe.each(adapters)('@tanstack/%s', (adapter) => { .toContain('Bookmarked: Villette') expect(localStorage.getItem('bookmark')).toBe('Villette') }) + + it('periodically refetches regular, infinite and suspense queries', async () => { + const app = await openApp('polling', adapter) + 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) => value > previous[index]) + ) + }, + { timeout: 4000 }, + ) + .toBe(true) + } + }) }) diff --git a/integrations/react/bundle-size/measure.mjs b/integrations/react/bundle-size/measure.mjs index e1b8647b82f..c26da85e569 100644 --- a/integrations/react/bundle-size/measure.mjs +++ b/integrations/react/bundle-size/measure.mjs @@ -14,10 +14,13 @@ const workloads = [ title: 'Paginated list with bookmarks · useQuery, useMutation, useInfiniteQuery', }, + { + screen: 'polling', + title: 'Polling with the four regular and suspense query hooks', + }, ] async function measure(packageName, screen) { - const withPlugins = packageName === pluggable && screen === 'paginated' const outDir = path.join(root, 'dist', screen, packageName.split('/')[1]) const result = await build({ root, @@ -28,10 +31,12 @@ async function measure(packageName, screen) { resolve: { alias: { '#adapter': packageName, - '#client': path.join( + '#polling-option': path.join( root, 'src', - withPlugins ? 'plugin-client.js' : 'client.js', + packageName === pluggable + ? 'pluggable-interval.js' + : 'numeric-interval.js', ), '#screen': path.join(root, 'src', `${screen}.jsx`), }, @@ -70,16 +75,15 @@ async function measure(packageName, screen) { ) { throw new Error(`${packageName} bundled @tanstack/query-core`) } - if ( - packageName === pluggable && - screen === 'query' && - modules.some((id) => - /\/runtime\/(mutation|mutationCache|infiniteQueryBehavior)\.js$/.test(id), - ) - ) { - throw new Error( - 'The query-only client bundled an optional plugin implementation', + if (packageName === pluggable) { + const includesPolling = modules.some((id) => + id.endsWith('/runtime/refetchInterval.js'), ) + if (includesPolling !== (screen === 'polling')) { + throw new Error( + `Unexpected refetchInterval implementation in ${screen}: included=${includesPolling}`, + ) + } } const sizes = { raw: 0, gzip: 0, brotli: 0 } @@ -104,6 +108,22 @@ function formatSize(bytes, baselineBytes, isBaseline) { return `${size} (${sign}${integer.format(difference)} B, ${sign}${percent}%)` } +// These public typing helpers share one callable in each standalone ESM package. +for (const name of packages.filter((name) => name !== baseline)) { + const { queryOptions, mutationOptions, infiniteQueryOptions } = await import( + name + ) + if ( + typeof queryOptions !== 'function' || + queryOptions !== mutationOptions || + queryOptions !== infiniteQueryOptions + ) { + throw new Error( + `${name} must export one runtime function for all three option factories`, + ) + } +} + const lines = [ '## React Query app bundle size', '', @@ -129,7 +149,7 @@ for (const { screen, title } of workloads) { } lines.push( '', - 'Gzip level 9 and Brotli quality 11 are applied to each JavaScript chunk before summing. The pluggable client registers mutation and infinite-query support for the paginated workload.', + 'Gzip level 9 and Brotli quality 11 are applied to each JavaScript chunk before summing. All workloads use the default client. Only the polling app imports the pluggable refetchInterval helper.', '', ) const report = lines.join('\n') diff --git a/integrations/react/bundle-size/src/client.js b/integrations/react/bundle-size/src/client.js deleted file mode 100644 index 723f2492e93..00000000000 --- a/integrations/react/bundle-size/src/client.js +++ /dev/null @@ -1,3 +0,0 @@ -import { QueryClient } from '#adapter' - -export const client = new QueryClient() diff --git a/integrations/react/bundle-size/src/main.jsx b/integrations/react/bundle-size/src/main.jsx index cc09878b2a1..244628c2b3b 100644 --- a/integrations/react/bundle-size/src/main.jsx +++ b/integrations/react/bundle-size/src/main.jsx @@ -1,9 +1,10 @@ import * as React from 'react' import { createRoot } from 'react-dom/client' -import { QueryClientProvider } from '#adapter' -import { client } from '#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.js b/integrations/react/bundle-size/src/numeric-interval.js new file mode 100644 index 00000000000..b22ad6afd12 --- /dev/null +++ b/integrations/react/bundle-size/src/numeric-interval.js @@ -0,0 +1 @@ +export const interval = 250 diff --git a/integrations/react/bundle-size/src/paginated.jsx b/integrations/react/bundle-size/src/paginated.jsx index 2cd97823030..599a6569e6d 100644 --- a/integrations/react/bundle-size/src/paginated.jsx +++ b/integrations/react/bundle-size/src/paginated.jsx @@ -1,22 +1,35 @@ import * as React from 'react' -import { useInfiniteQuery, useMutation, useQuery } from '#adapter' +import { + queryOptions, + infiniteQueryOptions, + mutationOptions, + useInfiniteQuery, + useMutation, + useQuery, +} from '#adapter' import { fetchBooks } from './books.js' export function ReadingList() { - const books = useInfiniteQuery({ - queryKey: ['books'], - queryFn: ({ pageParam, signal }) => fetchBooks(pageParam, signal), - initialPageParam: 1, - getNextPageParam: (lastPage) => lastPage.next, - }) - const bookmark = useQuery({ - queryKey: ['bookmark'], - queryFn: () => localStorage.getItem('bookmark'), - }) - const save = useMutation({ - mutationFn: async (title) => localStorage.setItem('bookmark', title), - onSuccess: () => bookmark.refetch(), - }) + const books = useInfiniteQuery( + infiniteQueryOptions({ + 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) => localStorage.setItem('bookmark', title), + onSuccess: () => bookmark.refetch(), + }), + ) if (books.isPending) return

Loading books…

if (books.isError) return

{books.error.message}

return ( diff --git a/integrations/react/bundle-size/src/pluggable-interval.js b/integrations/react/bundle-size/src/pluggable-interval.js new file mode 100644 index 00000000000..ca450d5790b --- /dev/null +++ b/integrations/react/bundle-size/src/pluggable-interval.js @@ -0,0 +1,3 @@ +import { refetchInterval } from '#adapter' + +export const interval = refetchInterval(250) diff --git a/integrations/react/bundle-size/src/plugin-client.js b/integrations/react/bundle-size/src/plugin-client.js deleted file mode 100644 index d6b5b1ce612..00000000000 --- a/integrations/react/bundle-size/src/plugin-client.js +++ /dev/null @@ -1,5 +0,0 @@ -import { QueryClient, infiniteQueryPlugin, mutationPlugin } from '#adapter' - -export const client = new QueryClient({ - plugins: [mutationPlugin, infiniteQueryPlugin], -}) diff --git a/integrations/react/bundle-size/src/polling.jsx b/integrations/react/bundle-size/src/polling.jsx new file mode 100644 index 00000000000..1ad84dd63dd --- /dev/null +++ b/integrations/react/bundle-size/src/polling.jsx @@ -0,0 +1,65 @@ +import * as React from 'react' +import { + useQuery, + useInfiniteQuery, + useSuspenseQuery, + useSuspenseInfiniteQuery, +} from '#adapter' +import { interval } from '#polling-option' +import { fetchBooks } from './books.js' + +function options(name) { + return { + queryKey: ['books', name], + queryFn: ({ pageParam = 1, signal }) => fetchBooks(pageParam, signal), + refetchInterval: interval, + refetchIntervalInBackground: true, + } +} + +const pagination = { + initialPageParam: 1, + getNextPageParam: (page) => page.next, +} + +function Updates() { + const query = useQuery(options('query')) + const infinite = useInfiniteQuery({ ...options('infinite'), ...pagination }) + const suspense = useSuspenseQuery(options('suspense')) + const suspenseInfinite = useSuspenseInfiniteQuery({ + ...options('suspense-infinite'), + ...pagination, + }) + const rows = [ + ['Query', query, query.data], + ['Infinite query', infinite, infinite.data?.pages[0]], + ['Suspense query', suspense, suspense.data], + [ + 'Suspense infinite query', + suspenseInfinite, + suspenseInfinite.data.pages[0], + ], + ] + return ( +
    + {rows.map(([name, result, page]) => ( +
  • + {name}: {page?.titles.join(', ')}{' '} + {result.dataUpdatedAt > 0 && ( + + )} +
  • + ))} +
+ ) +} + +export function ReadingList() { + return ( + Loading books…

}> + +
+ ) +} diff --git a/integrations/react/bundle-size/vitest.browser.config.js b/integrations/react/bundle-size/vitest.browser.config.js index df04aa0d4ad..51dd9c93e83 100644 --- a/integrations/react/bundle-size/vitest.browser.config.js +++ b/integrations/react/bundle-size/vitest.browser.config.js @@ -3,7 +3,7 @@ import { defineConfig } from 'vitest/config' export default defineConfig({ root: import.meta.dirname, - // Serve the six measured apps from disk, including their production JS chunks. + // Serve the measured apps from disk, including their production JS chunks. publicDir: 'dist', test: { include: ['browser/*.test.js'], diff --git a/knip.config.ts b/knip.config.ts index 9ed4a6cd8a9..746a9a2c8cc 100644 --- a/knip.config.ts +++ b/knip.config.ts @@ -20,7 +20,7 @@ const optionalPeerDependencies = (pkg: { // modules imported by the upstream suites. const compatibilityEntries = [ 'src/suspense.ts', - 'src/runtime/{query,notifyManager,timeoutManager,utils}.ts', + 'src/runtime/{query,notifyManager,retryer,timeoutManager,utils}.ts', ] export default { @@ -55,7 +55,7 @@ export default { ignoreDependencies: optionalPeerDependencies(reactQueryNoCore), }, 'packages/react-query-no-core-pluggable': { - entry: [...compatibilityEntries, 'tests/compat-client.ts'], + entry: [...compatibilityEntries, 'tests/compat-polling.ts'], ignoreDependencies: optionalPeerDependencies(reactQueryPluggable), }, 'packages/react-query-devtools': { diff --git a/packages/query-core/src/__tests__/clientOptions.ts b/packages/query-core/src/__tests__/clientOptions.ts deleted file mode 100644 index 5fff2884662..00000000000 --- a/packages/query-core/src/__tests__/clientOptions.ts +++ /dev/null @@ -1,2 +0,0 @@ -// Packages with an extended client configuration supply their extra keys here. -export type AdapterClientOptions = never diff --git a/packages/query-core/src/__tests__/queryClient.test-d.tsx b/packages/query-core/src/__tests__/queryClient.test-d.tsx index 62104b8fc65..4a8e15d3db1 100644 --- a/packages/query-core/src/__tests__/queryClient.test-d.tsx +++ b/packages/query-core/src/__tests__/queryClient.test-d.tsx @@ -26,7 +26,6 @@ import type { UnsetMarker, } from '../types' import type { MutationFilters, QueryFilters, Updater } from '../utils' -import type { AdapterClientOptions } from './clientOptions' type TypedData = { foo: string } type TypedError = DefaultError & { bar: string } @@ -1158,9 +1157,9 @@ describe('queryClient', () => { assertType>([]) }) - it('should declare exactly its supported options', () => { + it('should declare exactly its three options', () => { expectTypeOf().toEqualTypeOf< - 'queryCache' | 'mutationCache' | 'defaultOptions' | AdapterClientOptions + 'queryCache' | 'mutationCache' | 'defaultOptions' >() }) diff --git a/packages/query-core/src/__tests__/queryObserver.test-d.tsx b/packages/query-core/src/__tests__/queryObserver.test-d.tsx index 8049ce4ce16..d85a714f5e0 100644 --- a/packages/query-core/src/__tests__/queryObserver.test-d.tsx +++ b/packages/query-core/src/__tests__/queryObserver.test-d.tsx @@ -1,4 +1,5 @@ import { createKey } from '@tanstack/query-test-utils' +import { refetchInterval } from '@tanstack/query-test-utils/polling' import { afterEach, assertType, @@ -8,6 +9,7 @@ import { it, } from 'vitest' import { QueryClient, QueryObserver, defaultQueryFn } from '..' +import type { IntervalInput } from '@tanstack/query-test-utils/polling' import type { DefaultError, DefinedQueryObserverResult, @@ -191,7 +193,7 @@ describe('queryObserver', () => { expectTypeOf(query.state.data).toEqualTypeOf< { value: string } | undefined >() - return false + return refetchInterval(false) }, }) }) @@ -201,18 +203,18 @@ describe('queryObserver', () => { queryKey: createKey(), queryFn: () => Promise.resolve('data'), // @ts-expect-error a refetchInterval callback must return a number, false or undefined - refetchInterval: () => 'often', + refetchInterval: refetchInterval(() => 'often'), }) expectTypeOf< Extract< - QueryObserverOptions['refetchInterval'], + IntervalInput, (...args: Array) => any > >().returns.toEqualTypeOf() expectTypeOf< Exclude< - QueryObserverOptions['refetchInterval'], + IntervalInput, (...args: Array) => any > >().toEqualTypeOf() diff --git a/packages/query-core/src/__tests__/queryObserver.test.tsx b/packages/query-core/src/__tests__/queryObserver.test.tsx index 9ce8de6ce59..dad6075c650 100644 --- a/packages/query-core/src/__tests__/queryObserver.test.tsx +++ b/packages/query-core/src/__tests__/queryObserver.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { refetchInterval } from '@tanstack/query-test-utils/polling' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueryClient, @@ -945,7 +946,7 @@ describe('queryObserver', () => { queryKey: key, queryFn: fetchData, gcTime: 0, - refetchInterval: 10, + refetchInterval: refetchInterval(10), }) const unsubscribe = observer.subscribe(() => undefined) expect(count).toBe(1) @@ -967,7 +968,7 @@ describe('queryObserver', () => { count++ return Promise.resolve('data') }, - refetchInterval: () => 10, + refetchInterval: refetchInterval(() => 10), }) const unsubscribe = observer.subscribe(() => undefined) expect(count).toBe(1) @@ -979,15 +980,15 @@ describe('queryObserver', () => { it('should call refetchInterval with the query when it is a function', async () => { const key = createKey() - const refetchInterval = vi.fn<() => number>(() => 10) + const getInterval = vi.fn<() => number>(() => 10) const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => sleep(10).then(() => 'data'), - refetchInterval, + refetchInterval: refetchInterval(getInterval), }) const unsubscribe = observer.subscribe(() => undefined) await vi.advanceTimersByTimeAsync(10) - expect(refetchInterval).toHaveBeenCalledWith( + expect(getInterval).toHaveBeenCalledWith( queryClient.getQueryCache().find({ queryKey: key }), ) @@ -1137,7 +1138,7 @@ describe('queryObserver', () => { queryKey: key, queryFn, refetchIntervalInBackground: false, - refetchInterval: 10, + refetchInterval: refetchInterval(10), }) const unsubscribe = observer.subscribe(() => undefined) @@ -1418,7 +1419,7 @@ describe('queryObserver', () => { queryKey: key, queryFn: defaultQueryFn, enabled: false, - refetchInterval: 10, + refetchInterval: refetchInterval(10), }) const query = queryClient.getQueryCache().find({ queryKey: key }) @@ -1456,7 +1457,7 @@ describe('queryObserver', () => { queryFn: defaultQueryFn, enabled: false, staleTime: 10, - refetchInterval: 10, + refetchInterval: refetchInterval(10), }) const setTimeoutSpy = vi.spyOn(timeoutManager, 'setTimeout') const setIntervalSpy = vi.spyOn(timeoutManager, 'setInterval') @@ -1479,7 +1480,7 @@ describe('queryObserver', () => { queryKey: key, queryFn: defaultQueryFn, staleTime: 10, - refetchInterval: 10, + refetchInterval: refetchInterval(10), }) const setTimeoutSpy = vi.spyOn(timeoutManager, 'setTimeout') const setIntervalSpy = vi.spyOn(timeoutManager, 'setInterval') diff --git a/packages/query-core/src/hydration.ts b/packages/query-core/src/hydration.ts index 25f4fd5cac7..9f431f465e9 100644 --- a/packages/query-core/src/hydration.ts +++ b/packages/query-core/src/hydration.ts @@ -37,9 +37,9 @@ function tryResolveSync(promise: PromiseLike) { return undefined } -export type DehydrateOptions = Shared.DehydrateOptions +type DehydrateOptions = Shared.DehydrateOptions -export type HydrateOptions = Shared.HydrateOptions +type HydrateOptions = Shared.HydrateOptions // FUNCTIONS @@ -366,3 +366,5 @@ export function hydrate( } export type { DehydratedState } from '@tanstack/query-types/bindings' + +export type { DehydrateOptions, HydrateOptions } diff --git a/packages/query-core/src/index.ts b/packages/query-core/src/index.ts index 0b313930aa5..b2706f657e9 100644 --- a/packages/query-core/src/index.ts +++ b/packages/query-core/src/index.ts @@ -165,3 +165,4 @@ export type { NotifyEventType, NotifyEvent, } from './types' +export type { QueryRuntime } from './runtimeBinding' diff --git a/packages/query-core/src/mutationCache.ts b/packages/query-core/src/mutationCache.ts index f2e4475c64a..8b6e4a73e54 100644 --- a/packages/query-core/src/mutationCache.ts +++ b/packages/query-core/src/mutationCache.ts @@ -7,10 +7,9 @@ import type { QueryRuntime } from './runtimeBinding' import type { DefaultError } from './types' import type { MutationFilters } from './utils' -export type MutationCacheConfig = Shared.MutationCacheConfig +type MutationCacheConfig = Shared.MutationCacheConfig -export type MutationCacheNotifyEvent = - Shared.MutationCacheNotifyEvent +type MutationCacheNotifyEvent = Shared.MutationCacheNotifyEvent type MutationCacheListener = Shared.MutationCacheListener @@ -268,3 +267,5 @@ export class MutationCache extends Subscribable { function scopeFor(mutation: Mutation) { return mutation.options.scope?.id } + +export type { MutationCacheConfig, MutationCacheNotifyEvent } diff --git a/packages/query-core/src/query.ts b/packages/query-core/src/query.ts index 4e7f7e3ceec..5cf7cb228ab 100644 --- a/packages/query-core/src/query.ts +++ b/packages/query-core/src/query.ts @@ -13,8 +13,8 @@ import { } from './utils' import type * as Shared from '@tanstack/query-types/bindings' import type { - FetchOptions, QueryAction as Action, + FetchOptions, QueryState, } from '@tanstack/query-types/bindings' import type { QueryCache } from './queryCache' @@ -40,14 +40,14 @@ type QueryConfig< TQueryKey extends QueryKey = QueryKey, > = Shared.QueryConfig -export type FetchContext< +type FetchContext< TQueryFnData, TError, TData, TQueryKey extends QueryKey = QueryKey, > = Shared.FetchContext -export type QueryBehavior< +type QueryBehavior< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -908,3 +908,5 @@ export type { FetchOptions, QueryAction as Action, } from '@tanstack/query-types/bindings' + +export type { FetchContext, QueryBehavior } diff --git a/packages/query-core/src/queryCache.ts b/packages/query-core/src/queryCache.ts index 834a79a6eec..3cd097549f1 100644 --- a/packages/query-core/src/queryCache.ts +++ b/packages/query-core/src/queryCache.ts @@ -14,13 +14,13 @@ import type { } from './types' import type { QueryFilters } from './utils' -export type QueryCacheConfig = Shared.QueryCacheConfig +type QueryCacheConfig = Shared.QueryCacheConfig -export type QueryCacheNotifyEvent = Shared.QueryCacheNotifyEvent +type QueryCacheNotifyEvent = Shared.QueryCacheNotifyEvent type QueryCacheListener = Shared.QueryCacheListener -export type QueryStore = Shared.QueryStore +type QueryStore = Shared.QueryStore // CLASS @@ -296,3 +296,5 @@ export class QueryCache extends Subscribable { }) } } + +export type { QueryCacheConfig, QueryCacheNotifyEvent, QueryStore } diff --git a/packages/query-core/src/queryObserver.ts b/packages/query-core/src/queryObserver.ts index 5ba4e3d5190..76163eba849 100644 --- a/packages/query-core/src/queryObserver.ts +++ b/packages/query-core/src/queryObserver.ts @@ -34,7 +34,7 @@ import type { RefetchOptions, } from './types' -export type QueryObserverResultContext< +type QueryObserverResultContext< TQueryFnData, TError, TData, @@ -49,7 +49,7 @@ export type QueryObserverResultContext< TQueryKey > -export type ObserverOptionsInput< +type ObserverOptionsInput< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -1043,3 +1043,5 @@ function isStale( } export type { QueryObserverResultReader } from '@tanstack/query-types/bindings' + +export type { QueryObserverResultContext, ObserverOptionsInput } diff --git a/packages/query-core/src/runtimeBinding.ts b/packages/query-core/src/runtimeBinding.ts index 26f50dded36..0f604c89738 100644 --- a/packages/query-core/src/runtimeBinding.ts +++ b/packages/query-core/src/runtimeBinding.ts @@ -6,44 +6,37 @@ import type { Query } from './query' import type { QueryCache } from './queryCache' import type { QueryClient } from './queryClient' import type { QueryObserver } from './queryObserver' -import type { QueryKey } from './types' /** Binds shared option and callback types to the concrete classes in this runtime. */ -export interface QueryRuntime extends RuntimeBinding { +interface QueryRuntime extends RuntimeBinding { QueryClient: QueryClient QueryCache: QueryCache MutationCache: MutationCache - Query: this['args'] extends [ - infer TQueryFnData, - infer TError, - infer TData, - infer TQueryKey extends QueryKey, - ] - ? Query - : never - Mutation: this['args'] extends [ - infer TData, - infer TError, - infer TVariables, - infer TOnMutateResult, - ] - ? Mutation - : never - QueryObserver: this['args'] extends [ - infer TQueryFnData, - infer TError, - infer TData, - infer TQueryData, - infer TQueryKey extends QueryKey, - ] - ? QueryObserver - : never - MutationObserver: this['args'] extends [ - infer TData, - infer TError, - infer TVariables, - infer TOnMutateResult, - ] - ? MutationObserver - : never + Query: Query< + this['queryFnData'], + this['error'], + this['data'], + this['queryKey'][0] + > + Mutation: Mutation< + this['data'], + this['error'], + this['variables'], + this['onMutateResult'] + > + QueryObserver: QueryObserver< + this['queryFnData'], + this['error'], + this['data'], + this['queryData'], + this['queryKey'][0] + > + MutationObserver: MutationObserver< + this['data'], + this['error'], + this['variables'], + this['onMutateResult'] + > } + +export type { QueryRuntime } diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index 67aa6619cf5..d326387cc0e 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -3,9 +3,9 @@ import type { DefaultError, InfiniteData, QueryKey, - UnsetMarker as unsetMarkerType, dataTagErrorSymbol as dataTagErrorSymbolType, dataTagSymbol as dataTagSymbolType, + UnsetMarker as unsetMarkerType, } from '@tanstack/query-types/bindings' import type { QueryRuntime } from './runtimeBinding' @@ -27,13 +27,13 @@ export const unsetMarker: unsetMarkerType = Symbol.for( '@tanstack/query/unsetMarker', ) as unsetMarkerType -export type QueryFunction< +type QueryFunction< T = unknown, TQueryKey extends QueryKey = QueryKey, TPageParam = never, > = Shared.QueryFunction -export type StaleTimeFunction< +type StaleTimeFunction< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -46,7 +46,7 @@ export type StaleTimeFunction< TQueryKey > -export type QueryBooleanOption< +type QueryBooleanOption< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -59,20 +59,18 @@ export type QueryBooleanOption< TQueryKey > -export type QueryPersister< +type QueryPersister< T = unknown, TQueryKey extends QueryKey = QueryKey, TPageParam = never, > = Shared.QueryPersister -export type QueryFunctionContext< +type QueryFunctionContext< TQueryKey extends QueryKey = QueryKey, TPageParam = never, > = Shared.QueryFunctionContext -// oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes every function-like value, including constructors, from the value branch - -export type PlaceholderDataFunction< +type PlaceholderDataFunction< TQueryFnData = unknown, TError = DefaultError, TQueryData = TQueryFnData, @@ -85,7 +83,7 @@ export type PlaceholderDataFunction< TQueryKey > -export type QueryOptions< +type QueryOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -100,7 +98,7 @@ export type QueryOptions< TPageParam > -export type ThrowOnError< +type ThrowOnError< TQueryFnData, TError, TQueryData, @@ -113,7 +111,7 @@ export type ThrowOnError< TQueryKey > -export type QueryObserverOptionsBase< +type QueryObserverOptionsBase< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -130,7 +128,7 @@ export type QueryObserverOptionsBase< TPageParam > -export type QueryObserverOptions< +type QueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -147,7 +145,7 @@ export type QueryObserverOptions< TPageParam > -export type DefaultedQueryObserverOptions< +type DefaultedQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -164,7 +162,7 @@ export type DefaultedQueryObserverOptions< TPageParam > -export type InfiniteQueryObserverOptions< +type InfiniteQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -179,7 +177,7 @@ export type InfiniteQueryObserverOptions< TPageParam > -export type DefaultedInfiniteQueryObserverOptions< +type DefaultedInfiniteQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -194,7 +192,7 @@ export type DefaultedInfiniteQueryObserverOptions< TPageParam > -export type QueryExecuteOptions< +type QueryExecuteOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -211,7 +209,7 @@ export type QueryExecuteOptions< TPageParam > -export type InfiniteQueryExecuteOptions< +type InfiniteQueryExecuteOptions< TQueryFnData = unknown, TError = DefaultError, TData = InfiniteData, @@ -226,21 +224,20 @@ export type InfiniteQueryExecuteOptions< TPageParam > -export type InvalidateQueryFilters = +type InvalidateQueryFilters = Shared.InvalidateQueryFilters -export type RefetchQueryFilters = +type RefetchQueryFilters = Shared.RefetchQueryFilters -export type MutationFunctionContext = - Shared.MutationFunctionContext +type MutationFunctionContext = Shared.MutationFunctionContext -export type MutationFunction< +type MutationFunction< TData = unknown, TVariables = unknown, > = Shared.MutationFunction -export type MutationOptions< +type MutationOptions< TData = unknown, TError = DefaultError, TVariables = void, @@ -253,7 +250,7 @@ export type MutationOptions< TOnMutateResult > -export type MutationObserverOptions< +type MutationObserverOptions< TData = unknown, TError = DefaultError, TVariables = void, @@ -266,7 +263,7 @@ export type MutationObserverOptions< TOnMutateResult > -export type MutateOptions< +type MutateOptions< TData = unknown, TError = DefaultError, TVariables = void, @@ -279,7 +276,7 @@ export type MutateOptions< TOnMutateResult > -export type MutateFunctionRest< +type MutateFunctionRest< TData = unknown, TError = DefaultError, TVariables = void, @@ -292,7 +289,7 @@ export type MutateFunctionRest< TOnMutateResult > -export type MutateFunction< +type MutateFunction< TData = unknown, TError = DefaultError, TVariables = void, @@ -305,7 +302,7 @@ export type MutateFunction< TOnMutateResult > -export type MutationObserverBaseResult< +type MutationObserverBaseResult< TData = unknown, TError = DefaultError, TVariables = void, @@ -318,7 +315,7 @@ export type MutationObserverBaseResult< TOnMutateResult > -export type MutationObserverIdleResult< +type MutationObserverIdleResult< TData = unknown, TError = DefaultError, TVariables = void, @@ -331,7 +328,7 @@ export type MutationObserverIdleResult< TOnMutateResult > -export type MutationObserverLoadingResult< +type MutationObserverLoadingResult< TData = unknown, TError = DefaultError, TVariables = void, @@ -344,7 +341,7 @@ export type MutationObserverLoadingResult< TOnMutateResult > -export type MutationObserverErrorResult< +type MutationObserverErrorResult< TData = unknown, TError = DefaultError, TVariables = void, @@ -357,7 +354,7 @@ export type MutationObserverErrorResult< TOnMutateResult > -export type MutationObserverSuccessResult< +type MutationObserverSuccessResult< TData = unknown, TError = DefaultError, TVariables = void, @@ -370,7 +367,7 @@ export type MutationObserverSuccessResult< TOnMutateResult > -export type MutationObserverResult< +type MutationObserverResult< TData = unknown, TError = DefaultError, TVariables = void, @@ -383,9 +380,9 @@ export type MutationObserverResult< TOnMutateResult > -export type QueryClientConfig = Shared.QueryClientConfig +type QueryClientConfig = Shared.QueryClientConfig -export type DefaultOptions = Shared.DefaultOptions< +type DefaultOptions = Shared.DefaultOptions< QueryRuntime, TError > @@ -454,3 +451,38 @@ export type { NotifyEventType, NotifyEvent, } from '@tanstack/query-types/bindings' + +export type { + QueryFunction, + StaleTimeFunction, + QueryBooleanOption, + QueryPersister, + QueryFunctionContext, + PlaceholderDataFunction, + QueryOptions, + ThrowOnError, + QueryObserverOptionsBase, + QueryObserverOptions, + DefaultedQueryObserverOptions, + InfiniteQueryObserverOptions, + DefaultedInfiniteQueryObserverOptions, + QueryExecuteOptions, + InfiniteQueryExecuteOptions, + InvalidateQueryFilters, + RefetchQueryFilters, + MutationFunctionContext, + MutationFunction, + MutationOptions, + MutationObserverOptions, + MutateOptions, + MutateFunctionRest, + MutateFunction, + MutationObserverBaseResult, + MutationObserverIdleResult, + MutationObserverLoadingResult, + MutationObserverErrorResult, + MutationObserverSuccessResult, + MutationObserverResult, + QueryClientConfig, + DefaultOptions, +} diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index 2ffd6135e6a..9cd373fa216 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -2,11 +2,11 @@ import { timeoutManager } from './timeoutManager' import type * as Shared from '@tanstack/query-types/bindings' import type { DefaultQueryFn, + SkipToken, + Updater, DefaultQueryFn as defaultQueryFnType, FetchSignal as fetchSignalType, - SkipToken, SkipToken as skipTokenType, - Updater, } from '@tanstack/query-types/bindings' import type { Mutation } from './mutation' import type { FetchOptions, Query } from './query' @@ -21,10 +21,12 @@ import type { QueryOptions, } from './types' -export type QueryFilters = - Shared.QueryFilters +type QueryFilters = Shared.QueryFilters< + QueryRuntime, + TQueryKey +> -export type MutationFilters< +type MutationFilters< TData = unknown, TError = DefaultError, TVariables = unknown, @@ -746,3 +748,5 @@ export type { DefaultQueryFn, FetchSignalContext, } from '@tanstack/query-types/bindings' + +export type { QueryFilters, MutationFilters } diff --git a/packages/query-test-utils/package.json b/packages/query-test-utils/package.json index e8fe8451f00..5aa3f7ef427 100644 --- a/packages/query-test-utils/package.json +++ b/packages/query-test-utils/package.json @@ -23,7 +23,8 @@ "types": "./src/index.ts", "default": "./src/index.ts" }, - "./package.json": "./package.json" + "./package.json": "./package.json", + "./polling": "./src/polling.ts" }, "scripts": { "clean": "premove ./build ./coverage ./dist-ts ./.cache/test-types", diff --git a/packages/query-test-utils/src/polling.ts b/packages/query-test-utils/src/polling.ts new file mode 100644 index 00000000000..b76a0a7cb11 --- /dev/null +++ b/packages/query-test-utils/src/polling.ts @@ -0,0 +1,7 @@ +// The v6 and integrated adapters accept the interval directly. The pluggable +// compatibility suite resolves this module to its public polling factory. +export function refetchInterval(option: T): T { + return option +} + +export type IntervalInput = TOption diff --git a/packages/query-types/README.md b/packages/query-types/README.md new file mode 100644 index 00000000000..50ad55fcaaa --- /dev/null +++ b/packages/query-types/README.md @@ -0,0 +1,27 @@ +# @tanstack/query-types + +Shared TypeScript declarations for TanStack Query. Use type-only imports in code that models query state, cached data, results, and options. + +```ts +import type { QueryState } from '@tanstack/query-types' + +export function lastSuccessfulUpdate(state: QueryState) { + return state.dataUpdatedAt +} +``` + +The package root describes the public instance methods of the query client, caches, and observers. Each adapter also re-exports the query types with the concrete classes its callbacks receive. + +When publishing a callback or options object for use with a particular adapter, use its specialized types. Libraries that support multiple implementations can use the same declaration with each adapter's `QueryRuntime` type parameter. + +```ts +import type { QueryOptions } from '@tanstack/query-types/bindings' +import type { QueryRuntime } from '@tanstack/react-query-no-core' + +export const bookOptions: QueryOptions = { + queryKey: ['book'], + queryFn: async ({ client }) => client.getQueryData(['title']) ?? '', +} +``` + +Augment `Register` in `@tanstack/query-types` to share your application's error, key, or metadata types across installed adapters. diff --git a/packages/query-types/src/binding.ts b/packages/query-types/src/binding.ts index 7b698d755c0..8f590e05abf 100644 --- a/packages/query-types/src/binding.ts +++ b/packages/query-types/src/binding.ts @@ -1,45 +1,92 @@ import type { DefaultError, QueryKey } from './types' -/** Runtime implementations bind these slots to their own nominal class types. */ -export interface RuntimeBinding { - args: unknown +/** + * Type arguments and classes used by options and callbacks. Each runtime supplies + * its public classes using polymorphic `this` to read the current type arguments. + * For example, `QueryOf` selects `Query` after binding the data, error, and key. + */ +interface RuntimeBinding { + data: unknown + queryFnData: unknown + queryData: unknown + error: unknown + // A tuple keeps a bound key exact when this slot intersects with its input. + queryKey: ReadonlyArray + variables: unknown + onMutateResult: unknown + /** The client passed to query functions and mutations. */ QueryClient: unknown + /** The query cache accepted in client options. */ QueryCache: unknown + /** The mutation cache accepted in client options. */ MutationCache: unknown + /** The query passed to predicates, option callbacks, and cache listeners. */ Query: unknown + /** The mutation passed to predicates and cache listeners. */ Mutation: unknown + /** The observer included in query cache notifications. */ QueryObserver: unknown + /** The observer included in mutation cache notifications. */ MutationObserver: unknown } -export type QueryClientOf = - TRuntime['QueryClient'] +type QueryClientOf = TRuntime['QueryClient'] -export type QueryCacheOf = - TRuntime['QueryCache'] +type QueryCacheOf = TRuntime['QueryCache'] -export type MutationCacheOf = +type MutationCacheOf = TRuntime['MutationCache'] -export type QueryOf< +type BoundQuery = TRuntime & { + queryFnData: TQueryFnData + error: TError + data: TData + queryKey: [TQueryKey] +} + +type QueryOf< TRuntime extends RuntimeBinding, TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> = (TRuntime & { args: [TQueryFnData, TError, TData, TQueryKey] })['Query'] +> = BoundQuery['Query'] + +/** Allows an adapter to supply its own polling option while preserving the query type in callbacks. */ +type RefetchIntervalOf< + TRuntime extends RuntimeBinding, + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, +> = TRuntime extends { refetchInterval: unknown } + ? BoundQuery< + TRuntime, + TQueryFnData, + TError, + TData, + TQueryKey + >['refetchInterval'] + : | number + | false + | (( + query: QueryOf, + ) => number | false | undefined) -export type MutationOf< +type MutationOf< TRuntime extends RuntimeBinding, TData = unknown, TError = DefaultError, TVariables = unknown, TOnMutateResult = unknown, > = (TRuntime & { - args: [TData, TError, TVariables, TOnMutateResult] + data: TData + error: TError + variables: TVariables + onMutateResult: TOnMutateResult })['Mutation'] -export type QueryObserverOf< +type QueryObserverOf< TRuntime extends RuntimeBinding, TQueryFnData = unknown, TError = DefaultError, @@ -47,15 +94,34 @@ export type QueryObserverOf< TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, > = (TRuntime & { - args: [TQueryFnData, TError, TData, TQueryData, TQueryKey] + queryFnData: TQueryFnData + error: TError + data: TData + queryData: TQueryData + queryKey: [TQueryKey] })['QueryObserver'] -export type MutationObserverOf< +type MutationObserverOf< TRuntime extends RuntimeBinding, TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, > = (TRuntime & { - args: [TData, TError, TVariables, TOnMutateResult] + data: TData + error: TError + variables: TVariables + onMutateResult: TOnMutateResult })['MutationObserver'] + +export type { + RuntimeBinding, + QueryClientOf, + QueryCacheOf, + MutationCacheOf, + QueryOf, + RefetchIntervalOf, + MutationOf, + QueryObserverOf, + MutationObserverOf, +} diff --git a/packages/query-types/src/contracts.ts b/packages/query-types/src/contracts.ts index a2aa2bf61a6..862eb320e1e 100644 --- a/packages/query-types/src/contracts.ts +++ b/packages/query-types/src/contracts.ts @@ -1,19 +1,43 @@ import type { RuntimeBinding } from './binding' +import type { FocusManagerListener, FocusManagerSetupFn } from './focusManager' +import type { + InfiniteQueryObserverListener, + ReplaceReturnType, + InfiniteObserverOptionsInput as SharedInfiniteObserverOptionsInput, +} from './infiniteQueryObserver' import type { MutationCacheListener as SharedMutationCacheListener } from './mutationCache' import type { MutationObserverListener as SharedMutationObserverListener } from './mutationObserver' +import type { + OnlineManagerListener, + OnlineManagerSetupFn, +} from './onlineManager' +import type { + QueriesObserverListener, + QueriesObserverOptions, + QueriesObserverResultReader, +} from './queriesObserver' import type { QueryCacheListener as SharedQueryCacheListener } from './queryCache' import type { WithoutSkipToken } from './queryClient' import type { QueryObserverListener } from './queryObserver' +import type { + ManagedTimerId, + TimeoutCallback, + TimeoutProvider, +} from './timeoutManager' import type { CancelOptions, DefaultError, DefaultOptions, + DefaultedInfiniteQueryObserverOptions, DefaultedQueryObserverOptions, + FetchNextPageOptions, FetchOptions, + FetchPreviousPageOptions, InferDataFromTag, InferErrorFromTag, InfiniteData, InfiniteQueryExecuteOptions, + InfiniteQueryObserverResult, InvalidateOptions, InvalidateQueryFilters, MutateOptions, @@ -48,6 +72,9 @@ import type { Updater, WithRequired, } from './index' + +/* oxlint-disable typescript/method-signature-style -- Match runtime class methods, including their parameter variance. */ + interface Subscription { subscribe(listener: TListener): () => void hasListeners(): boolean @@ -56,7 +83,7 @@ interface CacheEntry { gcTime: number destroy(): void } -export interface QueryClient { +interface QueryClient { mount(): void unmount(): void isFetching(filters?: Omit): number @@ -276,7 +303,7 @@ export interface QueryClient { clear(): void } -export interface QueryCache extends Subscription { +interface QueryCache extends Subscription { config: QueryCacheConfig build< TQueryFnData = unknown, @@ -312,7 +339,7 @@ export interface QueryCache extends Subscription { onOnline(): void } -export interface MutationCache extends Subscription { +interface MutationCache extends Subscription { config: MutationCacheConfig register>(create: (id: number) => T): T add(mutation: Mutation): void @@ -335,7 +362,7 @@ export interface MutationCache extends Subscription { resumePausedMutations(): Promise } -export interface Query< +interface Query< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -381,7 +408,7 @@ export interface Query< ): Promise } -export interface Mutation< +interface Mutation< TData = unknown, TError = DefaultError, TVariables = unknown, @@ -400,7 +427,7 @@ export interface Mutation< execute(variables: TVariables): Promise } -export interface QueryObserver< +interface QueryObserver< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -456,7 +483,7 @@ export interface QueryObserver< onQueryUpdate(): void } -export interface MutationObserver< +interface MutationObserver< TData = unknown, TError = DefaultError, TVariables = void, @@ -501,41 +528,165 @@ type MutationObserverListener = > /** Structural public class shapes used when importing types without a runtime. */ -export interface DefaultRuntime extends RuntimeBinding { +interface DefaultRuntime extends RuntimeBinding { QueryClient: QueryClient QueryCache: QueryCache MutationCache: MutationCache - Query: this['args'] extends [ - infer TQueryFnData, - infer TError, - infer TData, - infer TQueryKey extends QueryKey, - ] - ? Query - : never - Mutation: this['args'] extends [ - infer TData, - infer TError, - infer TVariables, - infer TOnMutateResult, - ] - ? Mutation - : never - QueryObserver: this['args'] extends [ - infer TQueryFnData, - infer TError, - infer TData, - infer TQueryData, - infer TQueryKey extends QueryKey, - ] - ? QueryObserver - : never - MutationObserver: this['args'] extends [ - infer TData, - infer TError, - infer TVariables, - infer TOnMutateResult, - ] - ? MutationObserver - : never + Query: Query< + this['queryFnData'], + this['error'], + this['data'], + this['queryKey'][0] + > + Mutation: Mutation< + this['data'], + this['error'], + this['variables'], + this['onMutateResult'] + > + QueryObserver: QueryObserver< + this['queryFnData'], + this['error'], + this['data'], + this['queryData'], + this['queryKey'][0] + > + MutationObserver: MutationObserver< + this['data'], + this['error'], + this['variables'], + this['onMutateResult'] + > +} + +interface FocusManager extends Subscription { + setEventListener(setup: FocusManagerSetupFn): void + setFocused(focused?: boolean): void + onFocus(): void + isFocused(): boolean +} + +interface OnlineManager extends Subscription { + setEventListener(setup: OnlineManagerSetupFn): void + setOnline(online: boolean): void + isOnline(): boolean +} + +interface TimeoutManager { + setTimeoutProvider( + provider: TimeoutProvider, + ): void + setTimeout(callback: TimeoutCallback, delay: number): ManagedTimerId + clearTimeout(timeoutId: ManagedTimerId | undefined): void + setInterval(callback: TimeoutCallback, delay: number): ManagedTimerId + clearInterval(intervalId: ManagedTimerId | undefined): void +} + +interface QueriesObserver< + TCombinedResult = Array, +> extends Subscription { + destroy(): void + setQueries( + queries: Array, + options?: QueriesObserverOptions, + ): void + getCurrentResult(): Array + getQueries(): Array + getObservers(): Array + createResultReader( + queries: Array>, + options?: QueriesObserverOptions, + ): QueriesObserverResultReader +} + +interface InfiniteQueryObserver< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> extends QueryObserver< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey +> { + subscribe: Subscription< + InfiniteQueryObserverListener + >['subscribe'] + getCurrentResult: ReplaceReturnType< + QueryObserver< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey + >['getCurrentResult'], + InfiniteQueryObserverResult + > + setOptions( + options: InfiniteObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): void + createResultReader( + options: DefaultedInfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): QueryObserverResultReader> + fetchNextPage( + options?: FetchNextPageOptions, + ): Promise> + fetchPreviousPage( + options?: FetchPreviousPageOptions, + ): Promise> +} + +interface CancelledError extends Error { + revert?: boolean + silent?: boolean +} + +type InfiniteObserverOptionsInput< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, + TPageParam, +> = SharedInfiniteObserverOptionsInput< + DefaultRuntime, + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> + +export type { + FocusManager, + OnlineManager, + TimeoutManager, + QueriesObserver, + InfiniteQueryObserver, + CancelledError, +} + +export type { + QueryClient, + QueryCache, + MutationCache, + Query, + Mutation, + QueryObserver, + MutationObserver, + DefaultRuntime, } diff --git a/packages/query-types/src/focusManager.ts b/packages/query-types/src/focusManager.ts index f9c2a5eb0a4..5b9171555f0 100644 --- a/packages/query-types/src/focusManager.ts +++ b/packages/query-types/src/focusManager.ts @@ -1,5 +1,7 @@ -export type FocusManagerListener = (focused: boolean) => void +type FocusManagerListener = (focused: boolean) => void -export type FocusManagerSetupFn = ( +type FocusManagerSetupFn = ( setFocused: (focused?: boolean) => void, ) => (() => void) | undefined + +export type { FocusManagerListener, FocusManagerSetupFn } diff --git a/packages/query-types/src/hydration.ts b/packages/query-types/src/hydration.ts index 3938903f90a..55dbb5b7634 100644 --- a/packages/query-types/src/hydration.ts +++ b/packages/query-types/src/hydration.ts @@ -12,7 +12,7 @@ import type { QueryOptions, } from './types' -export type TransformerFn = (data: any) => any +type TransformerFn = (data: any) => any /** * Options for `dehydrate`, controlling which queries/mutations are included in the resulting `DehydratedState` and @@ -55,14 +55,14 @@ export interface HydrateOptions { } } -export interface DehydratedMutation { +interface DehydratedMutation { mutationKey?: MutationKey state: MutationState meta?: MutationMeta scope?: MutationScope } -export interface DehydratedQuery { +interface DehydratedQuery { queryHash: string queryKey: QueryKey state: QueryState @@ -87,3 +87,5 @@ export interface DehydratedState { */ queries: Array } + +export type { TransformerFn, DehydratedMutation, DehydratedQuery } diff --git a/packages/query-types/src/index.ts b/packages/query-types/src/index.ts index 0a021f0c64d..6fe9ce3013e 100644 --- a/packages/query-types/src/index.ts +++ b/packages/query-types/src/index.ts @@ -22,10 +22,11 @@ import type { } from './queryObserver' import type { DefaultError, + InfiniteData, + QueryKey, DefaultOptions as SharedDefaultOptions, DefaultedInfiniteQueryObserverOptions as SharedDefaultedInfiniteQueryObserverOptions, DefaultedQueryObserverOptions as SharedDefaultedQueryObserverOptions, - InfiniteData, InfiniteQueryExecuteOptions as SharedInfiniteQueryExecuteOptions, InfiniteQueryObserverOptions as SharedInfiniteQueryObserverOptions, InvalidateQueryFilters as SharedInvalidateQueryFilters, @@ -48,7 +49,6 @@ import type { QueryExecuteOptions as SharedQueryExecuteOptions, QueryFunction as SharedQueryFunction, QueryFunctionContext as SharedQueryFunctionContext, - QueryKey, QueryObserverOptions as SharedQueryObserverOptions, QueryObserverOptionsBase as SharedQueryObserverOptionsBase, QueryOptions as SharedQueryOptions, @@ -61,6 +61,7 @@ import type { MutationFilters as SharedMutationFilters, QueryFilters as SharedQueryFilters, } from './utils' + export type { IsServerValue } from './environmentManager' export type { DehydratedState } from './hydration' export type { MutationState, MutationAction } from './mutation' @@ -155,27 +156,26 @@ export type { DefaultQueryFn, FetchSignalContext, } from './utils' -export type DehydrateOptions = SharedDehydrateOptions -export type HydrateOptions = SharedHydrateOptions -export type MutationCacheConfig = SharedMutationCacheConfig -export type MutationCacheNotifyEvent = - SharedMutationCacheNotifyEvent -export type FetchContext< +type DehydrateOptions = SharedDehydrateOptions +type HydrateOptions = SharedHydrateOptions +type MutationCacheConfig = SharedMutationCacheConfig +type MutationCacheNotifyEvent = SharedMutationCacheNotifyEvent +type FetchContext< TQueryFnData, TError, TData, TQueryKey extends QueryKey = QueryKey, > = SharedFetchContext -export type QueryBehavior< +type QueryBehavior< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, > = SharedQueryBehavior -export type QueryCacheConfig = SharedQueryCacheConfig -export type QueryCacheNotifyEvent = SharedQueryCacheNotifyEvent -export type QueryStore = SharedQueryStore -export type QueryObserverResultContext< +type QueryCacheConfig = SharedQueryCacheConfig +type QueryCacheNotifyEvent = SharedQueryCacheNotifyEvent +type QueryStore = SharedQueryStore +type QueryObserverResultContext< TQueryFnData, TError, TData, @@ -189,7 +189,7 @@ export type QueryObserverResultContext< TQueryData, TQueryKey > -export type ObserverOptionsInput< +type ObserverOptionsInput< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -203,12 +203,12 @@ export type ObserverOptionsInput< TQueryData, TQueryKey > -export type QueryFunction< +type QueryFunction< T = unknown, TQueryKey extends QueryKey = QueryKey, TPageParam = never, > = SharedQueryFunction -export type StaleTimeFunction< +type StaleTimeFunction< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -220,7 +220,7 @@ export type StaleTimeFunction< TData, TQueryKey > -export type QueryBooleanOption< +type QueryBooleanOption< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -232,16 +232,16 @@ export type QueryBooleanOption< TData, TQueryKey > -export type QueryPersister< +type QueryPersister< T = unknown, TQueryKey extends QueryKey = QueryKey, TPageParam = never, > = SharedQueryPersister -export type QueryFunctionContext< +type QueryFunctionContext< TQueryKey extends QueryKey = QueryKey, TPageParam = never, > = SharedQueryFunctionContext -export type PlaceholderDataFunction< +type PlaceholderDataFunction< TQueryFnData = unknown, TError = DefaultError, TQueryData = TQueryFnData, @@ -253,7 +253,7 @@ export type PlaceholderDataFunction< TQueryData, TQueryKey > -export type QueryOptions< +type QueryOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -267,7 +267,7 @@ export type QueryOptions< TQueryKey, TPageParam > -export type ThrowOnError< +type ThrowOnError< TQueryFnData, TError, TQueryData, @@ -279,7 +279,7 @@ export type ThrowOnError< TQueryData, TQueryKey > -export type QueryObserverOptionsBase< +type QueryObserverOptionsBase< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -295,7 +295,7 @@ export type QueryObserverOptionsBase< TQueryKey, TPageParam > -export type QueryObserverOptions< +type QueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -311,7 +311,7 @@ export type QueryObserverOptions< TQueryKey, TPageParam > -export type DefaultedQueryObserverOptions< +type DefaultedQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -327,7 +327,7 @@ export type DefaultedQueryObserverOptions< TQueryKey, TPageParam > -export type InfiniteQueryObserverOptions< +type InfiniteQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -341,7 +341,7 @@ export type InfiniteQueryObserverOptions< TQueryKey, TPageParam > -export type DefaultedInfiniteQueryObserverOptions< +type DefaultedInfiniteQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -355,7 +355,7 @@ export type DefaultedInfiniteQueryObserverOptions< TQueryKey, TPageParam > -export type QueryExecuteOptions< +type QueryExecuteOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, @@ -371,7 +371,7 @@ export type QueryExecuteOptions< TQueryKey, TPageParam > -export type InfiniteQueryExecuteOptions< +type InfiniteQueryExecuteOptions< TQueryFnData = unknown, TError = DefaultError, TData = InfiniteData, @@ -385,17 +385,16 @@ export type InfiniteQueryExecuteOptions< TQueryKey, TPageParam > -export type InvalidateQueryFilters = +type InvalidateQueryFilters = SharedInvalidateQueryFilters -export type RefetchQueryFilters = +type RefetchQueryFilters = SharedRefetchQueryFilters -export type MutationFunctionContext = - SharedMutationFunctionContext -export type MutationFunction< +type MutationFunctionContext = SharedMutationFunctionContext +type MutationFunction< TData = unknown, TVariables = unknown, > = SharedMutationFunction -export type MutationOptions< +type MutationOptions< TData = unknown, TError = DefaultError, TVariables = void, @@ -407,7 +406,7 @@ export type MutationOptions< TVariables, TOnMutateResult > -export type MutationObserverOptions< +type MutationObserverOptions< TData = unknown, TError = DefaultError, TVariables = void, @@ -419,7 +418,7 @@ export type MutationObserverOptions< TVariables, TOnMutateResult > -export type MutateOptions< +type MutateOptions< TData = unknown, TError = DefaultError, TVariables = void, @@ -431,7 +430,7 @@ export type MutateOptions< TVariables, TOnMutateResult > -export type MutateFunctionRest< +type MutateFunctionRest< TData = unknown, TError = DefaultError, TVariables = void, @@ -443,7 +442,7 @@ export type MutateFunctionRest< TVariables, TOnMutateResult > -export type MutateFunction< +type MutateFunction< TData = unknown, TError = DefaultError, TVariables = void, @@ -455,7 +454,7 @@ export type MutateFunction< TVariables, TOnMutateResult > -export type MutationObserverBaseResult< +type MutationObserverBaseResult< TData = unknown, TError = DefaultError, TVariables = void, @@ -467,7 +466,7 @@ export type MutationObserverBaseResult< TVariables, TOnMutateResult > -export type MutationObserverIdleResult< +type MutationObserverIdleResult< TData = unknown, TError = DefaultError, TVariables = void, @@ -479,7 +478,7 @@ export type MutationObserverIdleResult< TVariables, TOnMutateResult > -export type MutationObserverLoadingResult< +type MutationObserverLoadingResult< TData = unknown, TError = DefaultError, TVariables = void, @@ -491,7 +490,7 @@ export type MutationObserverLoadingResult< TVariables, TOnMutateResult > -export type MutationObserverErrorResult< +type MutationObserverErrorResult< TData = unknown, TError = DefaultError, TVariables = void, @@ -503,7 +502,7 @@ export type MutationObserverErrorResult< TVariables, TOnMutateResult > -export type MutationObserverSuccessResult< +type MutationObserverSuccessResult< TData = unknown, TError = DefaultError, TVariables = void, @@ -515,7 +514,7 @@ export type MutationObserverSuccessResult< TVariables, TOnMutateResult > -export type MutationObserverResult< +type MutationObserverResult< TData = unknown, TError = DefaultError, TVariables = void, @@ -527,14 +526,16 @@ export type MutationObserverResult< TVariables, TOnMutateResult > -export type QueryClientConfig = SharedQueryClientConfig -export type DefaultOptions = SharedDefaultOptions< +type QueryClientConfig = SharedQueryClientConfig +type DefaultOptions = SharedDefaultOptions< DefaultRuntime, TError > -export type QueryFilters = - SharedQueryFilters -export type MutationFilters< +type QueryFilters = SharedQueryFilters< + DefaultRuntime, + TQueryKey +> +type MutationFilters< TData = unknown, TError = DefaultError, TVariables = unknown, @@ -553,3 +554,59 @@ export type { Query } from './contracts' export type { Mutation } from './contracts' export type { QueryObserver } from './contracts' export type { MutationObserver } from './contracts' +export type { + FocusManager, + OnlineManager, + TimeoutManager, + QueriesObserver, + InfiniteQueryObserver, + CancelledError, +} from './contracts' + +export type { + DehydrateOptions, + HydrateOptions, + MutationCacheConfig, + MutationCacheNotifyEvent, + FetchContext, + QueryBehavior, + QueryCacheConfig, + QueryCacheNotifyEvent, + QueryStore, + QueryObserverResultContext, + ObserverOptionsInput, + QueryFunction, + StaleTimeFunction, + QueryBooleanOption, + QueryPersister, + QueryFunctionContext, + PlaceholderDataFunction, + QueryOptions, + ThrowOnError, + QueryObserverOptionsBase, + QueryObserverOptions, + DefaultedQueryObserverOptions, + InfiniteQueryObserverOptions, + DefaultedInfiniteQueryObserverOptions, + QueryExecuteOptions, + InfiniteQueryExecuteOptions, + InvalidateQueryFilters, + RefetchQueryFilters, + MutationFunctionContext, + MutationFunction, + MutationOptions, + MutationObserverOptions, + MutateOptions, + MutateFunctionRest, + MutateFunction, + MutationObserverBaseResult, + MutationObserverIdleResult, + MutationObserverLoadingResult, + MutationObserverErrorResult, + MutationObserverSuccessResult, + MutationObserverResult, + QueryClientConfig, + DefaultOptions, + QueryFilters, + MutationFilters, +} diff --git a/packages/query-types/src/infiniteQueryObserver.ts b/packages/query-types/src/infiniteQueryObserver.ts index 4056817cabd..00a10a13581 100644 --- a/packages/query-types/src/infiniteQueryObserver.ts +++ b/packages/query-types/src/infiniteQueryObserver.ts @@ -6,11 +6,11 @@ import type { QueryKey, } from './types' -export type InfiniteQueryObserverListener = ( +type InfiniteQueryObserverListener = ( result: InfiniteQueryObserverResult, ) => void -export type InfiniteObserverOptionsInput< +type InfiniteObserverOptionsInput< TRuntime extends RuntimeBinding, TQueryFnData, TError, @@ -35,7 +35,13 @@ export type InfiniteObserverOptionsInput< TPageParam > -export type ReplaceReturnType< +type ReplaceReturnType< TFunction extends (...args: Array) => unknown, TReturn, > = (...args: Parameters) => TReturn + +export type { + InfiniteQueryObserverListener, + InfiniteObserverOptionsInput, + ReplaceReturnType, +} diff --git a/packages/query-types/src/mutation.ts b/packages/query-types/src/mutation.ts index bd4bbf1d641..bfa57e47dbc 100644 --- a/packages/query-types/src/mutation.ts +++ b/packages/query-types/src/mutation.ts @@ -1,7 +1,7 @@ import type { MutationCacheOf, QueryClientOf, RuntimeBinding } from './binding' import type { DefaultError, MutationOptions, MutationStatus } from './types' -export interface MutationConfig< +interface MutationConfig< TRuntime extends RuntimeBinding, TData, TError, @@ -66,34 +66,34 @@ export interface MutationState< submittedAt: number } -export interface MutationFailedAction { +interface MutationFailedAction { type: 'failed' failureCount: number error: TError | null } -export interface PendingAction { +interface PendingAction { type: 'pending' isPaused: boolean variables?: TVariables context?: TOnMutateResult } -export interface MutationSuccessAction { +interface MutationSuccessAction { type: 'success' data: TData } -export interface MutationErrorAction { +interface MutationErrorAction { type: 'error' error: TError } -export interface MutationPauseAction { +interface MutationPauseAction { type: 'pause' } -export interface MutationContinueAction { +interface MutationContinueAction { type: 'continue' } @@ -108,3 +108,13 @@ export type MutationAction = | PendingAction | MutationPauseAction | MutationSuccessAction + +export type { + MutationConfig, + MutationFailedAction, + PendingAction, + MutationSuccessAction, + MutationErrorAction, + MutationPauseAction, + MutationContinueAction, +} diff --git a/packages/query-types/src/mutationCache.ts b/packages/query-types/src/mutationCache.ts index 55c9ae9c378..37369002369 100644 --- a/packages/query-types/src/mutationCache.ts +++ b/packages/query-types/src/mutationCache.ts @@ -56,21 +56,21 @@ export interface MutationCacheConfig { ) => Promise | unknown } -export interface NotifyEventMutationAdded< +interface NotifyEventMutationAdded< TRuntime extends RuntimeBinding, > extends NotifyEvent { type: 'added' mutation: MutationOf } -export interface NotifyEventMutationRemoved< +interface NotifyEventMutationRemoved< TRuntime extends RuntimeBinding, > extends NotifyEvent { type: 'removed' mutation: MutationOf } -export interface NotifyEventMutationObserverAdded< +interface NotifyEventMutationObserverAdded< TRuntime extends RuntimeBinding, > extends NotifyEvent { type: 'observerAdded' @@ -78,7 +78,7 @@ export interface NotifyEventMutationObserverAdded< observer: MutationObserverOf } -export interface NotifyEventMutationObserverRemoved< +interface NotifyEventMutationObserverRemoved< TRuntime extends RuntimeBinding, > extends NotifyEvent { type: 'observerRemoved' @@ -86,7 +86,7 @@ export interface NotifyEventMutationObserverRemoved< observer: MutationObserverOf } -export interface NotifyEventMutationObserverOptionsUpdated< +interface NotifyEventMutationObserverOptionsUpdated< TRuntime extends RuntimeBinding, > extends NotifyEvent { type: 'observerOptionsUpdated' @@ -94,7 +94,7 @@ export interface NotifyEventMutationObserverOptionsUpdated< observer: MutationObserverOf } -export interface NotifyEventMutationUpdated< +interface NotifyEventMutationUpdated< TRuntime extends RuntimeBinding, > extends NotifyEvent { type: 'updated' @@ -115,6 +115,16 @@ export type MutationCacheNotifyEvent = | NotifyEventMutationObserverOptionsUpdated | NotifyEventMutationUpdated -export type MutationCacheListener = ( +type MutationCacheListener = ( event: MutationCacheNotifyEvent, ) => void + +export type { + NotifyEventMutationAdded, + NotifyEventMutationRemoved, + NotifyEventMutationObserverAdded, + NotifyEventMutationObserverRemoved, + NotifyEventMutationObserverOptionsUpdated, + NotifyEventMutationUpdated, + MutationCacheListener, +} diff --git a/packages/query-types/src/mutationObserver.ts b/packages/query-types/src/mutationObserver.ts index ce96e07d8ec..95da98d5c24 100644 --- a/packages/query-types/src/mutationObserver.ts +++ b/packages/query-types/src/mutationObserver.ts @@ -1,7 +1,7 @@ import type { RuntimeBinding } from './binding' import type { MutationObserverResult } from './types' -export type MutationObserverListener< +type MutationObserverListener< TRuntime extends RuntimeBinding, TData, TError, @@ -16,3 +16,5 @@ export type MutationObserverListener< TOnMutateResult >, ) => void + +export type { MutationObserverListener } diff --git a/packages/query-types/src/notifyManager.ts b/packages/query-types/src/notifyManager.ts index 3c729c1bbbd..173e937668f 100644 --- a/packages/query-types/src/notifyManager.ts +++ b/packages/query-types/src/notifyManager.ts @@ -1,9 +1,17 @@ -export type NotifyCallback = () => void +type NotifyCallback = () => void -export type NotifyFunction = (callback: () => void) => void +type NotifyFunction = (callback: () => void) => void -export type BatchNotifyFunction = (callback: () => void) => void +type BatchNotifyFunction = (callback: () => void) => void -export type BatchCallsCallback> = (...args: T) => void +type BatchCallsCallback> = (...args: T) => void -export type ScheduleFunction = (callback: () => void) => void +type ScheduleFunction = (callback: () => void) => void + +export type { + NotifyCallback, + NotifyFunction, + BatchNotifyFunction, + BatchCallsCallback, + ScheduleFunction, +} diff --git a/packages/query-types/src/onlineManager.ts b/packages/query-types/src/onlineManager.ts index fcbd1f1d006..f1dfb1e2955 100644 --- a/packages/query-types/src/onlineManager.ts +++ b/packages/query-types/src/onlineManager.ts @@ -1,5 +1,7 @@ -export type OnlineManagerListener = (online: boolean) => void +type OnlineManagerListener = (online: boolean) => void -export type OnlineManagerSetupFn = ( +type OnlineManagerSetupFn = ( setOnline: OnlineManagerListener, ) => (() => void) | undefined + +export type { OnlineManagerListener, OnlineManagerSetupFn } diff --git a/packages/query-types/src/queriesObserver.ts b/packages/query-types/src/queriesObserver.ts index 74b492a3f2a..a3ea53af738 100644 --- a/packages/query-types/src/queriesObserver.ts +++ b/packages/query-types/src/queriesObserver.ts @@ -5,11 +5,9 @@ import type { QueryObserverResult, } from './types' -export type QueriesObserverListener = ( - result: Array, -) => void +type QueriesObserverListener = (result: Array) => void -export type CombineFn = ( +type CombineFn = ( result: Array, ) => TCombinedResult @@ -21,7 +19,7 @@ export interface QueriesObserverResultReader< combineResult: (result: Array) => TCombinedResult } -export type CombineContext = { +type CombineContext = { result?: Array combine?: CombineFn value?: TCombinedResult @@ -45,8 +43,15 @@ export interface QueriesObserverOptions< combine?: CombineFn } -export type QueryObserverMatch = { +type QueryObserverMatch = { defaultedQueryOptions: DefaultedQueryObserverOptions observer: QueryObserverOf reader?: QueryObserverResultReader } + +export type { + QueriesObserverListener, + CombineFn, + CombineContext, + QueryObserverMatch, +} diff --git a/packages/query-types/src/query.ts b/packages/query-types/src/query.ts index 4c5041e1593..7e983dc670e 100644 --- a/packages/query-types/src/query.ts +++ b/packages/query-types/src/query.ts @@ -7,7 +7,7 @@ import type { QueryStatus, } from './types' -export interface QueryConfig< +interface QueryConfig< TRuntime extends RuntimeBinding, TQueryFnData, TError, @@ -191,42 +191,42 @@ export interface FetchOptions { initialPromise?: Promise } -export interface QueryFailedAction { +interface QueryFailedAction { type: 'failed' failureCount: number error: TError } -export interface FetchAction { +interface FetchAction { type: 'fetch' meta?: FetchMeta } -export interface QuerySuccessAction { +interface QuerySuccessAction { data: TData | undefined type: 'success' dataUpdatedAt?: number manual?: boolean } -export interface QueryErrorAction { +interface QueryErrorAction { type: 'error' error: TError } -export interface InvalidateAction { +interface InvalidateAction { type: 'invalidate' } -export interface QueryPauseAction { +interface QueryPauseAction { type: 'pause' } -export interface QueryContinueAction { +interface QueryContinueAction { type: 'continue' } -export interface SetStateAction { +interface SetStateAction { type: 'setState' state: Partial> } @@ -244,3 +244,15 @@ export type QueryAction = | QueryPauseAction | SetStateAction | QuerySuccessAction + +export type { + QueryConfig, + QueryFailedAction, + FetchAction, + QuerySuccessAction, + QueryErrorAction, + InvalidateAction, + QueryPauseAction, + QueryContinueAction, + SetStateAction, +} diff --git a/packages/query-types/src/queryCache.ts b/packages/query-types/src/queryCache.ts index cd75c838741..772c1eea27b 100644 --- a/packages/query-types/src/queryCache.ts +++ b/packages/query-types/src/queryCache.ts @@ -38,21 +38,21 @@ export interface QueryCacheConfig { ) => void } -export interface NotifyEventQueryAdded< +interface NotifyEventQueryAdded< TRuntime extends RuntimeBinding, > extends NotifyEvent { type: 'added' query: QueryOf } -export interface NotifyEventQueryRemoved< +interface NotifyEventQueryRemoved< TRuntime extends RuntimeBinding, > extends NotifyEvent { type: 'removed' query: QueryOf } -export interface NotifyEventQueryUpdated< +interface NotifyEventQueryUpdated< TRuntime extends RuntimeBinding, > extends NotifyEvent { type: 'updated' @@ -60,7 +60,7 @@ export interface NotifyEventQueryUpdated< action: QueryAction } -export interface NotifyEventQueryObserverAdded< +interface NotifyEventQueryObserverAdded< TRuntime extends RuntimeBinding, > extends NotifyEvent { type: 'observerAdded' @@ -68,7 +68,7 @@ export interface NotifyEventQueryObserverAdded< observer: QueryObserverOf } -export interface NotifyEventQueryObserverRemoved< +interface NotifyEventQueryObserverRemoved< TRuntime extends RuntimeBinding, > extends NotifyEvent { type: 'observerRemoved' @@ -76,14 +76,14 @@ export interface NotifyEventQueryObserverRemoved< observer: QueryObserverOf } -export interface NotifyEventQueryObserverResultsUpdated< +interface NotifyEventQueryObserverResultsUpdated< TRuntime extends RuntimeBinding, > extends NotifyEvent { type: 'observerResultsUpdated' query: QueryOf } -export interface NotifyEventQueryObserverOptionsUpdated< +interface NotifyEventQueryObserverOptionsUpdated< TRuntime extends RuntimeBinding, > extends NotifyEvent { type: 'observerOptionsUpdated' @@ -105,7 +105,7 @@ export type QueryCacheNotifyEvent = | NotifyEventQueryObserverResultsUpdated | NotifyEventQueryObserverOptionsUpdated -export type QueryCacheListener = ( +type QueryCacheListener = ( event: QueryCacheNotifyEvent, ) => void @@ -134,3 +134,14 @@ export interface QueryStore { */ values: () => IterableIterator> } + +export type { + NotifyEventQueryAdded, + NotifyEventQueryRemoved, + NotifyEventQueryUpdated, + NotifyEventQueryObserverAdded, + NotifyEventQueryObserverRemoved, + NotifyEventQueryObserverResultsUpdated, + NotifyEventQueryObserverOptionsUpdated, + QueryCacheListener, +} diff --git a/packages/query-types/src/queryClient.ts b/packages/query-types/src/queryClient.ts index 8ee82603d31..85738231202 100644 --- a/packages/query-types/src/queryClient.ts +++ b/packages/query-types/src/queryClient.ts @@ -8,19 +8,18 @@ import type { QueryOptions, } from './types' -export type WithoutSkipToken = Omit< - T, - 'queryFn' -> & { +type WithoutSkipToken = Omit & { queryFn?: Exclude } -export interface QueryDefaults { +interface QueryDefaults { queryKey: QueryKey defaultOptions: OmitKeyof, 'queryKey'> } -export interface MutationDefaults { +interface MutationDefaults { mutationKey: MutationKey defaultOptions: MutationOptions } + +export type { WithoutSkipToken, QueryDefaults, MutationDefaults } diff --git a/packages/query-types/src/queryObserver.ts b/packages/query-types/src/queryObserver.ts index 3981a974abc..f5a38d82f0e 100644 --- a/packages/query-types/src/queryObserver.ts +++ b/packages/query-types/src/queryObserver.ts @@ -9,11 +9,11 @@ import type { QueryOptions, } from './types' -export type QueryObserverListener = ( +type QueryObserverListener = ( result: QueryObserverResult, ) => void -export interface ObserverFetchOptions extends FetchOptions { +interface ObserverFetchOptions extends FetchOptions { throwOnError?: boolean } @@ -25,7 +25,7 @@ export interface QueryObserverResultReader { commit: () => void } -export type ProjectionFailure = { +type ProjectionFailure = { error: TError errorUpdatedAt: number } @@ -122,3 +122,5 @@ export type ObserverOptionsInput< TQueryData, TQueryKey > + +export type { QueryObserverListener, ObserverFetchOptions, ProjectionFailure } diff --git a/packages/query-types/src/retryer.ts b/packages/query-types/src/retryer.ts index 5060ff9902b..c156ad94458 100644 --- a/packages/query-types/src/retryer.ts +++ b/packages/query-types/src/retryer.ts @@ -1,6 +1,6 @@ import type { CancelOptions, DefaultError, NetworkMode } from './types' -export interface RetryerConfig { +interface RetryerConfig { fn: () => TData | Promise initialPromise?: Promise onCancel?: (error: TError) => void @@ -53,7 +53,7 @@ export interface Retryer { status: () => 'pending' | 'resolved' | 'rejected' } -export type RetryerStatus = 'pending' | 'resolved' | 'rejected' +type RetryerStatus = 'pending' | 'resolved' | 'rejected' /** @inline */ export type RetryValue = boolean | number | ShouldRetryFunction @@ -72,3 +72,5 @@ export type RetryDelayFunction = ( failureCount: number, error: TError, ) => number + +export type { RetryerConfig, RetryerStatus } diff --git a/packages/query-types/src/streamedQuery.ts b/packages/query-types/src/streamedQuery.ts index b3d799df924..dbd269045ba 100644 --- a/packages/query-types/src/streamedQuery.ts +++ b/packages/query-types/src/streamedQuery.ts @@ -1,7 +1,7 @@ import type { RuntimeBinding } from './binding' import type { QueryFunctionContext, QueryKey } from './types' -export type BaseStreamedQueryParams< +type BaseStreamedQueryParams< TRuntime extends RuntimeBinding, TQueryFnData, TQueryKey extends QueryKey, @@ -19,7 +19,7 @@ export type BaseStreamedQueryParams< refetchMode?: 'append' | 'reset' | 'replace' } -export type SimpleStreamedQueryParams< +type SimpleStreamedQueryParams< TRuntime extends RuntimeBinding, TQueryFnData, TQueryKey extends QueryKey, @@ -28,7 +28,7 @@ export type SimpleStreamedQueryParams< initialValue?: never } -export type ReducibleStreamedQueryParams< +type ReducibleStreamedQueryParams< TRuntime extends RuntimeBinding, TQueryFnData, TData, @@ -45,7 +45,7 @@ export type ReducibleStreamedQueryParams< initialValue: TData } -export type StreamedQueryParams< +type StreamedQueryParams< TRuntime extends RuntimeBinding, TQueryFnData, TData, @@ -53,3 +53,10 @@ export type StreamedQueryParams< > = | SimpleStreamedQueryParams | ReducibleStreamedQueryParams + +export type { + BaseStreamedQueryParams, + SimpleStreamedQueryParams, + ReducibleStreamedQueryParams, + StreamedQueryParams, +} diff --git a/packages/query-types/src/timeoutManager.ts b/packages/query-types/src/timeoutManager.ts index 24eb5fed13d..96b1ed69ccc 100644 --- a/packages/query-types/src/timeoutManager.ts +++ b/packages/query-types/src/timeoutManager.ts @@ -46,4 +46,6 @@ export type TimeoutProvider = readonly clearInterval: (intervalId: TTimerId | undefined) => void } -export type SystemTimerId = ReturnType +type SystemTimerId = ReturnType + +export type { SystemTimerId } diff --git a/packages/query-types/src/types.ts b/packages/query-types/src/types.ts index 1f1ff068988..97810bddcf4 100644 --- a/packages/query-types/src/types.ts +++ b/packages/query-types/src/types.ts @@ -3,15 +3,16 @@ import type { QueryCacheOf, QueryClientOf, QueryOf, + RefetchIntervalOf, RuntimeBinding, } from './binding' import type { DehydrateOptions, HydrateOptions } from './hydration' import type { MutationState } from './mutation' import type { RetryDelayValue, RetryValue } from './retryer' import type { + unsetMarker as UnsetMarker, dataTagErrorSymbol, dataTagSymbol, - unsetMarker as UnsetMarker, } from './symbols' import type { DefaultQueryFn, @@ -266,7 +267,8 @@ export type QueryFunctionContext< /** @inline */ export type InitialDataFunction = () => T | undefined -export type NonFunctionGuard = T extends Function ? never : T +// oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes every function-like value, including constructors, from the value branch +type NonFunctionGuard = T extends Function ? never : T /** @inline */ export type PlaceholderDataFunction< @@ -590,12 +592,13 @@ export interface QueryObserverOptionsBase< * If set to a function, the function will be executed with the latest data and query to compute a frequency * @defaultValue false */ - refetchInterval?: - | number - | false - | (( - query: QueryOf, - ) => number | false | undefined) + refetchInterval?: RefetchIntervalOf< + TRuntime, + TQueryFnData, + TError, + TQueryData, + TQueryKey + > /** * If set to `true`, the query will continue to refetch while their tab/window is in the background. * @defaultValue false @@ -860,7 +863,7 @@ export interface QueryExecuteOptions< > } -export type InfiniteQueryFetchPageOptions = Pick< +type InfiniteQueryFetchPageOptions = Pick< InfiniteQueryPageParamsOptions, 'initialPageParam' | 'getNextPageParam' > & { @@ -2550,3 +2553,5 @@ export interface NotifyEvent { */ type: NotifyEventType } + +export type { NonFunctionGuard, InfiniteQueryFetchPageOptions } diff --git a/packages/query-types/src/utils.ts b/packages/query-types/src/utils.ts index c97aa1ce003..5cacaf58b86 100644 --- a/packages/query-types/src/utils.ts +++ b/packages/query-types/src/utils.ts @@ -8,15 +8,16 @@ import type { QueryKey, } from './types' -export type DropLast> = T extends readonly [ +type DropLast> = T extends readonly [ ...infer R, unknown, ] ? readonly [...R] : never -export type TuplePrefixes> = - T extends readonly [] ? readonly [] : TuplePrefixes> | T +type TuplePrefixes> = T extends readonly [] + ? readonly [] + : TuplePrefixes> | T /** * Filters used to select queries, for example in `queryClient.getQueriesData` or `queryClient.invalidateQueries`. @@ -111,7 +112,9 @@ export type { skipToken as SkipToken } from './symbols' export type { defaultQueryFn as DefaultQueryFn } from './symbols' /** Internal view of a context that exposes its signal without consuming it. */ -export interface FetchSignalContext { +interface FetchSignalContext { readonly signal: AbortSignal readonly [fetchSignal]?: AbortSignal } + +export type { DropLast, TuplePrefixes, FetchSignalContext } diff --git a/packages/react-query-no-core-pluggable/README.md b/packages/react-query-no-core-pluggable/README.md index 85fbbf7b317..eaebe6d070f 100644 --- a/packages/react-query-no-core-pluggable/README.md +++ b/packages/react-query-no-core-pluggable/README.md @@ -1,46 +1,44 @@ # @tanstack/react-query-no-core-pluggable -An experimental ESM React Query adapter for React 19. The default client supports ordinary queries, including suspense, parallel queries, prefetching and query hydration. +An experimental ESM React Query adapter for React 19. Create a regular `QueryClient` to use queries, infinite queries and mutations. Import `refetchInterval` to enable polling for an observer. ```tsx import { QueryClient, QueryClientProvider, + refetchInterval, useQuery, } from '@tanstack/react-query-no-core-pluggable' const client = new QueryClient() -function Greeting() { +function Orders() { const { data } = useQuery({ - queryKey: ['greeting'], - queryFn: () => Promise.resolve('Hello'), + queryKey: ['orders'], + queryFn: fetchOrders, + refetchInterval: refetchInterval(3000), }) - return

{data}

+ return

{data?.length} orders

} export function App() { return ( - + ) } ``` -Import the plugins your application uses and register them on its client. Each client installs its own plugins and owns its caches. +`useQuery`, `useInfiniteQuery`, `useSuspenseQuery` and `useSuspenseInfiniteQuery` accept the same helper, as do query defaults. Pass a callback to compute the next interval from the cached query. Return `false` or `undefined` to stop polling. ```ts -import { - QueryClient, - infiniteQueryPlugin, - mutationPlugin, -} from '@tanstack/react-query-no-core-pluggable' - -const client = new QueryClient({ - plugins: [infiniteQueryPlugin, mutationPlugin], +useQuery({ + queryKey: ['job', jobId], + queryFn: () => fetchJob(jobId), + refetchInterval: (query) => + query.state.data?.status === 'complete' ? false : refetchInterval(3000), }) ``` -- `infiniteQueryPlugin` enables paginated fetching through `useInfiniteQuery`, `client.infiniteQuery` and their related APIs. Install it when restoring infinite queries from a server snapshot. -- `mutationPlugin` enables mutation observers, mutation state subscriptions and mutation hydration. To supply a custom cache, pass `mutationCache` alongside the plugin. +Polling runs while an enabled observer has subscribers and the window is focused. Set `refetchIntervalInBackground: true` to keep polling in the background. Each observer manages its own timer, including when several observers share a client default. diff --git a/packages/react-query-no-core-pluggable/package.json b/packages/react-query-no-core-pluggable/package.json index 16c19f5fd24..9e5d3b4083c 100644 --- a/packages/react-query-no-core-pluggable/package.json +++ b/packages/react-query-no-core-pluggable/package.json @@ -1,7 +1,7 @@ { "name": "@tanstack/react-query-no-core-pluggable", "version": "5.108.4", - "description": "React Query with a standalone runtime and opt-in mutation and infinite query plugins", + "description": "React Query with a standalone runtime and opt-in polling per query observer", "author": "tannerlinsley", "license": "MIT", "repository": { @@ -25,8 +25,8 @@ "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 run && node ../../scripts/test-react-query-compat.mjs", - "test:lib:dev": "vitest --watch", + "test:lib": "vitest run --typecheck src/__tests__ && node ../../scripts/test-react-query-compat.mjs", + "test:lib:dev": "vitest --watch src/__tests__", "test:build": "publint --strict && attw --pack --profile esm-only", "build": "tsdown --tsconfig tsconfig.prod.json" }, @@ -53,13 +53,9 @@ }, "devDependencies": { "@eslint-react/eslint-plugin": "catalog:", - "@testing-library/react": "catalog:", - "@testing-library/react-render-stream": "^2.0.2", "@types/react": "catalog:", - "@vitejs/plugin-react": "catalog:", "eslint-plugin-react-hooks": "catalog:", "react": "catalog:", - "react-dom": "catalog:", "typescript": "catalog:" }, "peerDependencies": { diff --git a/packages/react-query-no-core-pluggable/src/__tests__/plugins.test.ts b/packages/react-query-no-core-pluggable/src/__tests__/plugins.test.ts deleted file mode 100644 index bf629c167e4..00000000000 --- a/packages/react-query-no-core-pluggable/src/__tests__/plugins.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { - MutationCache, - MutationObserver, - QueryClient, - dehydrate, - hydrate, - infiniteQueryOptions, - infiniteQueryPlugin, - mutationPlugin, -} from '..' - -const pages = infiniteQueryOptions({ - queryKey: ['pages'], - initialPageParam: 1, - queryFn: ({ pageParam }) => pageParam, - getNextPageParam: (lastPage) => lastPage + 1, -}) - -describe('per-client plugins', () => { - it('fetches, hydrates, and clears query data with the default client', async () => { - const server = new QueryClient() - const client = new QueryClient() - - await server.query({ queryKey: ['answer'], queryFn: () => 42 }) - const snapshot = dehydrate(server) - expect(snapshot.mutations).toStrictEqual([]) - hydrate(client, snapshot) - expect(client.getQueryData(['answer'])).toBe(42) - expect(client.isMutating()).toBe(0) - await client.resumePausedMutations() - client.clear() - expect(client.getQueryData(['answer'])).toBeUndefined() - }) - - it('identifies missing plugins at their entry points', async () => { - const client = new QueryClient() - - expect(() => new MutationObserver(client, {})).toThrow('mutationPlugin') - await expect(client.infiniteQuery(pages)).rejects.toThrow( - 'infiniteQueryPlugin', - ) - expect(client.getQueryCache().getAll()).toHaveLength(0) - }) - - it('installs mutations on an individual client and honors a supplied cache', async () => { - const cache = new MutationCache() - const client = new QueryClient({ - plugins: [mutationPlugin], - mutationCache: cache, - }) - const other = new QueryClient({ plugins: [mutationPlugin] }) - - const observer = new MutationObserver(client, { - mutationFn: () => Promise.resolve(42), - }) - await expect(observer.mutate()).resolves.toBe(42) - expect(cache.getAll()).toHaveLength(1) - expect(other.getMutationCache().getAll()).toHaveLength(0) - const snapshot = dehydrate(client, { shouldDehydrateMutation: () => true }) - expect(() => hydrate(new QueryClient(), snapshot)).toThrow('mutationPlugin') - hydrate(other, snapshot) - expect(other.getMutationCache().getAll()[0]?.state.data).toBe(42) - await expect(client.infiniteQuery(pages)).rejects.toThrow( - 'infiniteQueryPlugin', - ) - }) - - it('fetches and restores pages independently of mutation support', async () => { - const server = new QueryClient({ plugins: [infiniteQueryPlugin] }) - const client = new QueryClient({ plugins: [infiniteQueryPlugin] }) - - const data = await server.infiniteQuery({ ...pages, pages: 2 }) - expect(data).toStrictEqual({ pages: [1, 2], pageParams: [1, 2] }) - const snapshot = dehydrate(server) - hydrate(client, snapshot) - await expect(client.infiniteQuery(pages)).resolves.toStrictEqual(data) - expect(() => client.getMutationCache()).toThrow('mutationPlugin') - }) -}) diff --git a/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test-d.ts b/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test-d.ts new file mode 100644 index 00000000000..6d76dde2046 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test-d.ts @@ -0,0 +1,57 @@ +import { describe, expectTypeOf, it } from 'vitest' +import { + refetchInterval, + useInfiniteQuery, + useQuery, + useSuspenseInfiniteQuery, + useSuspenseQuery, +} from '..' +import type { InfiniteData } from '..' + +describe('refetchInterval types', () => { + it('infers cached data in polling callbacks for regular and suspense hooks', () => { + const options = { queryKey: ['book'], queryFn: () => 'Dune' } + useQuery({ + ...options, + select: (book) => book.length, + refetchInterval: (query) => { + expectTypeOf(query.state.data).toEqualTypeOf() + return refetchInterval(query.state.data ? false : 3000) + }, + }) + useSuspenseQuery({ + ...options, + refetchInterval: (query) => { + expectTypeOf(query.state.data).toEqualTypeOf() + return undefined + }, + }) + }) + + it('infers cached pages in both infinite query hooks', () => { + const options = { + queryKey: ['list'], + initialPageParam: 1, + queryFn: () => 'Dune', + getNextPageParam: () => 2, + } + useInfiniteQuery({ + ...options, + refetchInterval: (query) => { + expectTypeOf(query.state.data).toEqualTypeOf< + InfiniteData | undefined + >() + return refetchInterval(3000) + }, + }) + useSuspenseInfiniteQuery({ + ...options, + refetchInterval: (query) => { + expectTypeOf(query.state.data).toEqualTypeOf< + InfiniteData | undefined + >() + return refetchInterval(3000) + }, + }) + }) +}) diff --git a/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test.ts b/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test.ts new file mode 100644 index 00000000000..b5c62ca3998 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test.ts @@ -0,0 +1,151 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + MutationObserver, + QueryClient, + QueryObserver, + environmentManager, + focusManager, + 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( + client.infiniteQuery({ + 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/react-query-no-core-pluggable/src/runtime/clientFeatures.ts b/packages/react-query-no-core-pluggable/src/runtime/clientFeatures.ts deleted file mode 100644 index c2c84dc09fc..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/clientFeatures.ts +++ /dev/null @@ -1,40 +0,0 @@ -import type { infiniteQueryBehavior } from './infiniteQueryBehavior' -import type { Mutation } from './mutation' -import type { MutationCache } from './mutationCache' -import type { QueryClient } from './queryClient' -import type { QueryClientConfig } from './types' - -/** Optional implementations owned by one query client. */ -export interface QueryClientFeatures { - /** Cache and builder shared by mutation observers and hydration. */ - mutations?: { - cache: MutationCache - build: typeof Mutation.build - } - /** Creates the fetch behavior for a paginated query. */ - infiniteQueryBehavior?: typeof infiniteQueryBehavior -} - -/** Installs optional behavior for one client, including caches owned by that client. */ -export type QueryClientPlugin = ( - features: QueryClientFeatures, - config: Readonly, -) => void - -export const clientFeatures = Symbol('clientFeatures') - -/** - * Looks up the mutation implementation for an operation that requires it. - * @param client - Client receiving the operation. - * @returns The installed mutation cache and builder. - * @throws {Error} When mutation support is missing from the client. - */ -export function requireMutations(client: QueryClient) { - const mutations = client[clientFeatures].mutations - if (!mutations) { - throw new Error( - 'Add mutationPlugin to the QueryClient plugins to use mutations.', - ) - } - return mutations -} diff --git a/packages/react-query-no-core-pluggable/src/runtime/hydration.ts b/packages/react-query-no-core-pluggable/src/runtime/hydration.ts index a206200ef9d..bafec476b72 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/hydration.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/hydration.ts @@ -1,4 +1,4 @@ -import { clientFeatures, requireMutations } from './clientFeatures' +import { Mutation } from './mutation' import { noop } from './utils' import type * as Shared from '@tanstack/query-types/bindings' import type { @@ -7,7 +7,6 @@ import type { DehydratedState, TransformerFn, } from '@tanstack/query-types/bindings' -import type { Mutation } from './mutation' import type { Query } from './query' import type { QueryClient } from './queryClient' import type { QueryRuntime } from './runtimeBinding' @@ -38,8 +37,10 @@ function tryResolveSync(promise: PromiseLike) { return undefined } +/** {@inheritDoc Shared.DehydrateOptions} */ export type DehydrateOptions = Shared.DehydrateOptions +/** {@inheritDoc Shared.HydrateOptions} */ export type HydrateOptions = Shared.HydrateOptions // FUNCTIONS @@ -183,11 +184,12 @@ export function dehydrate( client.getDefaultOptions().dehydrate?.shouldDehydrateMutation ?? defaultShouldDehydrateMutation - const mutations = ( - client[clientFeatures].mutations?.cache.getAll() ?? [] - ).flatMap((mutation) => - filterMutation(mutation) ? [dehydrateMutation(mutation)] : [], - ) + const mutations = client + .getMutationCache() + .getAll() + .flatMap((mutation) => + filterMutation(mutation) ? [dehydrateMutation(mutation)] : [], + ) const filterQuery = options.shouldDehydrateQuery ?? @@ -245,7 +247,7 @@ export function hydrate( client.getDefaultOptions().hydrate?.deserializeData dehydratedState.mutations?.forEach(({ state, ...mutationOptions }) => { - requireMutations(client).build( + Mutation.build( client, { ...client.getDefaultOptions().hydrate?.mutations, diff --git a/packages/react-query-no-core-pluggable/src/runtime/index.ts b/packages/react-query-no-core-pluggable/src/runtime/index.ts index dc08eafed78..ccd7586e985 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/index.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/index.ts @@ -1,7 +1,5 @@ /* istanbul ignore file */ -export { mutationPlugin, infiniteQueryPlugin } from './plugins' -export type { QueryClientFeatures, QueryClientPlugin } from './clientFeatures' export { focusManager } from './focusManager' export type { FocusManager } from './focusManager' export { environmentManager } from './environmentManager' @@ -23,6 +21,9 @@ export { QueriesObserver } from './queriesObserver' export { QueryCache } from './queryCache' export type { QueryCacheNotifyEvent } from './queryCache' export { QueryClient } from './queryClient' +export type { QueryRuntime } from './runtimeBinding' +export { refetchInterval } from './refetchInterval' +export type { RefetchInterval } from './refetchInterval' export { QueryObserver } from './queryObserver' export type { QueryObserverResultReader } from './queryObserver' export { CancelledError } from './retryer' diff --git a/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts b/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts index 5ebdcc079d7..c1d718aef25 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts @@ -7,8 +7,10 @@ import type { QueryRuntime } from './runtimeBinding' import type { DefaultError } from './types' import type { MutationFilters } from './utils' +/** {@inheritDoc Shared.MutationCacheConfig} */ export type MutationCacheConfig = Shared.MutationCacheConfig +/** {@inheritDoc Shared.MutationCacheNotifyEvent} */ export type MutationCacheNotifyEvent = Shared.MutationCacheNotifyEvent diff --git a/packages/react-query-no-core-pluggable/src/runtime/mutationObserver.ts b/packages/react-query-no-core-pluggable/src/runtime/mutationObserver.ts index a27291779f6..2feb3590d83 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/mutationObserver.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/mutationObserver.ts @@ -1,10 +1,9 @@ -import { requireMutations } from './clientFeatures' -import { getDefaultState } from './mutation' +import { Mutation, getDefaultState } from './mutation' import { notifyManager } from './notifyManager' import { Subscribable } from './subscribable' import { hashKeyByOptions, shallowEqualObjects } from './utils' import type * as Shared from '@tanstack/query-types/bindings' -import type { Action, Mutation } from './mutation' +import type { Action } from './mutation' import type { QueryClient } from './queryClient' import type { QueryRuntime } from './runtimeBinding' import type { @@ -235,10 +234,7 @@ export class MutationObserver< this.#currentMutation?.removeObserver(this) - this.#currentMutation = requireMutations(this.#client).build( - this.#client, - this.options, - ) + this.#currentMutation = Mutation.build(this.#client, this.options) this.#currentMutation.addObserver(this) diff --git a/packages/react-query-no-core-pluggable/src/runtime/plugins.ts b/packages/react-query-no-core-pluggable/src/runtime/plugins.ts deleted file mode 100644 index 05a8f7ee7cd..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/plugins.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { infiniteQueryBehavior } from './infiniteQueryBehavior' -import { Mutation } from './mutation' -import { MutationCache } from './mutationCache' -import type { QueryClientPlugin } from './clientFeatures' - -/** - * Enables mutation observers, caching and hydration on one client. - * @param features - The features being configured for this client. - * @param config - Client options, including any supplied mutation cache. - */ -export const mutationPlugin: QueryClientPlugin = (features, config) => { - features.mutations = { - cache: config.mutationCache ?? new MutationCache(), - build: Mutation.build, - } -} - -/** - * Enables page fetching for infinite queries on one client. - * @param features - The features being configured for this client. - */ -export const infiniteQueryPlugin: QueryClientPlugin = (features) => { - features.infiniteQueryBehavior = infiniteQueryBehavior -} diff --git a/packages/react-query-no-core-pluggable/src/runtime/query.ts b/packages/react-query-no-core-pluggable/src/runtime/query.ts index 279f2679e3d..d874a18146c 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/query.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/query.ts @@ -1,4 +1,4 @@ -import { clientFeatures } from './clientFeatures' +import { infiniteQueryBehavior } from './infiniteQueryBehavior' import { notifyManager } from './notifyManager' import { Removable } from './removable' import { CancelledError, canFetch, createRetryer } from './retryer' @@ -14,10 +14,9 @@ import { import type * as Shared from '@tanstack/query-types/bindings' import type { FetchOptions, - QueryAction as Action, + QueryAction, QueryState, } from '@tanstack/query-types/bindings' -import type { QueryClientFeatures } from './clientFeatures' import type { QueryCache } from './queryCache' import type { QueryClient } from './queryClient' import type { QueryObserver } from './queryObserver' @@ -41,6 +40,7 @@ type QueryConfig< TQueryKey extends QueryKey = QueryKey, > = Shared.QueryConfig +/** {@inheritDoc Shared.FetchContext} */ export type FetchContext< TQueryFnData, TError, @@ -48,6 +48,7 @@ export type FetchContext< TQueryKey extends QueryKey = QueryKey, > = Shared.FetchContext +/** {@inheritDoc Shared.QueryBehavior} */ export type QueryBehavior< TQueryFnData = unknown, TError = DefaultError, @@ -85,7 +86,7 @@ export class Query< queryHash: string options!: QueryOptions state: QueryState - #infiniteQueryBehavior?: QueryClientFeatures['infiniteQueryBehavior'] + #queryType?: 'infinite' #initialState: QueryState #revertState?: QueryState @@ -102,9 +103,9 @@ export class Query< this.#abortSignalConsumed = false this.#defaultOptions = config.defaultOptions - this.#client = config.client this.setOptions(config.options) this.observers = [] + this.#client = config.client this.#cache = this.#client.getQueryCache() this.queryKey = config.queryKey this.queryHash = config.queryHash @@ -125,8 +126,8 @@ export class Query< * @internal * @returns The type of the query, set from the `_type` option (e.g. `'infinite'`). */ - get queryType(): 'infinite' | undefined { - return this.#infiniteQueryBehavior ? 'infinite' : undefined + get queryType() { + return this.#queryType } /** @@ -143,22 +144,16 @@ export class Query< * the `initialData` from the new options, if any. * @internal * @param options - The new query options, merged on top of the query's default options. - * @throws {Error} When an infinite query is used without `infiniteQueryPlugin`. */ setOptions( options?: QueryOptions, ): void { - if (options?._type === 'infinite') { - const behavior = this.#client[clientFeatures].infiniteQueryBehavior - if (!behavior) { - throw new Error( - 'Add infiniteQueryPlugin to the QueryClient plugins to use infinite queries.', - ) - } - this.#infiniteQueryBehavior = behavior - } this.options = { ...this.#defaultOptions, ...options } + if (options?._type) { + this.#queryType = options._type + } + this.updateGcTime(this.options.gcTime) // oxlint-disable-next-line typescript/no-unnecessary-condition -- the constructor calls 'setOptions' before it assigns 'state' @@ -607,9 +602,10 @@ export class Query< state: this.state, fetchFn, } - if (this.#infiniteQueryBehavior) { - addSignalProperty(context) - const behavior = this.#infiniteQueryBehavior( + addSignalProperty(context) + + if (this.#queryType === 'infinite') { + const behavior = infiniteQueryBehavior( (this.options as { pages?: number }).pages, ) as QueryBehavior behavior.onFetch(context, this as unknown as Query) @@ -762,13 +758,13 @@ export class Query< #update( state: Partial>, - action: Action, + action: QueryAction, ): void { this.state = { ...this.state, ...state } this.#notify(action) } - #notify(action: Action): void { + #notify(action: QueryAction): void { notifyManager.batch(() => { // Keep the current iteration stable if an observer unsubscribes // synchronously while it is being notified. diff --git a/packages/react-query-no-core-pluggable/src/runtime/queryCache.ts b/packages/react-query-no-core-pluggable/src/runtime/queryCache.ts index 834a79a6eec..09179c347f3 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/queryCache.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/queryCache.ts @@ -14,12 +14,15 @@ import type { } from './types' import type { QueryFilters } from './utils' +/** {@inheritDoc Shared.QueryCacheConfig} */ export type QueryCacheConfig = Shared.QueryCacheConfig +/** {@inheritDoc Shared.QueryCacheNotifyEvent} */ export type QueryCacheNotifyEvent = Shared.QueryCacheNotifyEvent type QueryCacheListener = Shared.QueryCacheListener +/** {@inheritDoc Shared.QueryStore} */ export type QueryStore = Shared.QueryStore // CLASS diff --git a/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts b/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts index 8027eb4dca5..27030624dc6 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts @@ -1,5 +1,5 @@ -import { clientFeatures, requireMutations } from './clientFeatures' import { focusManager } from './focusManager' +import { MutationCache } from './mutationCache' import { notifyManager } from './notifyManager' import { onlineManager } from './onlineManager' import { QueryCache } from './queryCache' @@ -13,8 +13,6 @@ import { skipToken, } from './utils' import type { WithoutSkipToken } from '@tanstack/query-types/bindings' -import type { QueryClientFeatures } from './clientFeatures' -import type { MutationCache } from './mutationCache' import type { QueryState } from './query' import type { CacheKeyConfig, @@ -72,7 +70,7 @@ class KeyDefaults< /** * `QueryClient` is used to interact with a cache of queries and mutations. It owns a - * `QueryCache` and, with `mutationPlugin`, a `MutationCache`. It holds + * `QueryCache` and a `MutationCache` (creating default ones if none are passed in) and holds * the default options that are applied to queries and mutations created through it. * @example * ```ts @@ -89,20 +87,17 @@ class KeyDefaults< */ export class QueryClient { #queryCache: QueryCache - readonly [clientFeatures]: QueryClientFeatures = {} + #mutationCache: MutationCache #defaultOptions: DefaultOptions #queryDefaults = new KeyDefaults() - #mutationDefaults?: KeyDefaults + #mutationDefaults = new KeyDefaults() #mountCount: number #unsubscribeFocus?: () => void #unsubscribeOnline?: () => void constructor(config: QueryClientConfig = {}) { this.#queryCache = config.queryCache || new QueryCache() - for (const plugin of config.plugins ?? []) { - plugin(this[clientFeatures], config) - } - if (config.mutationCache) requireMutations(this) + this.#mutationCache = config.mutationCache || new MutationCache() this.#defaultOptions = config.defaultOptions || {} this.#mountCount = 0 } @@ -185,12 +180,7 @@ export class QueryClient { any >, >(filters?: NoInfer>): number { - return ( - this[clientFeatures].mutations?.cache.findAll({ - ...filters, - status: 'pending', - }).length ?? 0 - ) + return this.#mutationCache.findAll({ ...filters, status: 'pending' }).length } /** @@ -774,9 +764,8 @@ export class QueryClient { * ``` */ resumePausedMutations(): Promise { - const mutations = this[clientFeatures].mutations - if (mutations && onlineManager.isOnline()) { - return mutations.cache.resumePausedMutations() + if (onlineManager.isOnline()) { + return this.#mutationCache.resumePausedMutations() } return Promise.resolve() } @@ -802,15 +791,15 @@ export class QueryClient { * @returns The {@link MutationCache} instance. * @example * ```ts - * import { QueryClient, mutationPlugin } from '@tanstack/react-query-no-core-pluggable' + * import { QueryClient } from '@tanstack/react-query-no-core-pluggable' * - * const queryClient = new QueryClient({ plugins: [mutationPlugin] }) + * const queryClient = new QueryClient() * const mutationCache = queryClient.getMutationCache() * const mutations = mutationCache.findAll({ status: 'pending' }) * ``` */ getMutationCache(): MutationCache { - return requireMutations(this).cache + return this.#mutationCache } /** @@ -925,9 +914,11 @@ export class QueryClient { 'mutationKey' >, ): void { - const config = this.getMutationCache().config.mutationKey - this.#mutationDefaults ??= new KeyDefaults() - this.#mutationDefaults.set(mutationKey, options, config) + this.#mutationDefaults.set( + mutationKey, + options, + this.#mutationCache.config.mutationKey, + ) } /** @@ -945,11 +936,9 @@ export class QueryClient { getMutationDefaults( mutationKey: MutationKey, ): OmitKeyof, 'mutationKey'> { - return ( - this.#mutationDefaults?.get( - mutationKey, - this.getMutationCache().config.mutationKey, - ) ?? {} + return this.#mutationDefaults.get( + mutationKey, + this.#mutationCache.config.mutationKey, ) } @@ -1083,6 +1072,6 @@ export class QueryClient { */ clear(): void { this.#queryCache.clear() - this[clientFeatures].mutations?.cache.clear() + this.#mutationCache.clear() } } diff --git a/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts b/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts index 0f3861f4112..5c932a5ee2e 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts @@ -1,5 +1,4 @@ import { isServer as isServerEnvironment } from './environmentManager' -import { focusManager } from './focusManager' import { notifyManager } from './notifyManager' import { fetchState } from './query' import { Subscribable } from './subscribable' @@ -21,6 +20,7 @@ import type { } from '@tanstack/query-types/bindings' import type { Query, QueryState } from './query' import type { QueryClient } from './queryClient' +import type { PollingTimer } from './refetchInterval' import type { QueryRuntime } from './runtimeBinding' import type { ManagedTimerId } from './timeoutManager' import type { @@ -34,6 +34,7 @@ import type { RefetchOptions, } from './types' +/** {@inheritDoc Shared.QueryObserverResultContext} */ export type QueryObserverResultContext< TQueryFnData, TError, @@ -49,6 +50,7 @@ export type QueryObserverResultContext< TQueryKey > +/** {@inheritDoc Shared.ObserverOptionsInput} */ export type ObserverOptionsInput< TQueryFnData = unknown, TError = DefaultError, @@ -105,8 +107,7 @@ export class QueryObserver< // It will be used to pass the previous data and query to the placeholder function between renders. #lastQueryWithDefinedData?: Query #staleTimeoutId?: ManagedTimerId - #refetchIntervalId?: ManagedTimerId - #currentRefetchInterval?: number | false + #polling?: PollingTimer #trackedProps = new Set() constructor( @@ -191,7 +192,8 @@ export class QueryObserver< destroy(): void { this.listeners = new Set() this.#clearStaleTimeout() - this.#clearRefetchInterval() + this.#polling?.stop() + this.#polling = undefined this.#currentQuery.removeObserver(this) } @@ -281,18 +283,7 @@ export class QueryObserver< this.#updateStaleTimeout() } - const nextRefetchInterval = this.#computeRefetchInterval() - - // Update refetch interval if needed - if ( - mounted && - (this.#currentQuery !== prevQuery || - resolveQueryValue(this.options.enabled, this.#currentQuery) !== - resolveQueryValue(prevOptions.enabled, this.#currentQuery) || - nextRefetchInterval !== this.#currentRefetchInterval) - ) { - this.#updateRefetchInterval(nextRefetchInterval) - } + this.#updatePolling() } /** @@ -564,38 +555,23 @@ export class QueryObserver< }, timeout) } - #computeRefetchInterval() { - return ( - resolveQueryValue(this.options.refetchInterval, this.#currentQuery) ?? - false - ) - } - - #updateRefetchInterval(nextInterval: number | false): void { - this.#clearRefetchInterval() - - this.#currentRefetchInterval = nextInterval - - if ( - this.#currentRefetchInterval === 0 || - !this.#shouldScheduleTimer(this.#currentRefetchInterval) - ) { - return + #updatePolling(restart = false): void { + const option = this.options.refetchInterval + const polling = + typeof option === 'function' ? option(this.#currentQuery) : option + if (polling) { + this.#polling = polling.update(this, this.#polling, restart, () => + this.#executeFetch(), + ) + } else { + this.#polling?.stop() + this.#polling = undefined } - - this.#refetchIntervalId = timeoutManager.setInterval(() => { - if ( - this.options.refetchIntervalInBackground || - focusManager.isFocused() - ) { - this.#executeFetch() - } - }, this.#currentRefetchInterval) } #updateTimers(): void { this.#updateStaleTimeout() - this.#updateRefetchInterval(this.#computeRefetchInterval()) + this.#updatePolling(true) } #clearStaleTimeout(): void { @@ -605,13 +581,6 @@ export class QueryObserver< } } - #clearRefetchInterval(): void { - if (this.#refetchIntervalId !== undefined) { - timeoutManager.clearInterval(this.#refetchIntervalId) - this.#refetchIntervalId = undefined - } - } - #resolvePlaceholder( options: QueryObserverOptionsBase< TQueryFnData, diff --git a/packages/react-query-no-core-pluggable/src/runtime/refetchInterval.ts b/packages/react-query-no-core-pluggable/src/runtime/refetchInterval.ts new file mode 100644 index 00000000000..9a35dc7003c --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/refetchInterval.ts @@ -0,0 +1,95 @@ +import { isServer } from './environmentManager' +import { focusManager } from './focusManager' +import { timeoutManager } from './timeoutManager' +import { isValidTimeout } from './utils' + +interface PollingTimer { + query: object + delay: number + stop: () => void +} + +interface PollingObserver { + getCurrentQuery: () => TQuery + hasListeners: () => boolean + options: { + enabled?: boolean | ((query: TQuery) => boolean) + refetchIntervalInBackground?: boolean + } +} + +type Delay = number | false | undefined + +/** An observer option created by {@link refetchInterval}. */ +interface RefetchInterval { + value: Delay | ((query: TQuery) => Delay) + update: typeof updatePolling +} + +/** + * Polls an observed query after the specified delay in milliseconds. + * @param value - A delay or a callback that selects the delay for the current query. + * Returning zero, false or undefined stops the timer. + * @returns A polling option for a query hook or client defaults. + * @example + * ```ts + * useQuery({ queryKey: ['orders'], queryFn: fetchOrders, refetchInterval: refetchInterval(3000) }) + * ``` + */ +export function refetchInterval(value: Delay): RefetchInterval +export function refetchInterval( + value: Delay | ((query: TQuery) => Delay), +): RefetchInterval +export function refetchInterval( + value: Delay | ((query: TQuery) => Delay), +): RefetchInterval { + return { value, update: updatePolling } +} + +/** + * Reconciles one observer's timer with its current options and cached query. + * @param observer - Observer receiving the optional schedule. + * @param current - Timer installed during the preceding update. + * @param restart - Restarts the countdown after a query update or subscription. + * @param fetch - Refetches the observer's current query. + * @returns The active timer and its cleanup, when polling is enabled. + */ +function updatePolling( + this: RefetchInterval, + observer: PollingObserver, + current: PollingTimer | undefined, + restart: boolean, + fetch: () => void, +): PollingTimer | undefined { + const query = observer.getCurrentQuery() + const { value } = this + const delay = typeof value === 'function' ? value(query) : value + if (!observer.hasListeners()) return + + const { enabled } = observer.options + if ( + isServer() || + !isValidTimeout(delay) || + delay === 0 || + (typeof enabled === 'function' ? enabled(query) : enabled) === false + ) { + current?.stop() + return + } + if (!restart && current?.query === query && current.delay === delay) { + return current + } + current?.stop() + const id = timeoutManager.setInterval(() => { + if ( + observer.options.refetchIntervalInBackground || + focusManager.isFocused() + ) { + fetch() + } + }, delay) + + return { query, delay, stop: () => timeoutManager.clearInterval(id) } +} + +export type { PollingTimer, RefetchInterval } diff --git a/packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts b/packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts index 26f50dded36..c8e2a6691d2 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts @@ -6,44 +6,50 @@ import type { Query } from './query' import type { QueryCache } from './queryCache' import type { QueryClient } from './queryClient' import type { QueryObserver } from './queryObserver' -import type { QueryKey } from './types' +import type { RefetchInterval } from './refetchInterval' /** Binds shared option and callback types to the concrete classes in this runtime. */ export interface QueryRuntime extends RuntimeBinding { + /** Polling can be installed independently on each observed query. */ + refetchInterval: + | false + | RefetchInterval + | (( + query: this['Query'], + ) => false | undefined | RefetchInterval) + /** {@inheritDoc RuntimeBinding.QueryClient} */ QueryClient: QueryClient + /** {@inheritDoc RuntimeBinding.QueryCache} */ QueryCache: QueryCache + /** {@inheritDoc RuntimeBinding.MutationCache} */ MutationCache: MutationCache - Query: this['args'] extends [ - infer TQueryFnData, - infer TError, - infer TData, - infer TQueryKey extends QueryKey, - ] - ? Query - : never - Mutation: this['args'] extends [ - infer TData, - infer TError, - infer TVariables, - infer TOnMutateResult, - ] - ? Mutation - : never - QueryObserver: this['args'] extends [ - infer TQueryFnData, - infer TError, - infer TData, - infer TQueryData, - infer TQueryKey extends QueryKey, - ] - ? QueryObserver - : never - MutationObserver: this['args'] extends [ - infer TData, - infer TError, - infer TVariables, - infer TOnMutateResult, - ] - ? MutationObserver - : never + /** {@inheritDoc RuntimeBinding.Query} */ + Query: Query< + this['queryFnData'], + this['error'], + this['data'], + this['queryKey'][0] + > + /** {@inheritDoc RuntimeBinding.Mutation} */ + Mutation: Mutation< + this['data'], + this['error'], + this['variables'], + this['onMutateResult'] + > + /** {@inheritDoc RuntimeBinding.QueryObserver} */ + QueryObserver: QueryObserver< + this['queryFnData'], + this['error'], + this['data'], + this['queryData'], + this['queryKey'][0] + > + /** {@inheritDoc RuntimeBinding.MutationObserver} */ + MutationObserver: MutationObserver< + this['data'], + this['error'], + this['variables'], + this['onMutateResult'] + > } diff --git a/packages/react-query-no-core-pluggable/src/runtime/types.ts b/packages/react-query-no-core-pluggable/src/runtime/types.ts index b4bcad20394..f0baebff3e3 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/types.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/types.ts @@ -3,37 +3,35 @@ import type { DefaultError, InfiniteData, QueryKey, - UnsetMarker as unsetMarkerType, - dataTagErrorSymbol as dataTagErrorSymbolType, - dataTagSymbol as dataTagSymbolType, } from '@tanstack/query-types/bindings' -import type { QueryClientPlugin } from './clientFeatures' import type { QueryRuntime } from './runtimeBinding' -export const dataTagSymbol: dataTagSymbolType = Symbol.for( +export const dataTagSymbol: Shared.dataTagSymbol = Symbol.for( '@tanstack/query/dataTagSymbol', -) as dataTagSymbolType +) as Shared.dataTagSymbol /** * The type of the `dataTagSymbol` key, under which a {@link DataTag} stores its data type. */ export type dataTagSymbol = typeof dataTagSymbol -export const dataTagErrorSymbol: dataTagErrorSymbolType = Symbol.for( +export const dataTagErrorSymbol: Shared.dataTagErrorSymbol = Symbol.for( '@tanstack/query/dataTagErrorSymbol', -) as dataTagErrorSymbolType +) as Shared.dataTagErrorSymbol /** * The type of the `dataTagErrorSymbol` key, under which a {@link DataTag} stores its error type. */ export type dataTagErrorSymbol = typeof dataTagErrorSymbol -export const unsetMarker: unsetMarkerType = Symbol.for( +export const unsetMarker: Shared.UnsetMarker = Symbol.for( '@tanstack/query/unsetMarker', -) as unsetMarkerType +) as Shared.UnsetMarker +/** {@inheritDoc Shared.QueryFunction} */ export type QueryFunction< T = unknown, TQueryKey extends QueryKey = QueryKey, TPageParam = never, > = Shared.QueryFunction +/** {@inheritDoc Shared.StaleTimeFunction} */ export type StaleTimeFunction< TQueryFnData = unknown, TError = DefaultError, @@ -47,6 +45,7 @@ export type StaleTimeFunction< TQueryKey > +/** {@inheritDoc Shared.QueryBooleanOption} */ export type QueryBooleanOption< TQueryFnData = unknown, TError = DefaultError, @@ -60,12 +59,14 @@ export type QueryBooleanOption< TQueryKey > +/** {@inheritDoc Shared.QueryPersister} */ export type QueryPersister< T = unknown, TQueryKey extends QueryKey = QueryKey, TPageParam = never, > = Shared.QueryPersister +/** {@inheritDoc Shared.QueryFunctionContext} */ export type QueryFunctionContext< TQueryKey extends QueryKey = QueryKey, TPageParam = never, @@ -73,6 +74,7 @@ export type QueryFunctionContext< // oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes every function-like value, including constructors, from the value branch +/** {@inheritDoc Shared.PlaceholderDataFunction} */ export type PlaceholderDataFunction< TQueryFnData = unknown, TError = DefaultError, @@ -86,6 +88,7 @@ export type PlaceholderDataFunction< TQueryKey > +/** {@inheritDoc Shared.QueryOptions} */ export type QueryOptions< TQueryFnData = unknown, TError = DefaultError, @@ -101,6 +104,7 @@ export type QueryOptions< TPageParam > +/** {@inheritDoc Shared.ThrowOnError} */ export type ThrowOnError< TQueryFnData, TError, @@ -114,6 +118,7 @@ export type ThrowOnError< TQueryKey > +/** {@inheritDoc Shared.QueryObserverOptionsBase} */ export type QueryObserverOptionsBase< TQueryFnData = unknown, TError = DefaultError, @@ -131,6 +136,7 @@ export type QueryObserverOptionsBase< TPageParam > +/** {@inheritDoc Shared.QueryObserverOptions} */ export type QueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, @@ -148,6 +154,7 @@ export type QueryObserverOptions< TPageParam > +/** {@inheritDoc Shared.DefaultedQueryObserverOptions} */ export type DefaultedQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, @@ -165,6 +172,7 @@ export type DefaultedQueryObserverOptions< TPageParam > +/** {@inheritDoc Shared.InfiniteQueryObserverOptions} */ export type InfiniteQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, @@ -180,6 +188,7 @@ export type InfiniteQueryObserverOptions< TPageParam > +/** {@inheritDoc Shared.DefaultedInfiniteQueryObserverOptions} */ export type DefaultedInfiniteQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, @@ -195,6 +204,7 @@ export type DefaultedInfiniteQueryObserverOptions< TPageParam > +/** {@inheritDoc Shared.QueryExecuteOptions} */ export type QueryExecuteOptions< TQueryFnData = unknown, TError = DefaultError, @@ -212,6 +222,7 @@ export type QueryExecuteOptions< TPageParam > +/** {@inheritDoc Shared.InfiniteQueryExecuteOptions} */ export type InfiniteQueryExecuteOptions< TQueryFnData = unknown, TError = DefaultError, @@ -227,20 +238,25 @@ export type InfiniteQueryExecuteOptions< TPageParam > +/** {@inheritDoc Shared.InvalidateQueryFilters} */ export type InvalidateQueryFilters = Shared.InvalidateQueryFilters +/** {@inheritDoc Shared.RefetchQueryFilters} */ export type RefetchQueryFilters = Shared.RefetchQueryFilters +/** {@inheritDoc Shared.MutationFunctionContext} */ export type MutationFunctionContext = Shared.MutationFunctionContext +/** {@inheritDoc Shared.MutationFunction} */ export type MutationFunction< TData = unknown, TVariables = unknown, > = Shared.MutationFunction +/** {@inheritDoc Shared.MutationOptions} */ export type MutationOptions< TData = unknown, TError = DefaultError, @@ -254,6 +270,7 @@ export type MutationOptions< TOnMutateResult > +/** {@inheritDoc Shared.MutationObserverOptions} */ export type MutationObserverOptions< TData = unknown, TError = DefaultError, @@ -267,6 +284,7 @@ export type MutationObserverOptions< TOnMutateResult > +/** {@inheritDoc Shared.MutateOptions} */ export type MutateOptions< TData = unknown, TError = DefaultError, @@ -280,6 +298,7 @@ export type MutateOptions< TOnMutateResult > +/** {@inheritDoc Shared.MutateFunctionRest} */ export type MutateFunctionRest< TData = unknown, TError = DefaultError, @@ -293,6 +312,7 @@ export type MutateFunctionRest< TOnMutateResult > +/** {@inheritDoc Shared.MutateFunction} */ export type MutateFunction< TData = unknown, TError = DefaultError, @@ -306,6 +326,7 @@ export type MutateFunction< TOnMutateResult > +/** {@inheritDoc Shared.MutationObserverBaseResult} */ export type MutationObserverBaseResult< TData = unknown, TError = DefaultError, @@ -319,6 +340,7 @@ export type MutationObserverBaseResult< TOnMutateResult > +/** {@inheritDoc Shared.MutationObserverIdleResult} */ export type MutationObserverIdleResult< TData = unknown, TError = DefaultError, @@ -332,6 +354,7 @@ export type MutationObserverIdleResult< TOnMutateResult > +/** {@inheritDoc Shared.MutationObserverLoadingResult} */ export type MutationObserverLoadingResult< TData = unknown, TError = DefaultError, @@ -345,6 +368,7 @@ export type MutationObserverLoadingResult< TOnMutateResult > +/** {@inheritDoc Shared.MutationObserverErrorResult} */ export type MutationObserverErrorResult< TData = unknown, TError = DefaultError, @@ -358,6 +382,7 @@ export type MutationObserverErrorResult< TOnMutateResult > +/** {@inheritDoc Shared.MutationObserverSuccessResult} */ export type MutationObserverSuccessResult< TData = unknown, TError = DefaultError, @@ -371,6 +396,7 @@ export type MutationObserverSuccessResult< TOnMutateResult > +/** {@inheritDoc Shared.MutationObserverResult} */ export type MutationObserverResult< TData = unknown, TError = DefaultError, @@ -384,10 +410,10 @@ export type MutationObserverResult< TOnMutateResult > -export type QueryClientConfig = Shared.QueryClientConfig & { - plugins?: ReadonlyArray -} +/** {@inheritDoc Shared.QueryClientConfig} */ +export type QueryClientConfig = Shared.QueryClientConfig +/** {@inheritDoc Shared.DefaultOptions} */ export type DefaultOptions = Shared.DefaultOptions< QueryRuntime, TError diff --git a/packages/react-query-no-core-pluggable/src/runtime/utils.ts b/packages/react-query-no-core-pluggable/src/runtime/utils.ts index 2ffd6135e6a..39c95dfd394 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/utils.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/utils.ts @@ -2,10 +2,7 @@ import { timeoutManager } from './timeoutManager' import type * as Shared from '@tanstack/query-types/bindings' import type { DefaultQueryFn, - DefaultQueryFn as defaultQueryFnType, - FetchSignal as fetchSignalType, SkipToken, - SkipToken as skipTokenType, Updater, } from '@tanstack/query-types/bindings' import type { Mutation } from './mutation' @@ -21,9 +18,11 @@ import type { QueryOptions, } from './types' +/** {@inheritDoc Shared.QueryFilters} */ export type QueryFilters = Shared.QueryFilters +/** {@inheritDoc Shared.MutationFilters} */ export type MutationFilters< TData = unknown, TError = DefaultError, @@ -600,18 +599,18 @@ export function addToArray( * }) * ``` */ -export const skipToken: skipTokenType = Symbol.for( +export const skipToken: SkipToken = Symbol.for( '@tanstack/query/skipToken', -) as skipTokenType +) as SkipToken /** * Pass this as `queryFn` to use the query function configured on the client. * The defaults for the query key take precedence over the client's global query defaults. * If no query function is configured, a fetch fails with a `Missing queryFn` error. */ -export const defaultQueryFn: defaultQueryFnType = Symbol.for( +export const defaultQueryFn: DefaultQueryFn = Symbol.for( '@tanstack/query/defaultQueryFn', -) as defaultQueryFnType +) as DefaultQueryFn /** * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from @@ -691,9 +690,9 @@ export function shouldThrowError) => boolean>( return !!throwOnError } -export const fetchSignal: fetchSignalType = Symbol.for( +export const fetchSignal: Shared.FetchSignal = Symbol.for( '@tanstack/query/fetchSignal', -) as fetchSignalType +) as Shared.FetchSignal /** * Adds a lazy `signal` getter to an object, such as a query function context. The first time diff --git a/packages/react-query-no-core-pluggable/src/useBaseQuery.ts b/packages/react-query-no-core-pluggable/src/useBaseQuery.ts index 525dbc328d5..052bd5bb8b5 100644 --- a/packages/react-query-no-core-pluggable/src/useBaseQuery.ts +++ b/packages/react-query-no-core-pluggable/src/useBaseQuery.ts @@ -8,13 +8,13 @@ import { getHasError, useClearResetErrorBoundary, } from './errorBoundaryUtils' -import { noop, notifyManager } from './runtime/index' +import { useObserverSnapshot } from './useObserverSnapshot' import type { QueryClient, QueryKey, QueryObserver, QueryObserverResult, -} from './runtime/index' +} from './runtime' import type { suspenseQueryPolicy } from './suspense' import type { UseBaseQueryOptions } from './types' @@ -22,7 +22,7 @@ import type { UseBaseQueryOptions } from './types' * Base implementation shared by `useQuery`, `useInfiniteQuery`, `useSuspenseQuery`, and * `useSuspenseInfiniteQuery`. * @param options - The options passed to the calling hook. - * @param Observer - The observer class (`QueryObserver` or + * @param Observer - The query observer class (`QueryObserver` or * `InfiniteQueryObserver`). * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest * context will be used. @@ -111,28 +111,11 @@ export function useBaseQuery< errorResetBoundary, ) - React.useEffect(() => { - reader.commit() - }, [reader]) - - const shouldSubscribe = !isRestoring && subscribed - const result = React.useSyncExternalStore( - React.useCallback( - (onStoreChange) => { - const unsubscribe = shouldSubscribe - ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) - : noop - - // Update result to make sure we did not miss any query updates - // between creating the observer and subscribing to it. - observer.updateResult() - - return unsubscribe - }, - [observer, shouldSubscribe], - ), - reader.getSnapshot, - reader.getSnapshot, + const result = useObserverSnapshot( + observer, + reader, + !isRestoring && subscribed, + refreshQuery, ) // Handle error boundary @@ -153,3 +136,11 @@ export function useBaseQuery< ? observer.trackResult(result) : result } + +/** + * Refreshes the query after the observer subscribes. + * @param observer - The observer that was subscribed. + */ +function refreshQuery(observer: Pick): void { + observer.updateResult() +} diff --git a/packages/react-query-no-core-pluggable/src/useObserverSnapshot.ts b/packages/react-query-no-core-pluggable/src/useObserverSnapshot.ts new file mode 100644 index 00000000000..b02245410f1 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/useObserverSnapshot.ts @@ -0,0 +1,43 @@ +'use client' +import * as React from 'react' +import { notifyManager } from './runtime/notifyManager' +import { noop } from './runtime/utils' +import type { QueryObserverResultReader } from './runtime/queryObserver' + +interface ObserverStore { + subscribe: (listener: () => void) => () => void +} + +/** + * Commits a reader and subscribes React to its cached snapshots. + * @param observer - The observer that owns the subscription. + * @param reader - The reader scoped to the current render options. + * @param subscribed - Whether this render subscribes to updates. + * @param refresh - Includes updates that occurred before the subscription started. + * @returns The current snapshot. + */ +export function useObserverSnapshot( + observer: TObserver, + reader: QueryObserverResultReader, + subscribed: boolean, + refresh: (observer: TObserver) => void, +): TResult { + React.useEffect(() => { + reader.commit() + }, [reader]) + + return React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => { + const unsubscribe = subscribed + ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) + : noop + refresh(observer) + return unsubscribe + }, + [observer, subscribed, refresh], + ), + reader.getSnapshot, + reader.getSnapshot, + ) +} diff --git a/packages/react-query-no-core-pluggable/src/useQueries.ts b/packages/react-query-no-core-pluggable/src/useQueries.ts index 7854ac811bf..4f03e21813f 100644 --- a/packages/react-query-no-core-pluggable/src/useQueries.ts +++ b/packages/react-query-no-core-pluggable/src/useQueries.ts @@ -8,7 +8,8 @@ import { getHasError, useClearResetErrorBoundary, } from './errorBoundaryUtils' -import { QueriesObserver, noop, notifyManager } from './runtime/index' +import { QueriesObserver } from './runtime/queriesObserver' +import { useObserverSnapshot } from './useObserverSnapshot' import type { DefaultError, OmitKeyof, @@ -19,7 +20,7 @@ import type { QueryKey, QueryObserverOptions, ThrowOnError, -} from './runtime/index' +} from './runtime' import type { suspenseQueriesPolicy } from './suspense' import type { DefinedUseQueryResult, @@ -440,29 +441,11 @@ export function useBaseQueries< ) suspense?.readQueries(defaultedQueries, reader, client, errorResetBoundary) - // Commit the combine cache before subscription can start a fetch. - React.useEffect(() => { - reader.commit() - }, [reader]) - - const shouldSubscribe = !isRestoring && subscribed - const results = React.useSyncExternalStore( - React.useCallback( - (onStoreChange) => { - const unsubscribe = shouldSubscribe - ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) - : noop - - // Include cache updates that occurred before subscription. - observer - .getObservers() - .forEach((queryObserver) => queryObserver.updateResult()) - return unsubscribe - }, - [observer, shouldSubscribe], - ), - reader.getSnapshot, - reader.getSnapshot, + const results = useObserverSnapshot( + observer, + reader, + !isRestoring && subscribed, + refreshQueries, ) const firstErrorResult = results.find((result, index) => { @@ -485,3 +468,13 @@ export function useBaseQueries< return reader.combineResult(results) } + +/** + * Refreshes each query after the group subscribes. + * @param observer - The observer that was subscribed. + */ +function refreshQueries(observer: Pick): void { + observer + .getObservers() + .forEach((queryObserver) => queryObserver.updateResult()) +} diff --git a/packages/react-query-no-core-pluggable/test-setup.ts b/packages/react-query-no-core-pluggable/test-setup.ts deleted file mode 100644 index cc010a39cfd..00000000000 --- a/packages/react-query-no-core-pluggable/test-setup.ts +++ /dev/null @@ -1,16 +0,0 @@ -import '@testing-library/jest-dom/vitest' -import { act, cleanup as cleanupRTL } from '@testing-library/react' -import { cleanup as cleanupRRS } from '@testing-library/react-render-stream' -import { afterEach } from 'vitest' -import { notifyManager } from './src/runtime/index' - -// https://testing-library.com/docs/react-testing-library/api#cleanup -afterEach(() => { - cleanupRTL() - cleanupRRS() -}) - -// Wrap notifications with act to make sure React knows about React Query updates -notifyManager.setNotifyFunction((fn) => { - act(fn) -}) diff --git a/packages/react-query-no-core-pluggable/tests/compat-client.ts b/packages/react-query-no-core-pluggable/tests/compat-client.ts deleted file mode 100644 index a39bfc975f2..00000000000 --- a/packages/react-query-no-core-pluggable/tests/compat-client.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { - QueryClient as PluggableQueryClient, - infiniteQueryPlugin, - mutationPlugin, -} from '../src/runtime/index' -import type { QueryClientConfig } from '../src/runtime/index' - -/** Runs the upstream suites against a client with the full upstream feature set. */ -export class QueryClient extends PluggableQueryClient { - constructor(config?: QueryClientConfig) { - super({ ...config, plugins: [mutationPlugin, infiniteQueryPlugin] }) - } -} - -export type AdapterClientOptions = 'plugins' diff --git a/packages/react-query-no-core-pluggable/tests/compat-polling.ts b/packages/react-query-no-core-pluggable/tests/compat-polling.ts new file mode 100644 index 00000000000..458bc830135 --- /dev/null +++ b/packages/react-query-no-core-pluggable/tests/compat-polling.ts @@ -0,0 +1,6 @@ +export { refetchInterval } from '../src' + +export type IntervalInput = Extract< + TOption, + { value: unknown } +>['value'] diff --git a/packages/react-query-no-core-pluggable/tsconfig.json b/packages/react-query-no-core-pluggable/tsconfig.json index cae6ad65d3f..58e959cbe0f 100644 --- a/packages/react-query-no-core-pluggable/tsconfig.json +++ b/packages/react-query-no-core-pluggable/tsconfig.json @@ -5,12 +5,5 @@ "rootDir": ".", "jsx": "react-jsx" }, - "include": [ - "src", - "tests", - "test-setup.ts", - "*.config.ts", - "*.config.js", - "package.json" - ] + "include": ["src", "tests", "*.config.ts", "*.config.js", "package.json"] } diff --git a/packages/react-query-no-core-pluggable/vite.config.ts b/packages/react-query-no-core-pluggable/vite.config.ts deleted file mode 100644 index 79b96a728ee..00000000000 --- a/packages/react-query-no-core-pluggable/vite.config.ts +++ /dev/null @@ -1,33 +0,0 @@ -import react from '@vitejs/plugin-react' -import { defineConfig } from 'vitest/config' -import packageJson from './package.json' - -export default defineConfig({ - plugins: [react()], - // fix from https://github.com/vitest-dev/vitest/issues/6992#issuecomment-2509408660 - resolve: { - conditions: ['@tanstack/custom-condition'], - }, - environments: { - ssr: { - resolve: { - conditions: ['@tanstack/custom-condition'], - }, - }, - }, - test: { - name: packageJson.name, - dir: './src', - watch: false, - environment: 'jsdom', - setupFiles: ['test-setup.ts'], - coverage: { - enabled: !!process.env.CI, - provider: 'istanbul', - include: ['src/**/*'], - exclude: ['src/__tests__/**'], - }, - typecheck: { enabled: true }, - restoreMocks: true, - }, -}) diff --git a/packages/react-query-no-core/src/runtime/hydration.ts b/packages/react-query-no-core/src/runtime/hydration.ts index 25f4fd5cac7..bafec476b72 100644 --- a/packages/react-query-no-core/src/runtime/hydration.ts +++ b/packages/react-query-no-core/src/runtime/hydration.ts @@ -37,8 +37,10 @@ function tryResolveSync(promise: PromiseLike) { return undefined } +/** {@inheritDoc Shared.DehydrateOptions} */ export type DehydrateOptions = Shared.DehydrateOptions +/** {@inheritDoc Shared.HydrateOptions} */ export type HydrateOptions = Shared.HydrateOptions // FUNCTIONS diff --git a/packages/react-query-no-core/src/runtime/index.ts b/packages/react-query-no-core/src/runtime/index.ts index 0b313930aa5..bb8a1374dc2 100644 --- a/packages/react-query-no-core/src/runtime/index.ts +++ b/packages/react-query-no-core/src/runtime/index.ts @@ -21,6 +21,7 @@ export { QueriesObserver } from './queriesObserver' export { QueryCache } from './queryCache' export type { QueryCacheNotifyEvent } from './queryCache' export { QueryClient } from './queryClient' +export type { QueryRuntime } from './runtimeBinding' export { QueryObserver } from './queryObserver' export type { QueryObserverResultReader } from './queryObserver' export { CancelledError } from './retryer' diff --git a/packages/react-query-no-core/src/runtime/mutationCache.ts b/packages/react-query-no-core/src/runtime/mutationCache.ts index 5ebdcc079d7..c1d718aef25 100644 --- a/packages/react-query-no-core/src/runtime/mutationCache.ts +++ b/packages/react-query-no-core/src/runtime/mutationCache.ts @@ -7,8 +7,10 @@ import type { QueryRuntime } from './runtimeBinding' import type { DefaultError } from './types' import type { MutationFilters } from './utils' +/** {@inheritDoc Shared.MutationCacheConfig} */ export type MutationCacheConfig = Shared.MutationCacheConfig +/** {@inheritDoc Shared.MutationCacheNotifyEvent} */ export type MutationCacheNotifyEvent = Shared.MutationCacheNotifyEvent diff --git a/packages/react-query-no-core/src/runtime/query.ts b/packages/react-query-no-core/src/runtime/query.ts index fadde455f6e..d874a18146c 100644 --- a/packages/react-query-no-core/src/runtime/query.ts +++ b/packages/react-query-no-core/src/runtime/query.ts @@ -14,7 +14,7 @@ import { import type * as Shared from '@tanstack/query-types/bindings' import type { FetchOptions, - QueryAction as Action, + QueryAction, QueryState, } from '@tanstack/query-types/bindings' import type { QueryCache } from './queryCache' @@ -40,6 +40,7 @@ type QueryConfig< TQueryKey extends QueryKey = QueryKey, > = Shared.QueryConfig +/** {@inheritDoc Shared.FetchContext} */ export type FetchContext< TQueryFnData, TError, @@ -47,6 +48,7 @@ export type FetchContext< TQueryKey extends QueryKey = QueryKey, > = Shared.FetchContext +/** {@inheritDoc Shared.QueryBehavior} */ export type QueryBehavior< TQueryFnData = unknown, TError = DefaultError, @@ -756,13 +758,13 @@ export class Query< #update( state: Partial>, - action: Action, + action: QueryAction, ): void { this.state = { ...this.state, ...state } this.#notify(action) } - #notify(action: Action): void { + #notify(action: QueryAction): void { notifyManager.batch(() => { // Keep the current iteration stable if an observer unsubscribes // synchronously while it is being notified. diff --git a/packages/react-query-no-core/src/runtime/queryCache.ts b/packages/react-query-no-core/src/runtime/queryCache.ts index 834a79a6eec..09179c347f3 100644 --- a/packages/react-query-no-core/src/runtime/queryCache.ts +++ b/packages/react-query-no-core/src/runtime/queryCache.ts @@ -14,12 +14,15 @@ import type { } from './types' import type { QueryFilters } from './utils' +/** {@inheritDoc Shared.QueryCacheConfig} */ export type QueryCacheConfig = Shared.QueryCacheConfig +/** {@inheritDoc Shared.QueryCacheNotifyEvent} */ export type QueryCacheNotifyEvent = Shared.QueryCacheNotifyEvent type QueryCacheListener = Shared.QueryCacheListener +/** {@inheritDoc Shared.QueryStore} */ export type QueryStore = Shared.QueryStore // CLASS diff --git a/packages/react-query-no-core/src/runtime/queryObserver.ts b/packages/react-query-no-core/src/runtime/queryObserver.ts index 0f3861f4112..6973a997b58 100644 --- a/packages/react-query-no-core/src/runtime/queryObserver.ts +++ b/packages/react-query-no-core/src/runtime/queryObserver.ts @@ -34,6 +34,7 @@ import type { RefetchOptions, } from './types' +/** {@inheritDoc Shared.QueryObserverResultContext} */ export type QueryObserverResultContext< TQueryFnData, TError, @@ -49,6 +50,7 @@ export type QueryObserverResultContext< TQueryKey > +/** {@inheritDoc Shared.ObserverOptionsInput} */ export type ObserverOptionsInput< TQueryFnData = unknown, TError = DefaultError, diff --git a/packages/react-query-no-core/src/runtime/runtimeBinding.ts b/packages/react-query-no-core/src/runtime/runtimeBinding.ts index 26f50dded36..cbc72e7b585 100644 --- a/packages/react-query-no-core/src/runtime/runtimeBinding.ts +++ b/packages/react-query-no-core/src/runtime/runtimeBinding.ts @@ -6,44 +6,42 @@ import type { Query } from './query' import type { QueryCache } from './queryCache' import type { QueryClient } from './queryClient' import type { QueryObserver } from './queryObserver' -import type { QueryKey } from './types' /** Binds shared option and callback types to the concrete classes in this runtime. */ export interface QueryRuntime extends RuntimeBinding { + /** {@inheritDoc RuntimeBinding.QueryClient} */ QueryClient: QueryClient + /** {@inheritDoc RuntimeBinding.QueryCache} */ QueryCache: QueryCache + /** {@inheritDoc RuntimeBinding.MutationCache} */ MutationCache: MutationCache - Query: this['args'] extends [ - infer TQueryFnData, - infer TError, - infer TData, - infer TQueryKey extends QueryKey, - ] - ? Query - : never - Mutation: this['args'] extends [ - infer TData, - infer TError, - infer TVariables, - infer TOnMutateResult, - ] - ? Mutation - : never - QueryObserver: this['args'] extends [ - infer TQueryFnData, - infer TError, - infer TData, - infer TQueryData, - infer TQueryKey extends QueryKey, - ] - ? QueryObserver - : never - MutationObserver: this['args'] extends [ - infer TData, - infer TError, - infer TVariables, - infer TOnMutateResult, - ] - ? MutationObserver - : never + /** {@inheritDoc RuntimeBinding.Query} */ + Query: Query< + this['queryFnData'], + this['error'], + this['data'], + this['queryKey'][0] + > + /** {@inheritDoc RuntimeBinding.Mutation} */ + Mutation: Mutation< + this['data'], + this['error'], + this['variables'], + this['onMutateResult'] + > + /** {@inheritDoc RuntimeBinding.QueryObserver} */ + QueryObserver: QueryObserver< + this['queryFnData'], + this['error'], + this['data'], + this['queryData'], + this['queryKey'][0] + > + /** {@inheritDoc RuntimeBinding.MutationObserver} */ + MutationObserver: MutationObserver< + this['data'], + this['error'], + this['variables'], + this['onMutateResult'] + > } diff --git a/packages/react-query-no-core/src/runtime/types.ts b/packages/react-query-no-core/src/runtime/types.ts index 67aa6619cf5..f0baebff3e3 100644 --- a/packages/react-query-no-core/src/runtime/types.ts +++ b/packages/react-query-no-core/src/runtime/types.ts @@ -3,36 +3,35 @@ import type { DefaultError, InfiniteData, QueryKey, - UnsetMarker as unsetMarkerType, - dataTagErrorSymbol as dataTagErrorSymbolType, - dataTagSymbol as dataTagSymbolType, } from '@tanstack/query-types/bindings' import type { QueryRuntime } from './runtimeBinding' -export const dataTagSymbol: dataTagSymbolType = Symbol.for( +export const dataTagSymbol: Shared.dataTagSymbol = Symbol.for( '@tanstack/query/dataTagSymbol', -) as dataTagSymbolType +) as Shared.dataTagSymbol /** * The type of the `dataTagSymbol` key, under which a {@link DataTag} stores its data type. */ export type dataTagSymbol = typeof dataTagSymbol -export const dataTagErrorSymbol: dataTagErrorSymbolType = Symbol.for( +export const dataTagErrorSymbol: Shared.dataTagErrorSymbol = Symbol.for( '@tanstack/query/dataTagErrorSymbol', -) as dataTagErrorSymbolType +) as Shared.dataTagErrorSymbol /** * The type of the `dataTagErrorSymbol` key, under which a {@link DataTag} stores its error type. */ export type dataTagErrorSymbol = typeof dataTagErrorSymbol -export const unsetMarker: unsetMarkerType = Symbol.for( +export const unsetMarker: Shared.UnsetMarker = Symbol.for( '@tanstack/query/unsetMarker', -) as unsetMarkerType +) as Shared.UnsetMarker +/** {@inheritDoc Shared.QueryFunction} */ export type QueryFunction< T = unknown, TQueryKey extends QueryKey = QueryKey, TPageParam = never, > = Shared.QueryFunction +/** {@inheritDoc Shared.StaleTimeFunction} */ export type StaleTimeFunction< TQueryFnData = unknown, TError = DefaultError, @@ -46,6 +45,7 @@ export type StaleTimeFunction< TQueryKey > +/** {@inheritDoc Shared.QueryBooleanOption} */ export type QueryBooleanOption< TQueryFnData = unknown, TError = DefaultError, @@ -59,12 +59,14 @@ export type QueryBooleanOption< TQueryKey > +/** {@inheritDoc Shared.QueryPersister} */ export type QueryPersister< T = unknown, TQueryKey extends QueryKey = QueryKey, TPageParam = never, > = Shared.QueryPersister +/** {@inheritDoc Shared.QueryFunctionContext} */ export type QueryFunctionContext< TQueryKey extends QueryKey = QueryKey, TPageParam = never, @@ -72,6 +74,7 @@ export type QueryFunctionContext< // oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes every function-like value, including constructors, from the value branch +/** {@inheritDoc Shared.PlaceholderDataFunction} */ export type PlaceholderDataFunction< TQueryFnData = unknown, TError = DefaultError, @@ -85,6 +88,7 @@ export type PlaceholderDataFunction< TQueryKey > +/** {@inheritDoc Shared.QueryOptions} */ export type QueryOptions< TQueryFnData = unknown, TError = DefaultError, @@ -100,6 +104,7 @@ export type QueryOptions< TPageParam > +/** {@inheritDoc Shared.ThrowOnError} */ export type ThrowOnError< TQueryFnData, TError, @@ -113,6 +118,7 @@ export type ThrowOnError< TQueryKey > +/** {@inheritDoc Shared.QueryObserverOptionsBase} */ export type QueryObserverOptionsBase< TQueryFnData = unknown, TError = DefaultError, @@ -130,6 +136,7 @@ export type QueryObserverOptionsBase< TPageParam > +/** {@inheritDoc Shared.QueryObserverOptions} */ export type QueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, @@ -147,6 +154,7 @@ export type QueryObserverOptions< TPageParam > +/** {@inheritDoc Shared.DefaultedQueryObserverOptions} */ export type DefaultedQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, @@ -164,6 +172,7 @@ export type DefaultedQueryObserverOptions< TPageParam > +/** {@inheritDoc Shared.InfiniteQueryObserverOptions} */ export type InfiniteQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, @@ -179,6 +188,7 @@ export type InfiniteQueryObserverOptions< TPageParam > +/** {@inheritDoc Shared.DefaultedInfiniteQueryObserverOptions} */ export type DefaultedInfiniteQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, @@ -194,6 +204,7 @@ export type DefaultedInfiniteQueryObserverOptions< TPageParam > +/** {@inheritDoc Shared.QueryExecuteOptions} */ export type QueryExecuteOptions< TQueryFnData = unknown, TError = DefaultError, @@ -211,6 +222,7 @@ export type QueryExecuteOptions< TPageParam > +/** {@inheritDoc Shared.InfiniteQueryExecuteOptions} */ export type InfiniteQueryExecuteOptions< TQueryFnData = unknown, TError = DefaultError, @@ -226,20 +238,25 @@ export type InfiniteQueryExecuteOptions< TPageParam > +/** {@inheritDoc Shared.InvalidateQueryFilters} */ export type InvalidateQueryFilters = Shared.InvalidateQueryFilters +/** {@inheritDoc Shared.RefetchQueryFilters} */ export type RefetchQueryFilters = Shared.RefetchQueryFilters +/** {@inheritDoc Shared.MutationFunctionContext} */ export type MutationFunctionContext = Shared.MutationFunctionContext +/** {@inheritDoc Shared.MutationFunction} */ export type MutationFunction< TData = unknown, TVariables = unknown, > = Shared.MutationFunction +/** {@inheritDoc Shared.MutationOptions} */ export type MutationOptions< TData = unknown, TError = DefaultError, @@ -253,6 +270,7 @@ export type MutationOptions< TOnMutateResult > +/** {@inheritDoc Shared.MutationObserverOptions} */ export type MutationObserverOptions< TData = unknown, TError = DefaultError, @@ -266,6 +284,7 @@ export type MutationObserverOptions< TOnMutateResult > +/** {@inheritDoc Shared.MutateOptions} */ export type MutateOptions< TData = unknown, TError = DefaultError, @@ -279,6 +298,7 @@ export type MutateOptions< TOnMutateResult > +/** {@inheritDoc Shared.MutateFunctionRest} */ export type MutateFunctionRest< TData = unknown, TError = DefaultError, @@ -292,6 +312,7 @@ export type MutateFunctionRest< TOnMutateResult > +/** {@inheritDoc Shared.MutateFunction} */ export type MutateFunction< TData = unknown, TError = DefaultError, @@ -305,6 +326,7 @@ export type MutateFunction< TOnMutateResult > +/** {@inheritDoc Shared.MutationObserverBaseResult} */ export type MutationObserverBaseResult< TData = unknown, TError = DefaultError, @@ -318,6 +340,7 @@ export type MutationObserverBaseResult< TOnMutateResult > +/** {@inheritDoc Shared.MutationObserverIdleResult} */ export type MutationObserverIdleResult< TData = unknown, TError = DefaultError, @@ -331,6 +354,7 @@ export type MutationObserverIdleResult< TOnMutateResult > +/** {@inheritDoc Shared.MutationObserverLoadingResult} */ export type MutationObserverLoadingResult< TData = unknown, TError = DefaultError, @@ -344,6 +368,7 @@ export type MutationObserverLoadingResult< TOnMutateResult > +/** {@inheritDoc Shared.MutationObserverErrorResult} */ export type MutationObserverErrorResult< TData = unknown, TError = DefaultError, @@ -357,6 +382,7 @@ export type MutationObserverErrorResult< TOnMutateResult > +/** {@inheritDoc Shared.MutationObserverSuccessResult} */ export type MutationObserverSuccessResult< TData = unknown, TError = DefaultError, @@ -370,6 +396,7 @@ export type MutationObserverSuccessResult< TOnMutateResult > +/** {@inheritDoc Shared.MutationObserverResult} */ export type MutationObserverResult< TData = unknown, TError = DefaultError, @@ -383,8 +410,10 @@ export type MutationObserverResult< TOnMutateResult > +/** {@inheritDoc Shared.QueryClientConfig} */ export type QueryClientConfig = Shared.QueryClientConfig +/** {@inheritDoc Shared.DefaultOptions} */ export type DefaultOptions = Shared.DefaultOptions< QueryRuntime, TError diff --git a/packages/react-query-no-core/src/runtime/utils.ts b/packages/react-query-no-core/src/runtime/utils.ts index 2ffd6135e6a..39c95dfd394 100644 --- a/packages/react-query-no-core/src/runtime/utils.ts +++ b/packages/react-query-no-core/src/runtime/utils.ts @@ -2,10 +2,7 @@ import { timeoutManager } from './timeoutManager' import type * as Shared from '@tanstack/query-types/bindings' import type { DefaultQueryFn, - DefaultQueryFn as defaultQueryFnType, - FetchSignal as fetchSignalType, SkipToken, - SkipToken as skipTokenType, Updater, } from '@tanstack/query-types/bindings' import type { Mutation } from './mutation' @@ -21,9 +18,11 @@ import type { QueryOptions, } from './types' +/** {@inheritDoc Shared.QueryFilters} */ export type QueryFilters = Shared.QueryFilters +/** {@inheritDoc Shared.MutationFilters} */ export type MutationFilters< TData = unknown, TError = DefaultError, @@ -600,18 +599,18 @@ export function addToArray( * }) * ``` */ -export const skipToken: skipTokenType = Symbol.for( +export const skipToken: SkipToken = Symbol.for( '@tanstack/query/skipToken', -) as skipTokenType +) as SkipToken /** * Pass this as `queryFn` to use the query function configured on the client. * The defaults for the query key take precedence over the client's global query defaults. * If no query function is configured, a fetch fails with a `Missing queryFn` error. */ -export const defaultQueryFn: defaultQueryFnType = Symbol.for( +export const defaultQueryFn: DefaultQueryFn = Symbol.for( '@tanstack/query/defaultQueryFn', -) as defaultQueryFnType +) as DefaultQueryFn /** * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from @@ -691,9 +690,9 @@ export function shouldThrowError) => boolean>( return !!throwOnError } -export const fetchSignal: fetchSignalType = Symbol.for( +export const fetchSignal: Shared.FetchSignal = Symbol.for( '@tanstack/query/fetchSignal', -) as fetchSignalType +) as Shared.FetchSignal /** * Adds a lazy `signal` getter to an object, such as a query function context. The first time diff --git a/packages/react-query/src/__tests__/mutationOptions.test.tsx b/packages/react-query/src/__tests__/mutationOptions.test.tsx index 4cc045f532c..be363462832 100644 --- a/packages/react-query/src/__tests__/mutationOptions.test.tsx +++ b/packages/react-query/src/__tests__/mutationOptions.test.tsx @@ -1,7 +1,8 @@ +import { QueryClient } from '@tanstack/query-core' import { createKey, sleep } from '@tanstack/query-test-utils' import { fireEvent } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { QueryClient, useIsMutating, useMutation, useMutationState } from '..' +import { useIsMutating, useMutation, useMutationState } from '..' import { mutationOptions } from '../mutationOptions' import { renderWithClient } from './utils' import type { UseMutationOptions } from '../types' diff --git a/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test-d.tsx b/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test-d.tsx index 6f16f5d178c..c117dc98cc5 100644 --- a/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test-d.tsx @@ -1,4 +1,5 @@ import { createKey } from '@tanstack/query-test-utils' +import { refetchInterval } from '@tanstack/query-test-utils/polling' import { assertType, describe, expectTypeOf, it } from 'vitest' import { skipToken, usePrefetchInfiniteQuery } from '..' @@ -32,7 +33,7 @@ describe('usePrefetchInfiniteQuery', () => { initialPageParam: 1, getNextPageParam: () => 1, // @ts-expect-error TS2353 - refetchInterval: 1000, + refetchInterval: refetchInterval(1000), }), ) diff --git a/packages/react-query/src/__tests__/usePrefetchQuery.test-d.tsx b/packages/react-query/src/__tests__/usePrefetchQuery.test-d.tsx index 700f4e19e46..f48b05158b1 100644 --- a/packages/react-query/src/__tests__/usePrefetchQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/usePrefetchQuery.test-d.tsx @@ -1,4 +1,5 @@ import { createKey } from '@tanstack/query-test-utils' +import { refetchInterval } from '@tanstack/query-test-utils/polling' import { assertType, describe, expectTypeOf, it } from 'vitest' import { skipToken, usePrefetchQuery } from '..' @@ -18,7 +19,7 @@ describe('usePrefetchQuery', () => { queryKey: createKey(), queryFn: () => Promise.resolve(5), // @ts-expect-error TS2345 - refetchInterval: 1000, + refetchInterval: refetchInterval(1000), }), ) diff --git a/packages/react-query/src/__tests__/useQuery.test.tsx b/packages/react-query/src/__tests__/useQuery.test.tsx index edd9fb80c4b..457658026bc 100644 --- a/packages/react-query/src/__tests__/useQuery.test.tsx +++ b/packages/react-query/src/__tests__/useQuery.test.tsx @@ -3,6 +3,7 @@ import { mockVisibilityState, sleep, } from '@tanstack/query-test-utils' +import { refetchInterval } from '@tanstack/query-test-utils/polling' import { act, fireEvent, render, renderHook } from '@testing-library/react' import * as React from 'react' import { ErrorBoundary } from 'react-error-boundary' @@ -4039,7 +4040,7 @@ describe('useQuery', () => { const { data } = useQuery({ queryKey: key, queryFn: () => count++, - refetchInterval: int, + refetchInterval: refetchInterval(int), }) React.useEffect(() => { @@ -4071,7 +4072,8 @@ describe('useQuery', () => { const queryInfo = useQuery({ queryKey: key, queryFn: () => sleep(10).then(() => count++), - refetchInterval: ({ state: { data = 0 } }) => (data < 2 ? 10 : false), + refetchInterval: ({ state: { data = 0 } }) => + refetchInterval(data < 2 ? 10 : false), }) states.push(queryInfo) @@ -4135,7 +4137,7 @@ describe('useQuery', () => { const queryInfo = useQuery({ queryKey: key, queryFn, - refetchInterval: 0, + refetchInterval: refetchInterval(0), }) return
count: {queryInfo.data}
diff --git a/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx b/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx index 67b5d31e6ca..7714d4fd4d7 100644 --- a/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx +++ b/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { refetchInterval } from '@tanstack/query-test-utils/polling' import { act, fireEvent } from '@testing-library/react' import * as React from 'react' import { ErrorBoundary } from 'react-error-boundary' @@ -1211,7 +1212,7 @@ describe('useSuspenseQuery', () => { const state = useSuspenseQuery({ queryKey: key, queryFn: () => sleep(10).then(() => ++count), - refetchInterval: 10, + refetchInterval: refetchInterval(10), }) return
count: {state.data}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6d2631c6732..2d22aca9c32 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -8265,27 +8265,15 @@ importers: '@eslint-react/eslint-plugin': specifier: 'catalog:' version: 5.28.8(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3) - '@testing-library/react': - specifier: 'catalog:' - version: 16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) - '@testing-library/react-render-stream': - specifier: ^2.0.2 - version: 2.0.2(@jest/globals@30.3.0(supports-color@10.2.2))(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(expect@30.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(supports-color@10.2.2) '@types/react': specifier: ^19.3.0 version: 19.3.0 - '@vitejs/plugin-react': - specifier: 'catalog:' - version: 6.2.1(babel-plugin-react-compiler@1.0.0)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1)) eslint-plugin-react-hooks: specifier: 'catalog:' version: 7.1.1(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2) react: specifier: 'catalog:' version: 19.3.1 - react-dom: - specifier: 'catalog:' - version: 19.3.1(react@19.3.1) typescript: specifier: 'catalog:' version: 6.0.3 diff --git a/scripts/react-query-compat.config.ts b/scripts/react-query-compat.config.ts index dcd25642d5d..3769c750592 100644 --- a/scripts/react-query-compat.config.ts +++ b/scripts/react-query-compat.config.ts @@ -13,7 +13,15 @@ export default defineConfig({ ...base, resolve: { ...base.resolve, - alias: { '@tanstack/query-core': join(adapter, 'src/runtime/index.ts') }, + alias: { + '@tanstack/query-core': join(adapter, 'src/runtime/index.ts'), + ...(basename(adapter) === 'react-query-no-core-pluggable' && { + '@tanstack/query-test-utils/polling': join( + adapter, + 'tests/compat-polling.ts', + ), + }), + }, }, test: { ...base.test, diff --git a/scripts/test-react-query-compat.mjs b/scripts/test-react-query-compat.mjs index 52d7bd0510a..c6e76d55cab 100644 --- a/scripts/test-react-query-compat.mjs +++ b/scripts/test-react-query-compat.mjs @@ -17,7 +17,6 @@ const repository = resolve(import.meta.dirname, '..') const require = createRequire(import.meta.url) const core = join(adapter, 'src/runtime/index.ts') const pluggable = basename(adapter) === 'react-query-no-core-pluggable' -const fixture = join(adapter, 'tests/compat-client.ts') function importPath(from, to) { return './' + relative(from, to).split(sep).join('/') } @@ -37,23 +36,10 @@ for (const suite of ['query-core', 'react-query']) { recursive: true, }) - if (pluggable && suite === 'query-core') { - const tests = join(source, '__tests__') - writeFileSync( - join(tests, 'clientOptions.ts'), - `export type { AdapterClientOptions } from '${importPath(tests, fixture)}'\n`, - ) - } - for (const file of readdirSync(implementation, { withFileTypes: true })) { if (!file.isFile() || !/\.tsx?$/.test(file.name)) continue const target = importPath(source, join(implementation, file.name)) - let exports = `export * from '${target}'\n` - if (pluggable && ['index.ts', 'queryClient.ts'].includes(file.name)) { - const client = importPath(source, fixture) - exports += `export { QueryClient } from '${client}'\n` - } - writeFileSync(join(source, file.name), exports) + writeFileSync(join(source, file.name), `export * from '${target}'\n`) } const setup = join(repository, 'packages/react-query/test-setup.ts') @@ -65,7 +51,14 @@ for (const suite of ['query-core', 'react-query']) { incremental: false, emitDeclarationOnly: false, noEmit: true, - paths: { '@tanstack/query-core': [core] }, + paths: { + '@tanstack/query-core': [core], + ...(pluggable && { + '@tanstack/query-test-utils/polling': [ + join(adapter, 'tests/compat-polling.ts'), + ], + }), + }, }, include: suite === 'react-query' ? ['src', setup] : ['src'], } From 83a274814c1f794f29ff068d66faddb5b7977c97 Mon Sep 17 00:00:00 2001 From: Jonghyeon Ko Date: Fri, 27 Nov 2026 19:51:37 +0900 Subject: [PATCH 04/11] perf(react-query): share one runtime identity across typed option helpers --- .github/workflows/react-query-bundle-size.yml | 2 +- integrations/react/bundle-size/package.json | 3 +- integrations/react/nodenext/README.md | 1 + packages/query-test-utils/src/polling.ts | 9 +- .../src/infiniteQueryOptions.ts | 332 +++++++++--------- .../src/mutationOptions.ts | 165 +++++---- .../src/queryOptions.ts | 301 ++++++++-------- .../src/runtime/focusManager.ts | 2 +- .../src/runtime/identity.ts | 9 + .../src/runtime/refetchInterval.ts | 1 + .../src/runtime/timeoutManager.ts | 2 +- .../src/runtime/utils.ts | 7 +- .../src/infiniteQueryOptions.ts | 332 +++++++++--------- .../src/mutationOptions.ts | 165 +++++---- .../react-query-no-core/src/queryOptions.ts | 301 ++++++++-------- .../src/runtime/identity.ts | 9 + .../react-query-no-core/src/runtime/utils.ts | 7 +- 17 files changed, 842 insertions(+), 806 deletions(-) create mode 100644 packages/react-query-no-core-pluggable/src/runtime/identity.ts create mode 100644 packages/react-query-no-core/src/runtime/identity.ts diff --git a/.github/workflows/react-query-bundle-size.yml b/.github/workflows/react-query-bundle-size.yml index 5b8e3b12bbd..5178d7f0f74 100644 --- a/.github/workflows/react-query-bundle-size.yml +++ b/.github/workflows/react-query-bundle-size.yml @@ -45,7 +45,7 @@ jobs: jq -Rsr '"report=" + tojson' dist/report.md >> "$GITHUB_OUTPUT" - name: Install Chromium working-directory: integrations/react/bundle-size - run: pnpm exec playwright install --with-deps --only-shell chromium + run: pnpm run browser:install - name: Exercise production apps in Chromium working-directory: integrations/react/bundle-size run: pnpm run test:browser diff --git a/integrations/react/bundle-size/package.json b/integrations/react/bundle-size/package.json index a2dd970377e..59a0a873b69 100644 --- a/integrations/react/bundle-size/package.json +++ b/integrations/react/bundle-size/package.json @@ -5,7 +5,8 @@ "scripts": { "measure": "node measure.mjs", "test:browser": "vitest run --config vitest.browser.config.js", - "test:browser:ui": "vitest --watch --ui --config vitest.browser.config.js" + "test:browser:ui": "vitest --watch --ui --config vitest.browser.config.js", + "browser:install": "playwright install --with-deps --only-shell chromium" }, "dependencies": { "@tanstack/react-query": "workspace:*", diff --git a/integrations/react/nodenext/README.md b/integrations/react/nodenext/README.md index 0cbec8b73d7..e3fc41c8384 100644 --- a/integrations/react/nodenext/README.md +++ b/integrations/react/nodenext/README.md @@ -6,6 +6,7 @@ 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 the shared `Register` and passes an adapter-tagged query key to all three clients to check inference across the published ESM entry points. - 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/packages/query-test-utils/src/polling.ts b/packages/query-test-utils/src/polling.ts index b76a0a7cb11..6270186dbb1 100644 --- a/packages/query-test-utils/src/polling.ts +++ b/packages/query-test-utils/src/polling.ts @@ -1,7 +1,12 @@ -// The v6 and integrated adapters accept the interval directly. The pluggable -// compatibility suite resolves this module to its public polling factory. +/** + * Supplies the interval directly to v6 and the integrated React adapter. + * The pluggable compatibility suite uses its own public factory here. + * @param option - Interval setting from a shared test case. + * @returns The supplied setting with its original type. + */ export function refetchInterval(option: T): T { return option } +/** Input accepted by the polling option in this implementation. */ export type IntervalInput = TOption diff --git a/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts b/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts index d280fd34e0f..669863b4905 100644 --- a/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts +++ b/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts @@ -1,3 +1,4 @@ +import { identity } from './runtime/identity' import type { DefaultError, InfiniteData, @@ -117,186 +118,187 @@ export type DefinedInitialDataInfiniteOptions< | (() => NonUndefinedGuard>) } -/** - * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. - * `options.queryKey` is required and is the query key to generate options for. - * - * This overload is selected when `initialData` is known to be defined. - * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` known to be defined. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or - * automatically as the user scrolls. - * @see {@link useInfiniteQuery} to run an infinite query with these options. - * @example - * ```tsx - * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' - * - * export const projectsOptions = infiniteQueryOptions({ - * queryKey: ['projects'], - * queryFn: ({ pageParam }) => fetchProjects(pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * initialData: { pages: [], pageParams: [] }, - * }) - * - * function Projects() { - * // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the - * // list stays visible alongside the error. - * const { data, isError, error } = useInfiniteQuery(projectsOptions) - * - * return ( - *
- * {isError ? Error: {error.message} : null} - *
    - * {data.pages.map((page) => page.projects.map((p) =>
  • {p.name}
  • ))} - *
- *
- * ) - * } - * ``` - */ -export function infiniteQueryOptions< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, ->( - options: DefinedInitialDataInfiniteOptions< +type InfiniteQueryOptionsFn = { + /** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * `options.queryKey` is required and is the query key to generate options for. + * + * This overload is selected when `initialData` is known to be defined. + * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` known to be defined. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or + * automatically as the user scrolls. + * @see {@link useInfiniteQuery} to run an infinite query with these options. + * @example + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' + * + * export const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * initialData: { pages: [], pageParams: [] }, + * }) + * + * function Projects() { + * // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the + * // list stays visible alongside the error. + * const { data, isError, error } = useInfiniteQuery(projectsOptions) + * + * return ( + *
+ * {isError ? Error: {error.message} : null} + *
    + * {data.pages.map((page) => page.projects.map((p) =>
  • {p.name}
  • ))} + *
+ *
+ * ) + * } + * ``` + */ + < + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): DefinedInitialDataInfiniteOptions< TQueryFnData, TError, TData, TQueryKey, TPageParam - >, -): DefinedInitialDataInfiniteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> & - QueryKeyWithDataTag, TError> + > & + QueryKeyWithDataTag, TError> -/** - * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. - * `options.queryKey` is required and is the query key to generate options for. - * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or - * automatically as the user scrolls. - * @see {@link useInfiniteQuery} to run an infinite query with these options. - * @example - * A parameterized factory, so the same options object can be reused per `postId`: - * ```tsx - * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' - * - * export const commentsOptions = (postId: string) => - * infiniteQueryOptions({ - * queryKey: ['post', postId, 'comments'], - * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * }) - * - * function Comments({ postId }: { postId: string }) { - * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return ( - *
    - * {data.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} - *
- * ) - * } - * ``` - */ -export function infiniteQueryOptions< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, ->( - options: UnusedSkipTokenInfiniteOptions< + /** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * `options.queryKey` is required and is the query key to generate options for. + * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or + * automatically as the user scrolls. + * @see {@link useInfiniteQuery} to run an infinite query with these options. + * @example + * A parameterized factory, so the same options object can be reused per `postId`: + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' + * + * export const commentsOptions = (postId: string) => + * infiniteQueryOptions({ + * queryKey: ['post', postId, 'comments'], + * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Comments({ postId }: { postId: string }) { + * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
    + * {data.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} + *
+ * ) + * } + * ``` + */ + < + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): UnusedSkipTokenInfiniteOptions< TQueryFnData, TError, TData, TQueryKey, TPageParam - >, -): UnusedSkipTokenInfiniteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> & - QueryKeyWithDataTag, TError> + > & + QueryKeyWithDataTag, TError> -/** - * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. - * `options.queryKey` is required and is the query key to generate options for. - * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @remarks See {@link useInfiniteQuery} for examples that fetch further pages (from a button click or - * automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set. - * @see {@link useInfiniteQuery} to run an infinite query with these options. - * @example - * A parameterized factory, so the same options object can be reused per `postId`: - * ```tsx - * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' - * - * export const commentsOptions = (postId: string) => - * infiniteQueryOptions({ - * queryKey: ['post', postId, 'comments'], - * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * }) - * - * function Comments({ postId }: { postId: string }) { - * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return ( - *
    - * {data.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} - *
- * ) - * } - * ``` - */ -export function infiniteQueryOptions< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, ->( - options: UndefinedInitialDataInfiniteOptions< + /** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * `options.queryKey` is required and is the query key to generate options for. + * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks See {@link useInfiniteQuery} for examples that fetch further pages (from a button click or + * automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set. + * @see {@link useInfiniteQuery} to run an infinite query with these options. + * @example + * A parameterized factory, so the same options object can be reused per `postId`: + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' + * + * export const commentsOptions = (postId: string) => + * infiniteQueryOptions({ + * queryKey: ['post', postId, 'comments'], + * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Comments({ postId }: { postId: string }) { + * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
    + * {data.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} + *
+ * ) + * } + * ``` + */ + < + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): UndefinedInitialDataInfiniteOptions< TQueryFnData, TError, TData, TQueryKey, TPageParam - >, -): UndefinedInitialDataInfiniteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> & - QueryKeyWithDataTag, TError> - -export function infiniteQueryOptions(options: unknown) { - return options + > & + QueryKeyWithDataTag, TError> } + +/** Preserves infinite query options and tags their key with the inferred pages and error types. */ +export const infiniteQueryOptions: InfiniteQueryOptionsFn = identity diff --git a/packages/react-query-no-core-pluggable/src/mutationOptions.ts b/packages/react-query-no-core-pluggable/src/mutationOptions.ts index 2c0de1da87c..b92dbbb2b7b 100644 --- a/packages/react-query-no-core-pluggable/src/mutationOptions.ts +++ b/packages/react-query-no-core-pluggable/src/mutationOptions.ts @@ -1,92 +1,89 @@ +import { identity } from './runtime/identity' import type { DefaultError, WithRequired } from './runtime/index' import type { UseMutationOptions } from './types' -/** - * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A - * `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with - * `useMutationState`. - * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a - * required `mutationKey`. - * @returns The same options object, unchanged. - * @see {@link useMutation} to run the mutation these options describe. - * @example - * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator: - * ```tsx - * import { mutationOptions, useMutationState } from '@tanstack/react-query-no-core-pluggable' - * - * const createPostOptions = mutationOptions({ - * mutationKey: ['posts', 'create'], - * mutationFn: createPost, - * }) - * - * function SavingIndicator() { - * const isCreatingPost = useMutationState({ - * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' }, - * }).length > 0 - * - * return isCreatingPost ? Saving… : null - * } - * ``` - */ -export function mutationOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, ->( - options: WithRequired< +type MutationOptionsFn = { + /** + * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A + * `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with + * `useMutationState`. + * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a + * required `mutationKey`. + * @returns The same options object, unchanged. + * @see {@link useMutation} to run the mutation these options describe. + * @example + * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator: + * ```tsx + * import { mutationOptions, useMutationState } from '@tanstack/react-query-no-core-pluggable' + * + * const createPostOptions = mutationOptions({ + * mutationKey: ['posts', 'create'], + * mutationFn: createPost, + * }) + * + * function SavingIndicator() { + * const isCreatingPost = useMutationState({ + * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' }, + * }).length > 0 + * + * return isCreatingPost ? Saving… : null + * } + * ``` + */ + < + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, + >( + options: WithRequired< + UseMutationOptions, + 'mutationKey' + >, + ): WithRequired< UseMutationOptions, 'mutationKey' - >, -): WithRequired< - UseMutationOptions, - 'mutationKey' -> -/** - * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No - * `mutationKey` is required on this overload — use this when you don't need to target the mutation via a - * `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters, - * such as `status`. - * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a - * `mutationKey`. - * @returns The same options object, unchanged. - * @remarks See the other overload's example for looking a mutation up via `useMutationState`. - * @see {@link useMutation} to run the mutation these options describe. - * @example - * ```tsx - * import { mutationOptions, useMutation } from '@tanstack/react-query-no-core-pluggable' - * - * export const createPostOptions = mutationOptions({ - * mutationFn: createPost, - * }) - * - * function CreatePost() { - * const mutation = useMutation(createPostOptions) - * return - * } - * ``` - */ -export function mutationOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, ->( - options: Omit< + > + + /** + * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No + * `mutationKey` is required on this overload — use this when you don't need to target the mutation via a + * `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters, + * such as `status`. + * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a + * `mutationKey`. + * @returns The same options object, unchanged. + * @remarks See the other overload's example for looking a mutation up via `useMutationState`. + * @see {@link useMutation} to run the mutation these options describe. + * @example + * ```tsx + * import { mutationOptions, useMutation } from '@tanstack/react-query-no-core-pluggable' + * + * export const createPostOptions = mutationOptions({ + * mutationFn: createPost, + * }) + * + * function CreatePost() { + * const mutation = useMutation(createPostOptions) + * return + * } + * ``` + */ + < + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, + >( + options: Omit< + UseMutationOptions, + 'mutationKey' + >, + ): Omit< UseMutationOptions, 'mutationKey' - >, -): Omit< - UseMutationOptions, - 'mutationKey' -> -export function mutationOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, ->( - options: UseMutationOptions, -): UseMutationOptions { - return options + > } + +/** Preserves mutation option types when reusing the same options in multiple places. */ +export const mutationOptions: MutationOptionsFn = identity diff --git a/packages/react-query-no-core-pluggable/src/queryOptions.ts b/packages/react-query-no-core-pluggable/src/queryOptions.ts index 5b83a81c36c..fe919c06e48 100644 --- a/packages/react-query-no-core-pluggable/src/queryOptions.ts +++ b/packages/react-query-no-core-pluggable/src/queryOptions.ts @@ -1,3 +1,4 @@ +import { identity } from './runtime/identity' import type { DefaultError, DefaultQueryFn, @@ -90,153 +91,159 @@ export type DefinedInitialDataOptions< queryFn: QueryFunction | DefaultQueryFn } -/** - * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can - * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and - * is the query key to generate options for. - * - * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never - * `undefined` (unless a `select` changes `TData` to include `undefined`). - * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @see {@link useQuery} to run a query with these options. - * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. - * @example - * ```tsx - * import { queryOptions, useQuery } from '@tanstack/react-query-no-core-pluggable' - * - * export const postsOptions = queryOptions({ - * queryKey: ['posts'], - * queryFn: fetchPosts, - * initialData: [], - * }) - * - * function Posts() { - * // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, - * // so the list stays visible alongside the error. - * const { data, isError, error } = useQuery(postsOptions) - * - * return ( - *
- * {isError ? Error: {error.message} : null} - *
    - * {data.map((post) =>
  • {post.title}
  • )} - *
- *
- * ) - * } - * ``` - */ -export function queryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - options: DefinedInitialDataOptions, -): DefinedInitialDataOptions & - QueryKeyWithDataTag - -/** - * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can - * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and - * is the query key to generate options for. - * @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `useQuery`. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @see {@link useQuery} to run a query with these options. - * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. - * @example - * A parameterized factory, so the same options object can be reused per `id`: - * ```tsx - * import { queryOptions, useQuery } from '@tanstack/react-query-no-core-pluggable' - * - * export const postOptions = (id: string) => - * queryOptions({ - * queryKey: ['post', id], - * queryFn: () => fetchPost(id), - * }) - * - * function Post({ id }: { id: string }) { - * const { data, isPending, isError, error } = useQuery(postOptions(id)) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return

{data.title}

- * } - * ``` - */ -export function queryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - options: UnusedSkipTokenOptions, -): UnusedSkipTokenOptions & - QueryKeyWithDataTag +type QueryOptionsFn = { + /** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * is the query key to generate options for. + * + * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never + * `undefined` (unless a `select` changes `TData` to include `undefined`). + * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-no-core-pluggable' + * + * export const postsOptions = queryOptions({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * initialData: [], + * }) + * + * function Posts() { + * // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, + * // so the list stays visible alongside the error. + * const { data, isError, error } = useQuery(postsOptions) + * + * return ( + *
+ * {isError ? Error: {error.message} : null} + *
    + * {data.map((post) =>
  • {post.title}
  • )} + *
+ *
+ * ) + * } + * ``` + */ + < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + options: DefinedInitialDataOptions, + ): DefinedInitialDataOptions & + QueryKeyWithDataTag -/** - * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can - * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and - * is the query key to generate options for. - * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below. - * @see {@link useQuery} to run a query with these options. - * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. - * @example - * A parameterized factory, so the same options object can be reused per `id`: - * ```tsx - * import { queryOptions, useQuery } from '@tanstack/react-query-no-core-pluggable' - * - * export const postOptions = (id: string) => - * queryOptions({ - * queryKey: ['post', id], - * queryFn: () => fetchPost(id), - * }) - * - * function Post({ id }: { id: string }) { - * const { data, isPending, isError, error } = useQuery(postOptions(id)) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return

{data.title}

- * } - * ``` - * @example - * A factory that disables the query, type safe, until `postId` is set: - * ```tsx - * import { queryOptions, skipToken, useQuery } from '@tanstack/react-query-no-core-pluggable' - * - * export const postOptions = (postId: number | undefined) => - * queryOptions({ - * queryKey: ['post', postId], - * queryFn: postId != null ? () => fetchPost(postId) : skipToken, - * }) - * - * function Post({ postId }: { postId: number | undefined }) { - * const { data, isLoading, isError, error } = useQuery(postOptions(postId)) - * - * if (postId == null) return 'Select a post' - * if (isLoading) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return

{data?.title}

- * } - * ``` - */ -export function queryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - options: UndefinedInitialDataOptions, -): UndefinedInitialDataOptions & - QueryKeyWithDataTag + /** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * is the query key to generate options for. + * @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `useQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * A parameterized factory, so the same options object can be reused per `id`: + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-no-core-pluggable' + * + * export const postOptions = (id: string) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function Post({ id }: { id: string }) { + * const { data, isPending, isError, error } = useQuery(postOptions(id)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data.title}

+ * } + * ``` + */ + < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + options: UnusedSkipTokenOptions, + ): UnusedSkipTokenOptions & + QueryKeyWithDataTag -export function queryOptions(options: unknown) { - return options + /** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * is the query key to generate options for. + * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * A parameterized factory, so the same options object can be reused per `id`: + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-no-core-pluggable' + * + * export const postOptions = (id: string) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function Post({ id }: { id: string }) { + * const { data, isPending, isError, error } = useQuery(postOptions(id)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data.title}

+ * } + * ``` + * @example + * A factory that disables the query, type safe, until `postId` is set: + * ```tsx + * import { queryOptions, skipToken, useQuery } from '@tanstack/react-query-no-core-pluggable' + * + * export const postOptions = (postId: number | undefined) => + * queryOptions({ + * queryKey: ['post', postId], + * queryFn: postId != null ? () => fetchPost(postId) : skipToken, + * }) + * + * function Post({ postId }: { postId: number | undefined }) { + * const { data, isLoading, isError, error } = useQuery(postOptions(postId)) + * + * if (postId == null) return 'Select a post' + * if (isLoading) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data?.title}

+ * } + * ``` + */ + < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + options: UndefinedInitialDataOptions< + TQueryFnData, + TError, + TData, + TQueryKey + >, + ): UndefinedInitialDataOptions & + QueryKeyWithDataTag } + +/** Preserves query options and tags their key with the inferred data and error types. */ +export const queryOptions: QueryOptionsFn = identity diff --git a/packages/react-query-no-core-pluggable/src/runtime/focusManager.ts b/packages/react-query-no-core-pluggable/src/runtime/focusManager.ts index f52a8b2d199..6182b408e83 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/focusManager.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/focusManager.ts @@ -139,4 +139,4 @@ export class FocusManager extends Subscribable { /** * Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query. */ -export const focusManager = new FocusManager() +export const focusManager = /* @__PURE__ */ new FocusManager() diff --git a/packages/react-query-no-core-pluggable/src/runtime/identity.ts b/packages/react-query-no-core-pluggable/src/runtime/identity.ts new file mode 100644 index 00000000000..d6857688755 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/identity.ts @@ -0,0 +1,9 @@ +/** + * Returns its argument by reference. Option helpers specialize the signature with + * their own overloads and add their key tags at compile time. + * @param value - The original value. + * @returns The original value. + */ +export function identity(value: T): T { + return value +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/refetchInterval.ts b/packages/react-query-no-core-pluggable/src/runtime/refetchInterval.ts index 9a35dc7003c..2366117c196 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/refetchInterval.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/refetchInterval.ts @@ -40,6 +40,7 @@ export function refetchInterval(value: Delay): RefetchInterval export function refetchInterval( value: Delay | ((query: TQuery) => Delay), ): RefetchInterval +/* @__NO_SIDE_EFFECTS__ */ export function refetchInterval( value: Delay | ((query: TQuery) => Delay), ): RefetchInterval { diff --git a/packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts b/packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts index 898b8f3bda5..2d650ed10a2 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts @@ -202,7 +202,7 @@ export class TimeoutManager implements Omit { /** * Singleton instance of {@link TimeoutManager}, used throughout TanStack Query to schedule and cancel timers. */ -export const timeoutManager = new TimeoutManager() +export const timeoutManager = /* @__PURE__ */ new TimeoutManager() /** * In many cases code wants to delay to the next event loop tick; this is not diff --git a/packages/react-query-no-core-pluggable/src/runtime/utils.ts b/packages/react-query-no-core-pluggable/src/runtime/utils.ts index 39c95dfd394..7a666f2aa50 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/utils.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/utils.ts @@ -1,3 +1,4 @@ +import { identity } from './identity' import { timeoutManager } from './timeoutManager' import type * as Shared from '@tanstack/query-types/bindings' import type { @@ -559,11 +560,9 @@ export function replaceData< * }) * ``` */ -export function keepPreviousData( +export const keepPreviousData: ( previousData: T | undefined, -): T | undefined { - return previousData -} +) => T | undefined = identity /** * Adds an item to one end of a new array. If the result exceeds `max`, removes diff --git a/packages/react-query-no-core/src/infiniteQueryOptions.ts b/packages/react-query-no-core/src/infiniteQueryOptions.ts index d95f732d974..fa952f52158 100644 --- a/packages/react-query-no-core/src/infiniteQueryOptions.ts +++ b/packages/react-query-no-core/src/infiniteQueryOptions.ts @@ -1,3 +1,4 @@ +import { identity } from './runtime/identity' import type { DefaultError, InfiniteData, @@ -117,186 +118,187 @@ export type DefinedInitialDataInfiniteOptions< | (() => NonUndefinedGuard>) } -/** - * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. - * `options.queryKey` is required and is the query key to generate options for. - * - * This overload is selected when `initialData` is known to be defined. - * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` known to be defined. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or - * automatically as the user scrolls. - * @see {@link useInfiniteQuery} to run an infinite query with these options. - * @example - * ```tsx - * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core' - * - * export const projectsOptions = infiniteQueryOptions({ - * queryKey: ['projects'], - * queryFn: ({ pageParam }) => fetchProjects(pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * initialData: { pages: [], pageParams: [] }, - * }) - * - * function Projects() { - * // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the - * // list stays visible alongside the error. - * const { data, isError, error } = useInfiniteQuery(projectsOptions) - * - * return ( - *
- * {isError ? Error: {error.message} : null} - *
    - * {data.pages.map((page) => page.projects.map((p) =>
  • {p.name}
  • ))} - *
- *
- * ) - * } - * ``` - */ -export function infiniteQueryOptions< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, ->( - options: DefinedInitialDataInfiniteOptions< +type InfiniteQueryOptionsFn = { + /** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * `options.queryKey` is required and is the query key to generate options for. + * + * This overload is selected when `initialData` is known to be defined. + * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` known to be defined. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or + * automatically as the user scrolls. + * @see {@link useInfiniteQuery} to run an infinite query with these options. + * @example + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core' + * + * export const projectsOptions = infiniteQueryOptions({ + * queryKey: ['projects'], + * queryFn: ({ pageParam }) => fetchProjects(pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * initialData: { pages: [], pageParams: [] }, + * }) + * + * function Projects() { + * // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the + * // list stays visible alongside the error. + * const { data, isError, error } = useInfiniteQuery(projectsOptions) + * + * return ( + *
+ * {isError ? Error: {error.message} : null} + *
    + * {data.pages.map((page) => page.projects.map((p) =>
  • {p.name}
  • ))} + *
+ *
+ * ) + * } + * ``` + */ + < + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): DefinedInitialDataInfiniteOptions< TQueryFnData, TError, TData, TQueryKey, TPageParam - >, -): DefinedInitialDataInfiniteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> & - QueryKeyWithDataTag, TError> + > & + QueryKeyWithDataTag, TError> -/** - * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. - * `options.queryKey` is required and is the query key to generate options for. - * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or - * automatically as the user scrolls. - * @see {@link useInfiniteQuery} to run an infinite query with these options. - * @example - * A parameterized factory, so the same options object can be reused per `postId`: - * ```tsx - * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core' - * - * export const commentsOptions = (postId: string) => - * infiniteQueryOptions({ - * queryKey: ['post', postId, 'comments'], - * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * }) - * - * function Comments({ postId }: { postId: string }) { - * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return ( - *
    - * {data.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} - *
- * ) - * } - * ``` - */ -export function infiniteQueryOptions< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, ->( - options: UnusedSkipTokenInfiniteOptions< + /** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * `options.queryKey` is required and is the query key to generate options for. + * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or + * automatically as the user scrolls. + * @see {@link useInfiniteQuery} to run an infinite query with these options. + * @example + * A parameterized factory, so the same options object can be reused per `postId`: + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core' + * + * export const commentsOptions = (postId: string) => + * infiniteQueryOptions({ + * queryKey: ['post', postId, 'comments'], + * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Comments({ postId }: { postId: string }) { + * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
    + * {data.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} + *
+ * ) + * } + * ``` + */ + < + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): UnusedSkipTokenInfiniteOptions< TQueryFnData, TError, TData, TQueryKey, TPageParam - >, -): UnusedSkipTokenInfiniteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> & - QueryKeyWithDataTag, TError> + > & + QueryKeyWithDataTag, TError> -/** - * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. - * `options.queryKey` is required and is the query key to generate options for. - * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @remarks See {@link useInfiniteQuery} for examples that fetch further pages (from a button click or - * automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set. - * @see {@link useInfiniteQuery} to run an infinite query with these options. - * @example - * A parameterized factory, so the same options object can be reused per `postId`: - * ```tsx - * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core' - * - * export const commentsOptions = (postId: string) => - * infiniteQueryOptions({ - * queryKey: ['post', postId, 'comments'], - * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * }) - * - * function Comments({ postId }: { postId: string }) { - * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return ( - *
    - * {data.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} - *
- * ) - * } - * ``` - */ -export function infiniteQueryOptions< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, ->( - options: UndefinedInitialDataInfiniteOptions< + /** + * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * `options.queryKey` is required and is the query key to generate options for. + * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks See {@link useInfiniteQuery} for examples that fetch further pages (from a button click or + * automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set. + * @see {@link useInfiniteQuery} to run an infinite query with these options. + * @example + * A parameterized factory, so the same options object can be reused per `postId`: + * ```tsx + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core' + * + * export const commentsOptions = (postId: string) => + * infiniteQueryOptions({ + * queryKey: ['post', postId, 'comments'], + * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), + * initialPageParam: 0, + * getNextPageParam: (lastPage) => lastPage.nextId, + * }) + * + * function Comments({ postId }: { postId: string }) { + * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return ( + *
    + * {data.pages.map((page) => page.comments.map((c) =>
  • {c.text}
  • ))} + *
+ * ) + * } + * ``` + */ + < + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: UndefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): UndefinedInitialDataInfiniteOptions< TQueryFnData, TError, TData, TQueryKey, TPageParam - >, -): UndefinedInitialDataInfiniteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> & - QueryKeyWithDataTag, TError> - -export function infiniteQueryOptions(options: unknown) { - return options + > & + QueryKeyWithDataTag, TError> } + +/** Preserves infinite query options and tags their key with the inferred pages and error types. */ +export const infiniteQueryOptions: InfiniteQueryOptionsFn = identity diff --git a/packages/react-query-no-core/src/mutationOptions.ts b/packages/react-query-no-core/src/mutationOptions.ts index c8a25795195..37e9c00c925 100644 --- a/packages/react-query-no-core/src/mutationOptions.ts +++ b/packages/react-query-no-core/src/mutationOptions.ts @@ -1,92 +1,89 @@ +import { identity } from './runtime/identity' import type { DefaultError, WithRequired } from './runtime' import type { UseMutationOptions } from './types' -/** - * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A - * `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with - * `useMutationState`. - * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a - * required `mutationKey`. - * @returns The same options object, unchanged. - * @see {@link useMutation} to run the mutation these options describe. - * @example - * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator: - * ```tsx - * import { mutationOptions, useMutationState } from '@tanstack/react-query-no-core' - * - * const createPostOptions = mutationOptions({ - * mutationKey: ['posts', 'create'], - * mutationFn: createPost, - * }) - * - * function SavingIndicator() { - * const isCreatingPost = useMutationState({ - * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' }, - * }).length > 0 - * - * return isCreatingPost ? Saving… : null - * } - * ``` - */ -export function mutationOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, ->( - options: WithRequired< +type MutationOptionsFn = { + /** + * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A + * `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with + * `useMutationState`. + * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a + * required `mutationKey`. + * @returns The same options object, unchanged. + * @see {@link useMutation} to run the mutation these options describe. + * @example + * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator: + * ```tsx + * import { mutationOptions, useMutationState } from '@tanstack/react-query-no-core' + * + * const createPostOptions = mutationOptions({ + * mutationKey: ['posts', 'create'], + * mutationFn: createPost, + * }) + * + * function SavingIndicator() { + * const isCreatingPost = useMutationState({ + * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' }, + * }).length > 0 + * + * return isCreatingPost ? Saving… : null + * } + * ``` + */ + < + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, + >( + options: WithRequired< + UseMutationOptions, + 'mutationKey' + >, + ): WithRequired< UseMutationOptions, 'mutationKey' - >, -): WithRequired< - UseMutationOptions, - 'mutationKey' -> -/** - * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No - * `mutationKey` is required on this overload — use this when you don't need to target the mutation via a - * `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters, - * such as `status`. - * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a - * `mutationKey`. - * @returns The same options object, unchanged. - * @remarks See the other overload's example for looking a mutation up via `useMutationState`. - * @see {@link useMutation} to run the mutation these options describe. - * @example - * ```tsx - * import { mutationOptions, useMutation } from '@tanstack/react-query-no-core' - * - * export const createPostOptions = mutationOptions({ - * mutationFn: createPost, - * }) - * - * function CreatePost() { - * const mutation = useMutation(createPostOptions) - * return - * } - * ``` - */ -export function mutationOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, ->( - options: Omit< + > + + /** + * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No + * `mutationKey` is required on this overload — use this when you don't need to target the mutation via a + * `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters, + * such as `status`. + * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a + * `mutationKey`. + * @returns The same options object, unchanged. + * @remarks See the other overload's example for looking a mutation up via `useMutationState`. + * @see {@link useMutation} to run the mutation these options describe. + * @example + * ```tsx + * import { mutationOptions, useMutation } from '@tanstack/react-query-no-core' + * + * export const createPostOptions = mutationOptions({ + * mutationFn: createPost, + * }) + * + * function CreatePost() { + * const mutation = useMutation(createPostOptions) + * return + * } + * ``` + */ + < + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, + >( + options: Omit< + UseMutationOptions, + 'mutationKey' + >, + ): Omit< UseMutationOptions, 'mutationKey' - >, -): Omit< - UseMutationOptions, - 'mutationKey' -> -export function mutationOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, ->( - options: UseMutationOptions, -): UseMutationOptions { - return options + > } + +/** Preserves mutation option types when reusing the same options in multiple places. */ +export const mutationOptions: MutationOptionsFn = identity diff --git a/packages/react-query-no-core/src/queryOptions.ts b/packages/react-query-no-core/src/queryOptions.ts index 7e1f4fc7ebb..12cbeb14669 100644 --- a/packages/react-query-no-core/src/queryOptions.ts +++ b/packages/react-query-no-core/src/queryOptions.ts @@ -1,3 +1,4 @@ +import { identity } from './runtime/identity' import type { DefaultError, DefaultQueryFn, @@ -90,153 +91,159 @@ export type DefinedInitialDataOptions< queryFn: QueryFunction | DefaultQueryFn } -/** - * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can - * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and - * is the query key to generate options for. - * - * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never - * `undefined` (unless a `select` changes `TData` to include `undefined`). - * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @see {@link useQuery} to run a query with these options. - * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. - * @example - * ```tsx - * import { queryOptions, useQuery } from '@tanstack/react-query-no-core' - * - * export const postsOptions = queryOptions({ - * queryKey: ['posts'], - * queryFn: fetchPosts, - * initialData: [], - * }) - * - * function Posts() { - * // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, - * // so the list stays visible alongside the error. - * const { data, isError, error } = useQuery(postsOptions) - * - * return ( - *
- * {isError ? Error: {error.message} : null} - *
    - * {data.map((post) =>
  • {post.title}
  • )} - *
- *
- * ) - * } - * ``` - */ -export function queryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - options: DefinedInitialDataOptions, -): DefinedInitialDataOptions & - QueryKeyWithDataTag - -/** - * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can - * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and - * is the query key to generate options for. - * @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `useQuery`. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @see {@link useQuery} to run a query with these options. - * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. - * @example - * A parameterized factory, so the same options object can be reused per `id`: - * ```tsx - * import { queryOptions, useQuery } from '@tanstack/react-query-no-core' - * - * export const postOptions = (id: string) => - * queryOptions({ - * queryKey: ['post', id], - * queryFn: () => fetchPost(id), - * }) - * - * function Post({ id }: { id: string }) { - * const { data, isPending, isError, error } = useQuery(postOptions(id)) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return

{data.title}

- * } - * ``` - */ -export function queryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - options: UnusedSkipTokenOptions, -): UnusedSkipTokenOptions & - QueryKeyWithDataTag +type QueryOptionsFn = { + /** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * is the query key to generate options for. + * + * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never + * `undefined` (unless a `select` changes `TData` to include `undefined`). + * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-no-core' + * + * export const postsOptions = queryOptions({ + * queryKey: ['posts'], + * queryFn: fetchPosts, + * initialData: [], + * }) + * + * function Posts() { + * // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, + * // so the list stays visible alongside the error. + * const { data, isError, error } = useQuery(postsOptions) + * + * return ( + *
+ * {isError ? Error: {error.message} : null} + *
    + * {data.map((post) =>
  • {post.title}
  • )} + *
+ *
+ * ) + * } + * ``` + */ + < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + options: DefinedInitialDataOptions, + ): DefinedInitialDataOptions & + QueryKeyWithDataTag -/** - * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can - * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and - * is the query key to generate options for. - * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below. - * @see {@link useQuery} to run a query with these options. - * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. - * @example - * A parameterized factory, so the same options object can be reused per `id`: - * ```tsx - * import { queryOptions, useQuery } from '@tanstack/react-query-no-core' - * - * export const postOptions = (id: string) => - * queryOptions({ - * queryKey: ['post', id], - * queryFn: () => fetchPost(id), - * }) - * - * function Post({ id }: { id: string }) { - * const { data, isPending, isError, error } = useQuery(postOptions(id)) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return

{data.title}

- * } - * ``` - * @example - * A factory that disables the query, type safe, until `postId` is set: - * ```tsx - * import { queryOptions, skipToken, useQuery } from '@tanstack/react-query-no-core' - * - * export const postOptions = (postId: number | undefined) => - * queryOptions({ - * queryKey: ['post', postId], - * queryFn: postId != null ? () => fetchPost(postId) : skipToken, - * }) - * - * function Post({ postId }: { postId: number | undefined }) { - * const { data, isLoading, isError, error } = useQuery(postOptions(postId)) - * - * if (postId == null) return 'Select a post' - * if (isLoading) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return

{data?.title}

- * } - * ``` - */ -export function queryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - options: UndefinedInitialDataOptions, -): UndefinedInitialDataOptions & - QueryKeyWithDataTag + /** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * is the query key to generate options for. + * @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `useQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * A parameterized factory, so the same options object can be reused per `id`: + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-no-core' + * + * export const postOptions = (id: string) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function Post({ id }: { id: string }) { + * const { data, isPending, isError, error } = useQuery(postOptions(id)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data.title}

+ * } + * ``` + */ + < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + options: UnusedSkipTokenOptions, + ): UnusedSkipTokenOptions & + QueryKeyWithDataTag -export function queryOptions(options: unknown) { - return options + /** + * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can + * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * is the query key to generate options for. + * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. + * @returns The same options object, typed so that `queryKey` carries the inferred data type. + * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below. + * @see {@link useQuery} to run a query with these options. + * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. + * @example + * A parameterized factory, so the same options object can be reused per `id`: + * ```tsx + * import { queryOptions, useQuery } from '@tanstack/react-query-no-core' + * + * export const postOptions = (id: string) => + * queryOptions({ + * queryKey: ['post', id], + * queryFn: () => fetchPost(id), + * }) + * + * function Post({ id }: { id: string }) { + * const { data, isPending, isError, error } = useQuery(postOptions(id)) + * + * if (isPending) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data.title}

+ * } + * ``` + * @example + * A factory that disables the query, type safe, until `postId` is set: + * ```tsx + * import { queryOptions, skipToken, useQuery } from '@tanstack/react-query-no-core' + * + * export const postOptions = (postId: number | undefined) => + * queryOptions({ + * queryKey: ['post', postId], + * queryFn: postId != null ? () => fetchPost(postId) : skipToken, + * }) + * + * function Post({ postId }: { postId: number | undefined }) { + * const { data, isLoading, isError, error } = useQuery(postOptions(postId)) + * + * if (postId == null) return 'Select a post' + * if (isLoading) return 'Loading...' + * if (isError) return Error: {error.message} + * + * return

{data?.title}

+ * } + * ``` + */ + < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + >( + options: UndefinedInitialDataOptions< + TQueryFnData, + TError, + TData, + TQueryKey + >, + ): UndefinedInitialDataOptions & + QueryKeyWithDataTag } + +/** Preserves query options and tags their key with the inferred data and error types. */ +export const queryOptions: QueryOptionsFn = identity diff --git a/packages/react-query-no-core/src/runtime/identity.ts b/packages/react-query-no-core/src/runtime/identity.ts new file mode 100644 index 00000000000..d6857688755 --- /dev/null +++ b/packages/react-query-no-core/src/runtime/identity.ts @@ -0,0 +1,9 @@ +/** + * Returns its argument by reference. Option helpers specialize the signature with + * their own overloads and add their key tags at compile time. + * @param value - The original value. + * @returns The original value. + */ +export function identity(value: T): T { + return value +} diff --git a/packages/react-query-no-core/src/runtime/utils.ts b/packages/react-query-no-core/src/runtime/utils.ts index 39c95dfd394..7a666f2aa50 100644 --- a/packages/react-query-no-core/src/runtime/utils.ts +++ b/packages/react-query-no-core/src/runtime/utils.ts @@ -1,3 +1,4 @@ +import { identity } from './identity' import { timeoutManager } from './timeoutManager' import type * as Shared from '@tanstack/query-types/bindings' import type { @@ -559,11 +560,9 @@ export function replaceData< * }) * ``` */ -export function keepPreviousData( +export const keepPreviousData: ( previousData: T | undefined, -): T | undefined { - return previousData -} +) => T | undefined = identity /** * Adds an item to one end of a new array. If the result exceeds `max`, removes From ca32c29f4f307ddab78d97e237b1dce5ff178b19 Mon Sep 17 00:00:00 2001 From: Jonghyeon Ko Date: Fri, 27 Nov 2026 20:02:30 +0900 Subject: [PATCH 05/11] refactor(react-query): import React runtime modules directly and drop adapter hooks --- .../frameworkAdapters.test-d.ts | 43 +++++ .../frameworkAdapters.test.ts | 48 +++++ .../src/__tests__/notifyManager.test-d.tsx | 29 --- .../src/__tests__/notifyManager.test.tsx | 19 -- .../src/__tests__/queriesObserver.test-d.tsx | 17 +- .../src/__tests__/queriesObserver.test.tsx | 29 +-- .../src/HydrationBoundary.tsx | 11 +- .../src/QueryClientProvider.tsx | 2 +- .../src/errorBoundaryUtils.ts | 12 +- .../src/index.ts | 163 ++++++++++++++++- .../src/infiniteQueryOptions.ts | 2 +- .../src/mutationOptions.ts | 2 +- .../src/queryOptions.ts | 4 +- .../src/runtime/focusManager.ts | 2 +- .../src/runtime/index.ts | 170 ------------------ .../src/runtime/notifyManager.ts | 26 +-- .../src/runtime/queriesObserver.ts | 9 - .../src/runtime/queryObserver.ts | 13 +- .../src/runtime/refetchInterval.ts | 18 +- .../src/runtime/timeoutManager.ts | 2 +- .../src/suspense.ts | 12 +- .../src/types.ts | 18 +- .../src/useBaseQuery.ts | 6 +- .../src/useInfiniteQuery.ts | 16 +- .../src/useIsFetching.ts | 5 +- .../src/useMutation.ts | 12 +- .../src/useMutationState.ts | 15 +- .../src/usePrefetchInfiniteQuery.tsx | 6 +- .../src/usePrefetchQuery.tsx | 5 +- .../src/useQueries.ts | 8 +- .../src/useQuery.ts | 5 +- .../src/useSuspenseInfiniteQuery.ts | 9 +- .../src/useSuspenseQueries.ts | 9 +- .../src/useSuspenseQuery.ts | 7 +- packages/react-query-no-core/README.md | 2 + .../src/HydrationBoundary.tsx | 11 +- .../src/QueryClientProvider.tsx | 2 +- .../src/errorBoundaryUtils.ts | 12 +- packages/react-query-no-core/src/index.ts | 163 ++++++++++++++++- .../src/infiniteQueryOptions.ts | 2 +- .../src/mutationOptions.ts | 2 +- .../react-query-no-core/src/queryOptions.ts | 4 +- .../react-query-no-core/src/runtime/index.ts | 168 ----------------- .../src/runtime/notifyManager.ts | 26 +-- .../src/runtime/queriesObserver.ts | 9 - .../src/runtime/queryObserver.ts | 6 +- packages/react-query-no-core/src/suspense.ts | 12 +- packages/react-query-no-core/src/types.ts | 18 +- .../react-query-no-core/src/useBaseQuery.ts | 6 +- .../src/useInfiniteQuery.ts | 16 +- .../react-query-no-core/src/useIsFetching.ts | 5 +- .../react-query-no-core/src/useMutation.ts | 12 +- .../src/useMutationState.ts | 15 +- .../src/usePrefetchInfiniteQuery.tsx | 6 +- .../src/usePrefetchQuery.tsx | 5 +- .../react-query-no-core/src/useQueries.ts | 8 +- packages/react-query-no-core/src/useQuery.ts | 5 +- .../src/useSuspenseInfiniteQuery.ts | 9 +- .../src/useSuspenseQueries.ts | 9 +- .../src/useSuspenseQuery.ts | 10 +- scripts/react-query-compat.config.ts | 2 +- scripts/test-react-query-compat.mjs | 14 +- 62 files changed, 637 insertions(+), 676 deletions(-) create mode 100644 packages/query-core/src/__tests__/frameworkAdapters/frameworkAdapters.test-d.ts create mode 100644 packages/query-core/src/__tests__/frameworkAdapters/frameworkAdapters.test.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/index.ts delete mode 100644 packages/react-query-no-core/src/runtime/index.ts diff --git a/packages/query-core/src/__tests__/frameworkAdapters/frameworkAdapters.test-d.ts b/packages/query-core/src/__tests__/frameworkAdapters/frameworkAdapters.test-d.ts new file mode 100644 index 00000000000..9ec03113f45 --- /dev/null +++ b/packages/query-core/src/__tests__/frameworkAdapters/frameworkAdapters.test-d.ts @@ -0,0 +1,43 @@ +import { describe, expectTypeOf, it } from 'vitest' +import { QueriesObserver, QueryClient } from '../..' +import { createNotifyManager } from '../../notifyManager' +import type { Query } from '../..' + +describe('framework adapter APIs', () => { + it('should only expose its documented members', () => { + expectTypeOf>().toEqualTypeOf< + | 'batch' + | 'batchCalls' + | 'schedule' + | 'setNotifyFunction' + | 'setBatchNotifyFunction' + | 'setScheduler' + >() + }) + + describe('setBatchNotifyFunction', () => { + it('should only accept a function taking a callback', () => { + const localNotifyManager = createNotifyManager() + + expectTypeOf( + localNotifyManager.setBatchNotifyFunction, + ).parameters.toEqualTypeOf<[fn: (callback: () => void) => void]>() + }) + + it('should return void', () => { + const localNotifyManager = createNotifyManager() + + expectTypeOf( + localNotifyManager.setBatchNotifyFunction, + ).returns.toEqualTypeOf() + }) + }) + + describe('getQueries', () => { + it('should return the observed queries', () => { + const observer = new QueriesObserver(new QueryClient(), []) + + expectTypeOf(observer.getQueries()).toEqualTypeOf>() + }) + }) +}) diff --git a/packages/query-core/src/__tests__/frameworkAdapters/frameworkAdapters.test.ts b/packages/query-core/src/__tests__/frameworkAdapters/frameworkAdapters.test.ts new file mode 100644 index 00000000000..9deeec16882 --- /dev/null +++ b/packages/query-core/src/__tests__/frameworkAdapters/frameworkAdapters.test.ts @@ -0,0 +1,48 @@ +import { createKey } from '@tanstack/query-test-utils' +import { describe, expect, it, vi } from 'vitest' +import { QueriesObserver, QueryClient } from '../..' +import { createNotifyManager } from '../../notifyManager' + +describe('framework adapter APIs', () => { + it('should use custom batch notify function', async () => { + const notifyManagerTest = createNotifyManager() + const batchNotifySpy = vi.fn<(callback: () => void) => void>((cb) => cb()) + const callbackSpy1 = vi.fn<() => void>() + const callbackSpy2 = vi.fn<() => void>() + + notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) + + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(callbackSpy1) + notifyManagerTest.schedule(callbackSpy2) + }) + + await Promise.resolve() + expect(batchNotifySpy).toHaveBeenCalledWith(expect.any(Function)) + expect(callbackSpy1).toHaveBeenCalledWith() + expect(callbackSpy2).toHaveBeenCalledWith() + }) + + it('should return current queries via getQueries', async () => { + const queryClient = new QueryClient() + const key1 = createKey() + const key2 = createKey() + const queryFn1 = vi.fn<() => number>().mockReturnValue(1) + const queryFn2 = vi.fn<() => number>().mockReturnValue(2) + const observer = new QueriesObserver(queryClient, [ + { queryKey: key1, queryFn: queryFn1 }, + { queryKey: key2, queryFn: queryFn2 }, + ]) + const unsubscribe = observer.subscribe(() => undefined) + await Promise.resolve() + + const queries = observer.getQueries() + + expect(queries).toHaveLength(2) + expect(queries[0]?.queryKey).toStrictEqual(key1) + expect(queries[1]?.queryKey).toStrictEqual(key2) + + unsubscribe() + queryClient.clear() + }) +}) diff --git a/packages/query-core/src/__tests__/notifyManager.test-d.tsx b/packages/query-core/src/__tests__/notifyManager.test-d.tsx index 5ccfd3addcc..33a685ab1d4 100644 --- a/packages/query-core/src/__tests__/notifyManager.test-d.tsx +++ b/packages/query-core/src/__tests__/notifyManager.test-d.tsx @@ -20,17 +20,6 @@ describe('notifyManager', () => { }>() }) - it('should only expose its documented members', () => { - expectTypeOf>().toEqualTypeOf< - | 'batch' - | 'batchCalls' - | 'schedule' - | 'setNotifyFunction' - | 'setBatchNotifyFunction' - | 'setScheduler' - >() - }) - describe('batch', () => { it('should pass the return type of the callback through', () => { const localNotifyManager = createNotifyManager() @@ -161,24 +150,6 @@ describe('notifyManager', () => { }) }) - describe('setBatchNotifyFunction', () => { - it('should only accept a function taking a callback', () => { - const localNotifyManager = createNotifyManager() - - expectTypeOf( - localNotifyManager.setBatchNotifyFunction, - ).parameters.toEqualTypeOf<[fn: (callback: () => void) => void]>() - }) - - it('should return void', () => { - const localNotifyManager = createNotifyManager() - - expectTypeOf( - localNotifyManager.setBatchNotifyFunction, - ).returns.toEqualTypeOf() - }) - }) - describe('setScheduler', () => { it('should only accept a function taking a callback', () => { const localNotifyManager = createNotifyManager() diff --git a/packages/query-core/src/__tests__/notifyManager.test.tsx b/packages/query-core/src/__tests__/notifyManager.test.tsx index 46037beacee..816dc4bd975 100644 --- a/packages/query-core/src/__tests__/notifyManager.test.tsx +++ b/packages/query-core/src/__tests__/notifyManager.test.tsx @@ -76,25 +76,6 @@ describe('notifyManager', () => { expect(notifySpy).toHaveBeenCalledTimes(1) }) - it('should use custom batch notify function', async () => { - const notifyManagerTest = createNotifyManager() - const batchNotifySpy = vi.fn<(callback: () => void) => void>((cb) => cb()) - const callbackSpy1 = vi.fn<() => void>() - const callbackSpy2 = vi.fn<() => void>() - - notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) - - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(callbackSpy1) - notifyManagerTest.schedule(callbackSpy2) - }) - - await vi.advanceTimersByTimeAsync(0) - expect(batchNotifySpy).toHaveBeenCalledWith(expect.any(Function)) - expect(callbackSpy1).toHaveBeenCalledWith() - expect(callbackSpy2).toHaveBeenCalledWith() - }) - it('should batch calls correctly', async () => { const notifyManagerTest = createNotifyManager() const callbackSpy = vi.fn<(a: number, b: string) => void>() diff --git a/packages/query-core/src/__tests__/queriesObserver.test-d.tsx b/packages/query-core/src/__tests__/queriesObserver.test-d.tsx index 0cb59c59e08..55729bc0634 100644 --- a/packages/query-core/src/__tests__/queriesObserver.test-d.tsx +++ b/packages/query-core/src/__tests__/queriesObserver.test-d.tsx @@ -1,7 +1,7 @@ import { createKey } from '@tanstack/query-test-utils' import { afterEach, beforeEach, describe, expectTypeOf, it } from 'vitest' import { QueriesObserver, QueryClient, defaultQueryFn } from '..' -import type { Query, QueryObserver, QueryObserverResult } from '..' +import type { QueryObserver, QueryObserverResult } from '..' import type { QueriesObserverOptions } from '../queriesObserver' import type { ObserverOptionsInput } from '../queryObserver' @@ -18,14 +18,15 @@ describe('queriesObserver', () => { }) describe('QueriesObserver', () => { - it('should only expose its documented members', () => { - expectTypeOf().toEqualTypeOf< + it('should expose the common observer methods', () => { + expectTypeOf< + Exclude + >().toEqualTypeOf< | 'subscribe' | 'hasListeners' | 'destroy' | 'setQueries' | 'getCurrentResult' - | 'getQueries' | 'getObservers' | 'createResultReader' >() @@ -185,14 +186,6 @@ describe('queriesObserver', () => { }) }) - describe('getQueries', () => { - it('should return the observed queries', () => { - const observer = new QueriesObserver(queryClient, []) - - expectTypeOf(observer.getQueries()).toEqualTypeOf>() - }) - }) - describe('getObservers', () => { it('should return the underlying observers', () => { const observer = new QueriesObserver(queryClient, []) diff --git a/packages/query-core/src/__tests__/queriesObserver.test.tsx b/packages/query-core/src/__tests__/queriesObserver.test.tsx index db926c7e274..41463f22631 100644 --- a/packages/query-core/src/__tests__/queriesObserver.test.tsx +++ b/packages/query-core/src/__tests__/queriesObserver.test.tsx @@ -84,7 +84,9 @@ describe('queriesObserver', () => { listener.mockClear() readerB.commit() expect(listener).toHaveBeenCalledTimes(1) - expect(observer.getQueries()[0]!.queryKey).toStrictEqual(keyB) + expect( + observer.getObservers()[0]!.getCurrentQuery().queryKey, + ).toStrictEqual(keyB) listener.mockClear() queryClient.setQueryData(keyA, 3) expect(listener).not.toHaveBeenCalled() @@ -144,7 +146,9 @@ describe('queriesObserver', () => { expect(select).toHaveBeenCalledTimes(1) expect(observer.getCurrentResult()[0]!.data).toBe(snapshot[0]!.data) expect( - observer.getQueries().map((query) => query.queryKey), + observer + .getObservers() + .map((entry) => entry.getCurrentQuery().queryKey), ).toStrictEqual([keyB, keyA]) unsubscribe() }) @@ -298,27 +302,6 @@ describe('queriesObserver', () => { expect(observerResult).toMatchObject([{ data: 1 }, { data: 2 }]) }) - it('should return current queries via getQueries', async () => { - const key1 = createKey() - const key2 = createKey() - const queryFn1 = vi.fn<() => number>().mockReturnValue(1) - const queryFn2 = vi.fn<() => number>().mockReturnValue(2) - const observer = new QueriesObserver(queryClient, [ - { queryKey: key1, queryFn: queryFn1 }, - { queryKey: key2, queryFn: queryFn2 }, - ]) - const unsubscribe = observer.subscribe(() => undefined) - await vi.advanceTimersByTimeAsync(0) - - const queries = observer.getQueries() - - expect(queries).toHaveLength(2) - expect(queries[0]?.queryKey).toStrictEqual(key1) - expect(queries[1]?.queryKey).toStrictEqual(key2) - - unsubscribe() - }) - it('should update when a query updates', async () => { const key1 = createKey() const key2 = createKey() diff --git a/packages/react-query-no-core-pluggable/src/HydrationBoundary.tsx b/packages/react-query-no-core-pluggable/src/HydrationBoundary.tsx index f51a7928983..3b22e90597a 100644 --- a/packages/react-query-no-core-pluggable/src/HydrationBoundary.tsx +++ b/packages/react-query-no-core-pluggable/src/HydrationBoundary.tsx @@ -1,13 +1,10 @@ 'use client' import * as React from 'react' import { useQueryClient } from './QueryClientProvider' -import { hydrate } from './runtime/index' -import type { - DehydratedState, - HydrateOptions, - OmitKeyof, - QueryClient, -} from './runtime/index' +import { hydrate } from './runtime/hydration' +import type { DehydratedState, OmitKeyof } from '@tanstack/query-types/bindings' +import type { HydrateOptions } from './runtime/hydration' +import type { QueryClient } from './runtime/queryClient' /** * The props accepted by `HydrationBoundary`. diff --git a/packages/react-query-no-core-pluggable/src/QueryClientProvider.tsx b/packages/react-query-no-core-pluggable/src/QueryClientProvider.tsx index 3f93a38df1e..e307347cfea 100644 --- a/packages/react-query-no-core-pluggable/src/QueryClientProvider.tsx +++ b/packages/react-query-no-core-pluggable/src/QueryClientProvider.tsx @@ -1,6 +1,6 @@ 'use client' import * as React from 'react' -import type { QueryClient } from './runtime/index' +import type { QueryClient } from './runtime/queryClient' /** * The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it. diff --git a/packages/react-query-no-core-pluggable/src/errorBoundaryUtils.ts b/packages/react-query-no-core-pluggable/src/errorBoundaryUtils.ts index 5d927363a0b..8ba639b93bc 100644 --- a/packages/react-query-no-core-pluggable/src/errorBoundaryUtils.ts +++ b/packages/react-query-no-core-pluggable/src/errorBoundaryUtils.ts @@ -1,14 +1,16 @@ 'use client' import * as React from 'react' -import { shouldThrowError } from './runtime/index' -import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import { shouldThrowError } from './runtime/utils' import type { - DefaultedQueryObserverOptions, - Query, QueryKey, QueryObserverResult, +} from '@tanstack/query-types/bindings' +import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import type { Query } from './runtime/query' +import type { + DefaultedQueryObserverOptions, ThrowOnError, -} from './runtime/index' +} from './runtime/types' /** * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`), diff --git a/packages/react-query-no-core-pluggable/src/index.ts b/packages/react-query-no-core-pluggable/src/index.ts index 816f5f3a89e..66030409a7a 100644 --- a/packages/react-query-no-core-pluggable/src/index.ts +++ b/packages/react-query-no-core-pluggable/src/index.ts @@ -1,8 +1,167 @@ /* istanbul ignore file */ // Public cache and observer API -// oxlint-disable-next-line tanstack-query/no-restricted-syntax -export * from './runtime/index' +export { focusManager } from './runtime/focusManager' +export type { FocusManager } from './runtime/focusManager' +export { environmentManager } from './runtime/environmentManager' +export { + defaultShouldDehydrateMutation, + defaultShouldDehydrateQuery, + dehydrate, + dehydrateQuery, + hydrate, +} from './runtime/hydration' +export { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' +export { MutationCache } from './runtime/mutationCache' +export type { + MutationCacheNotifyEvent, + MutationCacheConfig, +} from './runtime/mutationCache' +export { MutationObserver } from './runtime/mutationObserver' +export { defaultScheduler, notifyManager } from './runtime/notifyManager' +export { onlineManager } from './runtime/onlineManager' +export type { OnlineManager } from './runtime/onlineManager' +export { QueriesObserver } from './runtime/queriesObserver' +export { QueryCache } from './runtime/queryCache' +export type { + QueryCacheNotifyEvent, + QueryCacheConfig, +} from './runtime/queryCache' +export { QueryClient } from './runtime/queryClient' +export type { QueryRuntime } from './runtime/runtimeBinding' +export { refetchInterval } from './runtime/refetchInterval' +export type { RefetchInterval } from './runtime/refetchInterval' +export { QueryObserver } from './runtime/queryObserver' +export type { + QueryObserverResultReader, + ManagedTimerId, + TimeoutCallback, + TimeoutProvider, + DefaultQueryFn, + SkipToken, + Updater, + DehydratedState, + MutationState, + QueriesObserverOptions, + QueriesObserverResultReader, + QueryState, + NonUndefinedGuard, + DistributiveOmit, + OmitKeyof, + Override, + Register, + DefaultError, + QueryKey, + 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, + QueryObserverResult, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverPendingResult, + InfiniteQueryObserverLoadingResult, + InfiniteQueryObserverLoadingErrorResult, + InfiniteQueryObserverRefetchErrorResult, + InfiniteQueryObserverSuccessResult, + InfiniteQueryObserverPlaceholderResult, + DefinedInfiniteQueryObserverResult, + InfiniteQueryObserverResult, + MutationKey, + MutationStatus, + MutationScope, + MutationMeta, + CancelOptions, + SetDataOptions, + NotifyEventType, + NotifyEvent, +} from '@tanstack/query-types/bindings' +export { CancelledError } from './runtime/retryer' +export { timeoutManager } from './runtime/timeoutManager' +export type { TimeoutManager } from './runtime/timeoutManager' +export { + hashKey, + keepPreviousData, + matchMutation, + matchQuery, + noop, + partialMatchKey, + replaceEqualDeep, + shouldThrowError, + defaultQueryFn, + skipToken, +} from './runtime/utils' +export type { MutationFilters, QueryFilters } from './runtime/utils' +export { streamedQuery } from './runtime/streamedQuery' +export type { DehydrateOptions, HydrateOptions } from './runtime/hydration' +export { Mutation } from './runtime/mutation' +export { Query } from './runtime/query' +export { dataTagSymbol, dataTagErrorSymbol, unsetMarker } from './runtime/types' +export type { + QueryFunction, + StaleTimeFunction, + QueryBooleanOption, + QueryPersister, + QueryFunctionContext, + PlaceholderDataFunction, + QueryOptions, + ThrowOnError, + QueryObserverOptions, + DefaultedQueryObserverOptions, + InfiniteQueryObserverOptions, + DefaultedInfiniteQueryObserverOptions, + QueryExecuteOptions, + InfiniteQueryExecuteOptions, + InvalidateQueryFilters, + RefetchQueryFilters, + MutationFunctionContext, + MutationFunction, + MutationOptions, + MutationObserverOptions, + MutateOptions, + MutateFunctionRest, + MutateFunction, + MutationObserverBaseResult, + MutationObserverIdleResult, + MutationObserverLoadingResult, + MutationObserverErrorResult, + MutationObserverSuccessResult, + MutationObserverResult, + QueryClientConfig, + DefaultOptions, +} from './runtime/types' // React Query export type { diff --git a/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts b/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts index 669863b4905..1cf0bc837d5 100644 --- a/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts +++ b/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts @@ -8,7 +8,7 @@ import type { QueryKey, QueryKeyWithDataTag, SkipToken, -} from './runtime/index' +} from '@tanstack/query-types/bindings' import type { UseInfiniteQueryOptions } from './types' /** diff --git a/packages/react-query-no-core-pluggable/src/mutationOptions.ts b/packages/react-query-no-core-pluggable/src/mutationOptions.ts index b92dbbb2b7b..904ed253fc8 100644 --- a/packages/react-query-no-core-pluggable/src/mutationOptions.ts +++ b/packages/react-query-no-core-pluggable/src/mutationOptions.ts @@ -1,5 +1,5 @@ import { identity } from './runtime/identity' -import type { DefaultError, WithRequired } from './runtime/index' +import type { DefaultError, WithRequired } from '@tanstack/query-types/bindings' import type { UseMutationOptions } from './types' type MutationOptionsFn = { diff --git a/packages/react-query-no-core-pluggable/src/queryOptions.ts b/packages/react-query-no-core-pluggable/src/queryOptions.ts index fe919c06e48..c3b557c51f6 100644 --- a/packages/react-query-no-core-pluggable/src/queryOptions.ts +++ b/packages/react-query-no-core-pluggable/src/queryOptions.ts @@ -5,11 +5,11 @@ import type { InitialDataFunction, NonUndefinedGuard, OmitKeyof, - QueryFunction, QueryKey, QueryKeyWithDataTag, SkipToken, -} from './runtime/index' +} from '@tanstack/query-types/bindings' +import type { QueryFunction } from './runtime/types' import type { UseQueryOptions } from './types' /** diff --git a/packages/react-query-no-core-pluggable/src/runtime/focusManager.ts b/packages/react-query-no-core-pluggable/src/runtime/focusManager.ts index 6182b408e83..40ea98cff79 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/focusManager.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/focusManager.ts @@ -139,4 +139,4 @@ export class FocusManager extends Subscribable { /** * Singleton instance of {@link FocusManager}, used to manage and observe the focus state within TanStack Query. */ -export const focusManager = /* @__PURE__ */ new FocusManager() +export const focusManager = /* #__PURE__ */ new FocusManager() diff --git a/packages/react-query-no-core-pluggable/src/runtime/index.ts b/packages/react-query-no-core-pluggable/src/runtime/index.ts deleted file mode 100644 index ccd7586e985..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/index.ts +++ /dev/null @@ -1,170 +0,0 @@ -/* istanbul ignore file */ - -export { focusManager } from './focusManager' -export type { FocusManager } from './focusManager' -export { environmentManager } from './environmentManager' -export { - defaultShouldDehydrateMutation, - defaultShouldDehydrateQuery, - dehydrate, - dehydrateQuery, - hydrate, -} from './hydration' -export { InfiniteQueryObserver } from './infiniteQueryObserver' -export { MutationCache } from './mutationCache' -export type { MutationCacheNotifyEvent } from './mutationCache' -export { MutationObserver } from './mutationObserver' -export { defaultScheduler, notifyManager } from './notifyManager' -export { onlineManager } from './onlineManager' -export type { OnlineManager } from './onlineManager' -export { QueriesObserver } from './queriesObserver' -export { QueryCache } from './queryCache' -export type { QueryCacheNotifyEvent } from './queryCache' -export { QueryClient } from './queryClient' -export type { QueryRuntime } from './runtimeBinding' -export { refetchInterval } from './refetchInterval' -export type { RefetchInterval } from './refetchInterval' -export { QueryObserver } from './queryObserver' -export type { QueryObserverResultReader } from './queryObserver' -export { CancelledError } from './retryer' -export { - timeoutManager, - type ManagedTimerId, - type TimeoutCallback, - type TimeoutManager, - type TimeoutProvider, -} from './timeoutManager' -export { - hashKey, - keepPreviousData, - matchMutation, - matchQuery, - noop, - partialMatchKey, - replaceEqualDeep, - shouldThrowError, - defaultQueryFn, - skipToken, -} from './utils' -export type { - DefaultQueryFn, - MutationFilters, - QueryFilters, - SkipToken, - Updater, -} from './utils' - -export { streamedQuery } from './streamedQuery' - -// Types -export type { - DehydratedState, - DehydrateOptions, - HydrateOptions, -} from './hydration' -export { Mutation } from './mutation' -export type { MutationState } from './mutation' -export type { MutationCacheConfig } from './mutationCache' -export type { - QueriesObserverOptions, - QueriesObserverResultReader, -} from './queriesObserver' -export { Query } from './query' -export type { QueryState } from './query' -export type { QueryCacheConfig } from './queryCache' -export { dataTagSymbol, dataTagErrorSymbol, unsetMarker } from './types' -export type { - NonUndefinedGuard, - DistributiveOmit, - OmitKeyof, - Override, - Register, - DefaultError, - QueryKey, - UnsetMarker, - AnyDataTag, - DataTag, - QueryKeyWithDataTag, - InferDataFromTag, - InferErrorFromTag, - QueryFunction, - StaleTime, - StaleTimeFunction, - QueryBooleanOption, - QueryPersister, - QueryFunctionContext, - InitialDataFunction, - PlaceholderDataFunction, - QueriesPlaceholderDataFunction, - EqualityFn, - CacheKeyHashFunction, - CacheKeyConfig, - GetPreviousPageParamFunction, - GetNextPageParamFunction, - InfiniteData, - QueryMeta, - NetworkMode, - NotifyOnChangeProps, - QueryOptions, - InitialPageParam, - InfiniteQueryPageParamsOptions, - ThrowOnError, - QueryObserverOptions, - WithRequired, - DefaultedQueryObserverOptions, - InfiniteQueryObserverOptions, - DefaultedInfiniteQueryObserverOptions, - QueryExecuteOptions, - InfiniteQueryExecuteOptions, - ResultOptions, - RefetchOptions, - InvalidateQueryFilters, - RefetchQueryFilters, - InvalidateOptions, - ResetOptions, - FetchNextPageOptions, - FetchPreviousPageOptions, - QueryStatus, - FetchStatus, - QueryObserverBaseResult, - QueryObserverPendingResult, - QueryObserverLoadingResult, - QueryObserverLoadingErrorResult, - QueryObserverRefetchErrorResult, - QueryObserverSuccessResult, - QueryObserverPlaceholderResult, - DefinedQueryObserverResult, - QueryObserverResult, - InfiniteQueryObserverBaseResult, - InfiniteQueryObserverPendingResult, - InfiniteQueryObserverLoadingResult, - InfiniteQueryObserverLoadingErrorResult, - InfiniteQueryObserverRefetchErrorResult, - InfiniteQueryObserverSuccessResult, - InfiniteQueryObserverPlaceholderResult, - DefinedInfiniteQueryObserverResult, - InfiniteQueryObserverResult, - MutationKey, - MutationStatus, - MutationScope, - MutationMeta, - MutationFunctionContext, - MutationFunction, - MutationOptions, - MutationObserverOptions, - MutateOptions, - MutateFunctionRest, - MutateFunction, - MutationObserverBaseResult, - MutationObserverIdleResult, - MutationObserverLoadingResult, - MutationObserverErrorResult, - MutationObserverSuccessResult, - MutationObserverResult, - QueryClientConfig, - DefaultOptions, - CancelOptions, - SetDataOptions, - NotifyEventType, - NotifyEvent, -} from './types' diff --git a/packages/react-query-no-core-pluggable/src/runtime/notifyManager.ts b/packages/react-query-no-core-pluggable/src/runtime/notifyManager.ts index aaac1276c0d..d60c0155755 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/notifyManager.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/notifyManager.ts @@ -1,6 +1,5 @@ import type { BatchCallsCallback, - BatchNotifyFunction, NotifyCallback, NotifyFunction, ScheduleFunction, @@ -23,9 +22,6 @@ export function createNotifyManager() { let notifyFn: NotifyFunction = (callback) => { callback() } - let batchNotifyFn: BatchNotifyFunction = (callback: () => void) => { - callback() - } let scheduleFn = defaultScheduler const schedule = (callback: NotifyCallback): void => { @@ -42,10 +38,8 @@ export function createNotifyManager() { queue = [] if (originalQueue.length) { scheduleFn(() => { - batchNotifyFn(() => { - originalQueue.forEach((callback) => { - notifyFn(callback) - }) + originalQueue.forEach((callback) => { + notifyFn(callback) }) }) } @@ -100,22 +94,6 @@ export function createNotifyManager() { setNotifyFunction: (fn: NotifyFunction) => { notifyFn = fn }, - /** - * Use this method to set a custom function to batch notifications together into a single tick. - * Framework adapters use this to plug in their own batching primitive, so that a single query - * update only triggers one re-render instead of one per subscriber. - * @param fn - Receives a function that runs a batch of notifications and must call it. - * @example - * ```ts - * import { notifyManager } from '@tanstack/react-query-no-core-pluggable' - * import { batch } from 'solid-js' - * - * notifyManager.setBatchNotifyFunction(batch) - * ``` - */ - setBatchNotifyFunction: (fn: BatchNotifyFunction) => { - batchNotifyFn = fn - }, /** * Configures a custom callback that schedules when the next batch runs. * The default behavior is `queueMicrotask(callback)`. diff --git a/packages/react-query-no-core-pluggable/src/runtime/queriesObserver.ts b/packages/react-query-no-core-pluggable/src/runtime/queriesObserver.ts index 1a9392c5ca5..2b91a71a5d8 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/queriesObserver.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/queriesObserver.ts @@ -226,15 +226,6 @@ export class QueriesObserver< return this.#result } - /** - * Returns the underlying `Query` instances currently being observed, in - * the same order as the queries passed to the constructor or `setQueries`. - * @returns The observed queries. - */ - getQueries() { - return this.#observers.map((observer) => observer.getCurrentQuery()) - } - /** * Returns the underlying `QueryObserver` instances this observer manages, * in the same order as the queries passed to the constructor or diff --git a/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts b/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts index 5c932a5ee2e..c304f9c5ca9 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts @@ -393,9 +393,9 @@ export class QueryObserver< /** * Records that the given `QueryObserverResult` property was read, so a subsequent update only - * notifies this observer if a tracked property actually changed. Normally called indirectly via - * {@link QueryObserver#trackResult}'s proxy; exposed directly for adapters that track property - * access themselves (e.g. through their own reactivity system) instead of via the proxy. + * notifies this observer if a tracked property actually changed. {@link QueryObserver#trackResult} + * calls this on property access. `useQueries` tracks the same property across its observers + * when computing a combined result. * @param key - The name of the property that was read. */ trackProp(key: keyof QueryObserverResult) { @@ -556,9 +556,10 @@ export class QueryObserver< } #updatePolling(restart = false): void { - const option = this.options.refetchInterval - const polling = - typeof option === 'function' ? option(this.#currentQuery) : option + const polling = resolveQueryValue( + this.options.refetchInterval, + this.#currentQuery, + ) if (polling) { this.#polling = polling.update(this, this.#polling, restart, () => this.#executeFetch(), diff --git a/packages/react-query-no-core-pluggable/src/runtime/refetchInterval.ts b/packages/react-query-no-core-pluggable/src/runtime/refetchInterval.ts index 2366117c196..20a1733de0b 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/refetchInterval.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/refetchInterval.ts @@ -1,7 +1,9 @@ import { isServer } from './environmentManager' import { focusManager } from './focusManager' import { timeoutManager } from './timeoutManager' -import { isValidTimeout } from './utils' +import { isValidTimeout, resolveQueryValue } from './utils' +import type { QueryKey } from '@tanstack/query-types/bindings' +import type { Query } from './query' interface PollingTimer { query: object @@ -40,7 +42,7 @@ export function refetchInterval(value: Delay): RefetchInterval export function refetchInterval( value: Delay | ((query: TQuery) => Delay), ): RefetchInterval -/* @__NO_SIDE_EFFECTS__ */ +/* #__NO_SIDE_EFFECTS__ */ export function refetchInterval( value: Delay | ((query: TQuery) => Delay), ): RefetchInterval { @@ -55,24 +57,22 @@ export function refetchInterval( * @param fetch - Refetches the observer's current query. * @returns The active timer and its cleanup, when polling is enabled. */ -function updatePolling( - this: RefetchInterval, - observer: PollingObserver, +function updatePolling( + this: RefetchInterval>, + observer: PollingObserver>, current: PollingTimer | undefined, restart: boolean, fetch: () => void, ): PollingTimer | undefined { const query = observer.getCurrentQuery() - const { value } = this - const delay = typeof value === 'function' ? value(query) : value + const delay = resolveQueryValue(this.value, query) if (!observer.hasListeners()) return - const { enabled } = observer.options if ( isServer() || !isValidTimeout(delay) || delay === 0 || - (typeof enabled === 'function' ? enabled(query) : enabled) === false + resolveQueryValue(observer.options.enabled, query) === false ) { current?.stop() return diff --git a/packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts b/packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts index 2d650ed10a2..35f211807e3 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts @@ -202,7 +202,7 @@ export class TimeoutManager implements Omit { /** * Singleton instance of {@link TimeoutManager}, used throughout TanStack Query to schedule and cancel timers. */ -export const timeoutManager = /* @__PURE__ */ new TimeoutManager() +export const timeoutManager = /* #__PURE__ */ new TimeoutManager() /** * In many cases code wants to delay to the next event loop tick; this is not diff --git a/packages/react-query-no-core-pluggable/src/suspense.ts b/packages/react-query-no-core-pluggable/src/suspense.ts index 4c1cb60de54..09ff0957953 100644 --- a/packages/react-query-no-core-pluggable/src/suspense.ts +++ b/packages/react-query-no-core-pluggable/src/suspense.ts @@ -1,14 +1,14 @@ import { use } from 'react' -import { QueryObserver } from './runtime/index' -import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import { QueryObserver } from './runtime/queryObserver' import type { DefaultError, - DefaultedQueryObserverOptions, - Query, - QueryClient, QueryKey, QueryObserverResult, -} from './runtime/index' +} from '@tanstack/query-types/bindings' +import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import type { Query } from './runtime/query' +import type { QueryClient } from './runtime/queryClient' +import type { DefaultedQueryObserverOptions } from './runtime/types' type SuspensePromiseEntry = { fetchPromise: Promise diff --git a/packages/react-query-no-core-pluggable/src/types.ts b/packages/react-query-no-core-pluggable/src/types.ts index c0ca73490e4..ee037a36c4d 100644 --- a/packages/react-query-no-core-pluggable/src/types.ts +++ b/packages/react-query-no-core-pluggable/src/types.ts @@ -6,22 +6,24 @@ import type { DefinedQueryObserverResult, DistributiveOmit, InfiniteData, - InfiniteQueryExecuteOptions, - InfiniteQueryObserverOptions, InfiniteQueryObserverPlaceholderResult, InfiniteQueryObserverResult, - MutateFunction, - MutationObserverOptions, - MutationObserverResult, OmitKeyof, Override, - QueryExecuteOptions, QueryKey, - QueryObserverOptions, QueryObserverPlaceholderResult, QueryObserverResult, SkipToken, -} from './runtime/index' +} from '@tanstack/query-types/bindings' +import type { + InfiniteQueryExecuteOptions, + InfiniteQueryObserverOptions, + MutateFunction, + MutationObserverOptions, + MutationObserverResult, + QueryExecuteOptions, + QueryObserverOptions, +} from './runtime/types' /** * {@link UseBaseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't diff --git a/packages/react-query-no-core-pluggable/src/useBaseQuery.ts b/packages/react-query-no-core-pluggable/src/useBaseQuery.ts index 052bd5bb8b5..7216bf66c41 100644 --- a/packages/react-query-no-core-pluggable/src/useBaseQuery.ts +++ b/packages/react-query-no-core-pluggable/src/useBaseQuery.ts @@ -10,11 +10,11 @@ import { } from './errorBoundaryUtils' import { useObserverSnapshot } from './useObserverSnapshot' import type { - QueryClient, QueryKey, - QueryObserver, QueryObserverResult, -} from './runtime' +} from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' +import type { QueryObserver } from './runtime/queryObserver' import type { suspenseQueryPolicy } from './suspense' import type { UseBaseQueryOptions } from './types' diff --git a/packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts b/packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts index d895e3c3dd3..ab42edd48b8 100644 --- a/packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts +++ b/packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts @@ -1,17 +1,17 @@ 'use client' -import { InfiniteQueryObserver } from './runtime/index' +import { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' import { useBaseQuery } from './useBaseQuery' -import type { - DefinedInitialDataInfiniteOptions, - UndefinedInitialDataInfiniteOptions, -} from './infiniteQueryOptions' import type { DefaultError, InfiniteData, - QueryClient, QueryKey, - QueryObserver, -} from './runtime/index' +} from '@tanstack/query-types/bindings' +import type { + DefinedInitialDataInfiniteOptions, + UndefinedInitialDataInfiniteOptions, +} from './infiniteQueryOptions' +import type { QueryClient } from './runtime/queryClient' +import type { QueryObserver } from './runtime/queryObserver' import type { DefinedUseInfiniteQueryResult, UseInfiniteQueryOptions, diff --git a/packages/react-query-no-core-pluggable/src/useIsFetching.ts b/packages/react-query-no-core-pluggable/src/useIsFetching.ts index b423949a91b..a34c4aafe9e 100644 --- a/packages/react-query-no-core-pluggable/src/useIsFetching.ts +++ b/packages/react-query-no-core-pluggable/src/useIsFetching.ts @@ -1,8 +1,9 @@ 'use client' import * as React from 'react' import { useQueryClient } from './QueryClientProvider' -import { notifyManager } from './runtime/index' -import type { QueryClient, QueryFilters } from './runtime/index' +import { notifyManager } from './runtime/notifyManager' +import type { QueryClient } from './runtime/queryClient' +import type { QueryFilters } from './runtime/utils' /** * The `useIsFetching` hook returns the `number` of the queries that your application is loading or fetching in diff --git a/packages/react-query-no-core-pluggable/src/useMutation.ts b/packages/react-query-no-core-pluggable/src/useMutation.ts index b4b64f471a1..702969bd830 100644 --- a/packages/react-query-no-core-pluggable/src/useMutation.ts +++ b/packages/react-query-no-core-pluggable/src/useMutation.ts @@ -1,13 +1,11 @@ 'use client' import * as React from 'react' import { useQueryClient } from './QueryClientProvider' -import { - MutationObserver, - noop, - notifyManager, - shouldThrowError, -} from './runtime/index' -import type { DefaultError, QueryClient } from './runtime/index' +import { MutationObserver } from './runtime/mutationObserver' +import { notifyManager } from './runtime/notifyManager' +import { noop, shouldThrowError } from './runtime/utils' +import type { DefaultError } from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' import type { UseMutateFunction, UseMutationOptions, diff --git a/packages/react-query-no-core-pluggable/src/useMutationState.ts b/packages/react-query-no-core-pluggable/src/useMutationState.ts index 8a71c381bf4..28e15d17301 100644 --- a/packages/react-query-no-core-pluggable/src/useMutationState.ts +++ b/packages/react-query-no-core-pluggable/src/useMutationState.ts @@ -1,14 +1,13 @@ 'use client' import * as React from 'react' import { useQueryClient } from './QueryClientProvider' -import { notifyManager, replaceEqualDeep } from './runtime/index' -import type { - Mutation, - MutationCache, - MutationFilters, - MutationState, - QueryClient, -} from './runtime/index' +import { notifyManager } from './runtime/notifyManager' +import { replaceEqualDeep } from './runtime/utils' +import type { MutationState } from '@tanstack/query-types/bindings' +import type { Mutation } from './runtime/mutation' +import type { MutationCache } from './runtime/mutationCache' +import type { QueryClient } from './runtime/queryClient' +import type { MutationFilters } from './runtime/utils' /** * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending` diff --git a/packages/react-query-no-core-pluggable/src/usePrefetchInfiniteQuery.tsx b/packages/react-query-no-core-pluggable/src/usePrefetchInfiniteQuery.tsx index 4bf20560b89..ef9463f348d 100644 --- a/packages/react-query-no-core-pluggable/src/usePrefetchInfiniteQuery.tsx +++ b/packages/react-query-no-core-pluggable/src/usePrefetchInfiniteQuery.tsx @@ -1,11 +1,11 @@ import { useQueryClient } from './QueryClientProvider' -import { noop } from './runtime/index' +import { noop } from './runtime/utils' import type { DefaultError, InfiniteData, - QueryClient, QueryKey, -} from './runtime/index' +} from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' import type { UsePrefetchInfiniteQueryOptions } from './types' /** diff --git a/packages/react-query-no-core-pluggable/src/usePrefetchQuery.tsx b/packages/react-query-no-core-pluggable/src/usePrefetchQuery.tsx index 458c9424d88..04429309988 100644 --- a/packages/react-query-no-core-pluggable/src/usePrefetchQuery.tsx +++ b/packages/react-query-no-core-pluggable/src/usePrefetchQuery.tsx @@ -1,6 +1,7 @@ import { useQueryClient } from './QueryClientProvider' -import { noop } from './runtime/index' -import type { DefaultError, QueryClient, QueryKey } from './runtime/index' +import { noop } from './runtime/utils' +import type { DefaultError, QueryKey } from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' import type { UsePrefetchQueryOptions } from './types' /** diff --git a/packages/react-query-no-core-pluggable/src/useQueries.ts b/packages/react-query-no-core-pluggable/src/useQueries.ts index 4f03e21813f..7270df47dc8 100644 --- a/packages/react-query-no-core-pluggable/src/useQueries.ts +++ b/packages/react-query-no-core-pluggable/src/useQueries.ts @@ -15,12 +15,14 @@ import type { OmitKeyof, QueriesObserverOptions, QueriesPlaceholderDataFunction, - QueryClient, - QueryFunction, QueryKey, +} from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' +import type { + QueryFunction, QueryObserverOptions, ThrowOnError, -} from './runtime' +} from './runtime/types' import type { suspenseQueriesPolicy } from './suspense' import type { DefinedUseQueryResult, diff --git a/packages/react-query-no-core-pluggable/src/useQuery.ts b/packages/react-query-no-core-pluggable/src/useQuery.ts index 842a1226bda..070724dabf8 100644 --- a/packages/react-query-no-core-pluggable/src/useQuery.ts +++ b/packages/react-query-no-core-pluggable/src/useQuery.ts @@ -1,11 +1,12 @@ 'use client' -import { QueryObserver } from './runtime/index' +import { QueryObserver } from './runtime/queryObserver' import { useBaseQuery } from './useBaseQuery' +import type { DefaultError, QueryKey } from '@tanstack/query-types/bindings' import type { DefinedInitialDataOptions, UndefinedInitialDataOptions, } from './queryOptions' -import type { DefaultError, QueryClient, QueryKey } from './runtime/index' +import type { QueryClient } from './runtime/queryClient' import type { DefinedUseQueryResult, UseQueryOptions, diff --git a/packages/react-query-no-core-pluggable/src/useSuspenseInfiniteQuery.ts b/packages/react-query-no-core-pluggable/src/useSuspenseInfiniteQuery.ts index d19264b0d1c..0b347444c20 100644 --- a/packages/react-query-no-core-pluggable/src/useSuspenseInfiniteQuery.ts +++ b/packages/react-query-no-core-pluggable/src/useSuspenseInfiniteQuery.ts @@ -1,15 +1,16 @@ 'use client' -import { InfiniteQueryObserver, skipToken } from './runtime/index' +import { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' +import { skipToken } from './runtime/utils' import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' import { useBaseQuery } from './useBaseQuery' import type { DefaultError, InfiniteData, OmitKeyof, - QueryClient, QueryKey, - QueryObserver, -} from './runtime/index' +} from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' +import type { QueryObserver } from './runtime/queryObserver' import type { UseInfiniteQueryOptions, UseInfiniteQueryResult, diff --git a/packages/react-query-no-core-pluggable/src/useSuspenseQueries.ts b/packages/react-query-no-core-pluggable/src/useSuspenseQueries.ts index 20a5854ad4c..7265653bb3b 100644 --- a/packages/react-query-no-core-pluggable/src/useSuspenseQueries.ts +++ b/packages/react-query-no-core-pluggable/src/useSuspenseQueries.ts @@ -1,16 +1,15 @@ 'use client' -import { skipToken } from './runtime/index' +import { skipToken } from './runtime/utils' import { defaultThrowOnError, suspenseQueriesPolicy } from './suspense' import { useBaseQueries } from './useQueries' import type { DefaultError, OmitKeyof, QueriesPlaceholderDataFunction, - QueryClient, - QueryFunction, QueryKey, - ThrowOnError, -} from './runtime/index' +} from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' +import type { QueryFunction, ThrowOnError } from './runtime/types' import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types' // `placeholderData` functions in useQueries never receive previous query data. diff --git a/packages/react-query-no-core-pluggable/src/useSuspenseQuery.ts b/packages/react-query-no-core-pluggable/src/useSuspenseQuery.ts index b187bbcf23b..258522826ba 100644 --- a/packages/react-query-no-core-pluggable/src/useSuspenseQuery.ts +++ b/packages/react-query-no-core-pluggable/src/useSuspenseQuery.ts @@ -1,13 +1,14 @@ 'use client' -import { QueryObserver, skipToken } from './runtime/index' +import { QueryObserver } from './runtime/queryObserver' +import { skipToken } from './runtime/utils' import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' import { useBaseQuery } from './useBaseQuery' import type { DefaultError, OmitKeyof, - QueryClient, QueryKey, -} from './runtime/index' +} from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' import type { UseQueryOptions, UseQueryResult, diff --git a/packages/react-query-no-core/README.md b/packages/react-query-no-core/README.md index 1358c181827..8d49a7fca37 100644 --- a/packages/react-query-no-core/README.md +++ b/packages/react-query-no-core/README.md @@ -29,3 +29,5 @@ export function App() { ``` The original adapter and both experimental adapters share their TypeScript definitions through `@tanstack/query-types`. Each React adapter owns its provider context and each client owns its caches. + +React batches subscriber updates. Use `notifyManager.setScheduler` to choose when notifications run, or `setNotifyFunction` to wrap them in `act` during tests. To inspect the queries in a `QueriesObserver`, call `observer.getObservers().map((item) => item.getCurrentQuery())`. diff --git a/packages/react-query-no-core/src/HydrationBoundary.tsx b/packages/react-query-no-core/src/HydrationBoundary.tsx index 47f6a0b77f9..d323f68d103 100644 --- a/packages/react-query-no-core/src/HydrationBoundary.tsx +++ b/packages/react-query-no-core/src/HydrationBoundary.tsx @@ -1,13 +1,10 @@ 'use client' import * as React from 'react' import { useQueryClient } from './QueryClientProvider' -import { hydrate } from './runtime' -import type { - DehydratedState, - HydrateOptions, - OmitKeyof, - QueryClient, -} from './runtime' +import { hydrate } from './runtime/hydration' +import type { DehydratedState, OmitKeyof } from '@tanstack/query-types/bindings' +import type { HydrateOptions } from './runtime/hydration' +import type { QueryClient } from './runtime/queryClient' /** * The props accepted by `HydrationBoundary`. diff --git a/packages/react-query-no-core/src/QueryClientProvider.tsx b/packages/react-query-no-core/src/QueryClientProvider.tsx index 8659fa6e346..d1d7b9fc14d 100644 --- a/packages/react-query-no-core/src/QueryClientProvider.tsx +++ b/packages/react-query-no-core/src/QueryClientProvider.tsx @@ -1,6 +1,6 @@ 'use client' import * as React from 'react' -import type { QueryClient } from './runtime' +import type { QueryClient } from './runtime/queryClient' /** * The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it. diff --git a/packages/react-query-no-core/src/errorBoundaryUtils.ts b/packages/react-query-no-core/src/errorBoundaryUtils.ts index f80e52deb03..8ba639b93bc 100644 --- a/packages/react-query-no-core/src/errorBoundaryUtils.ts +++ b/packages/react-query-no-core/src/errorBoundaryUtils.ts @@ -1,14 +1,16 @@ 'use client' import * as React from 'react' -import { shouldThrowError } from './runtime' -import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import { shouldThrowError } from './runtime/utils' import type { - DefaultedQueryObserverOptions, - Query, QueryKey, QueryObserverResult, +} from '@tanstack/query-types/bindings' +import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import type { Query } from './runtime/query' +import type { + DefaultedQueryObserverOptions, ThrowOnError, -} from './runtime' +} from './runtime/types' /** * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`), diff --git a/packages/react-query-no-core/src/index.ts b/packages/react-query-no-core/src/index.ts index ec5aac29a4c..ed1f2e1c562 100644 --- a/packages/react-query-no-core/src/index.ts +++ b/packages/react-query-no-core/src/index.ts @@ -1,8 +1,165 @@ /* istanbul ignore file */ -// Query runtime -// oxlint-disable-next-line tanstack-query/no-restricted-syntax -export * from './runtime' +// Public cache and observer API +export { focusManager } from './runtime/focusManager' +export type { FocusManager } from './runtime/focusManager' +export { environmentManager } from './runtime/environmentManager' +export { + defaultShouldDehydrateMutation, + defaultShouldDehydrateQuery, + dehydrate, + dehydrateQuery, + hydrate, +} from './runtime/hydration' +export { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' +export { MutationCache } from './runtime/mutationCache' +export type { + MutationCacheNotifyEvent, + MutationCacheConfig, +} from './runtime/mutationCache' +export { MutationObserver } from './runtime/mutationObserver' +export { defaultScheduler, notifyManager } from './runtime/notifyManager' +export { onlineManager } from './runtime/onlineManager' +export type { OnlineManager } from './runtime/onlineManager' +export { QueriesObserver } from './runtime/queriesObserver' +export { QueryCache } from './runtime/queryCache' +export type { + QueryCacheNotifyEvent, + QueryCacheConfig, +} from './runtime/queryCache' +export { QueryClient } from './runtime/queryClient' +export type { QueryRuntime } from './runtime/runtimeBinding' +export { QueryObserver } from './runtime/queryObserver' +export type { + QueryObserverResultReader, + ManagedTimerId, + TimeoutCallback, + TimeoutProvider, + DefaultQueryFn, + SkipToken, + Updater, + DehydratedState, + MutationState, + QueriesObserverOptions, + QueriesObserverResultReader, + QueryState, + NonUndefinedGuard, + DistributiveOmit, + OmitKeyof, + Override, + Register, + DefaultError, + QueryKey, + 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, + QueryObserverResult, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverPendingResult, + InfiniteQueryObserverLoadingResult, + InfiniteQueryObserverLoadingErrorResult, + InfiniteQueryObserverRefetchErrorResult, + InfiniteQueryObserverSuccessResult, + InfiniteQueryObserverPlaceholderResult, + DefinedInfiniteQueryObserverResult, + InfiniteQueryObserverResult, + MutationKey, + MutationStatus, + MutationScope, + MutationMeta, + CancelOptions, + SetDataOptions, + NotifyEventType, + NotifyEvent, +} from '@tanstack/query-types/bindings' +export { CancelledError } from './runtime/retryer' +export { timeoutManager } from './runtime/timeoutManager' +export type { TimeoutManager } from './runtime/timeoutManager' +export { + hashKey, + keepPreviousData, + matchMutation, + matchQuery, + noop, + partialMatchKey, + replaceEqualDeep, + shouldThrowError, + defaultQueryFn, + skipToken, +} from './runtime/utils' +export type { MutationFilters, QueryFilters } from './runtime/utils' +export { streamedQuery } from './runtime/streamedQuery' +export type { DehydrateOptions, HydrateOptions } from './runtime/hydration' +export { Mutation } from './runtime/mutation' +export { Query } from './runtime/query' +export { dataTagSymbol, dataTagErrorSymbol, unsetMarker } from './runtime/types' +export type { + QueryFunction, + StaleTimeFunction, + QueryBooleanOption, + QueryPersister, + QueryFunctionContext, + PlaceholderDataFunction, + QueryOptions, + ThrowOnError, + QueryObserverOptions, + DefaultedQueryObserverOptions, + InfiniteQueryObserverOptions, + DefaultedInfiniteQueryObserverOptions, + QueryExecuteOptions, + InfiniteQueryExecuteOptions, + InvalidateQueryFilters, + RefetchQueryFilters, + MutationFunctionContext, + MutationFunction, + MutationOptions, + MutationObserverOptions, + MutateOptions, + MutateFunctionRest, + MutateFunction, + MutationObserverBaseResult, + MutationObserverIdleResult, + MutationObserverLoadingResult, + MutationObserverErrorResult, + MutationObserverSuccessResult, + MutationObserverResult, + QueryClientConfig, + DefaultOptions, +} from './runtime/types' // React Query export type { diff --git a/packages/react-query-no-core/src/infiniteQueryOptions.ts b/packages/react-query-no-core/src/infiniteQueryOptions.ts index fa952f52158..9ecbe9cb090 100644 --- a/packages/react-query-no-core/src/infiniteQueryOptions.ts +++ b/packages/react-query-no-core/src/infiniteQueryOptions.ts @@ -8,7 +8,7 @@ import type { QueryKey, QueryKeyWithDataTag, SkipToken, -} from './runtime' +} from '@tanstack/query-types/bindings' import type { UseInfiniteQueryOptions } from './types' /** diff --git a/packages/react-query-no-core/src/mutationOptions.ts b/packages/react-query-no-core/src/mutationOptions.ts index 37e9c00c925..a126abd7e93 100644 --- a/packages/react-query-no-core/src/mutationOptions.ts +++ b/packages/react-query-no-core/src/mutationOptions.ts @@ -1,5 +1,5 @@ import { identity } from './runtime/identity' -import type { DefaultError, WithRequired } from './runtime' +import type { DefaultError, WithRequired } from '@tanstack/query-types/bindings' import type { UseMutationOptions } from './types' type MutationOptionsFn = { diff --git a/packages/react-query-no-core/src/queryOptions.ts b/packages/react-query-no-core/src/queryOptions.ts index 12cbeb14669..2290631e0dc 100644 --- a/packages/react-query-no-core/src/queryOptions.ts +++ b/packages/react-query-no-core/src/queryOptions.ts @@ -5,11 +5,11 @@ import type { InitialDataFunction, NonUndefinedGuard, OmitKeyof, - QueryFunction, QueryKey, QueryKeyWithDataTag, SkipToken, -} from './runtime' +} from '@tanstack/query-types/bindings' +import type { QueryFunction } from './runtime/types' import type { UseQueryOptions } from './types' /** diff --git a/packages/react-query-no-core/src/runtime/index.ts b/packages/react-query-no-core/src/runtime/index.ts deleted file mode 100644 index bb8a1374dc2..00000000000 --- a/packages/react-query-no-core/src/runtime/index.ts +++ /dev/null @@ -1,168 +0,0 @@ -/* istanbul ignore file */ - -export { focusManager } from './focusManager' -export type { FocusManager } from './focusManager' -export { environmentManager } from './environmentManager' -export { - defaultShouldDehydrateMutation, - defaultShouldDehydrateQuery, - dehydrate, - dehydrateQuery, - hydrate, -} from './hydration' -export { InfiniteQueryObserver } from './infiniteQueryObserver' -export { MutationCache } from './mutationCache' -export type { MutationCacheNotifyEvent } from './mutationCache' -export { MutationObserver } from './mutationObserver' -export { defaultScheduler, notifyManager } from './notifyManager' -export { onlineManager } from './onlineManager' -export type { OnlineManager } from './onlineManager' -export { QueriesObserver } from './queriesObserver' -export { QueryCache } from './queryCache' -export type { QueryCacheNotifyEvent } from './queryCache' -export { QueryClient } from './queryClient' -export type { QueryRuntime } from './runtimeBinding' -export { QueryObserver } from './queryObserver' -export type { QueryObserverResultReader } from './queryObserver' -export { CancelledError } from './retryer' -export { - timeoutManager, - type ManagedTimerId, - type TimeoutCallback, - type TimeoutManager, - type TimeoutProvider, -} from './timeoutManager' -export { - hashKey, - keepPreviousData, - matchMutation, - matchQuery, - noop, - partialMatchKey, - replaceEqualDeep, - shouldThrowError, - defaultQueryFn, - skipToken, -} from './utils' -export type { - DefaultQueryFn, - MutationFilters, - QueryFilters, - SkipToken, - Updater, -} from './utils' - -export { streamedQuery } from './streamedQuery' - -// Types -export type { - DehydratedState, - DehydrateOptions, - HydrateOptions, -} from './hydration' -export { Mutation } from './mutation' -export type { MutationState } from './mutation' -export type { MutationCacheConfig } from './mutationCache' -export type { - QueriesObserverOptions, - QueriesObserverResultReader, -} from './queriesObserver' -export { Query } from './query' -export type { QueryState } from './query' -export type { QueryCacheConfig } from './queryCache' -export { dataTagSymbol, dataTagErrorSymbol, unsetMarker } from './types' -export type { - NonUndefinedGuard, - DistributiveOmit, - OmitKeyof, - Override, - Register, - DefaultError, - QueryKey, - UnsetMarker, - AnyDataTag, - DataTag, - QueryKeyWithDataTag, - InferDataFromTag, - InferErrorFromTag, - QueryFunction, - StaleTime, - StaleTimeFunction, - QueryBooleanOption, - QueryPersister, - QueryFunctionContext, - InitialDataFunction, - PlaceholderDataFunction, - QueriesPlaceholderDataFunction, - EqualityFn, - CacheKeyHashFunction, - CacheKeyConfig, - GetPreviousPageParamFunction, - GetNextPageParamFunction, - InfiniteData, - QueryMeta, - NetworkMode, - NotifyOnChangeProps, - QueryOptions, - InitialPageParam, - InfiniteQueryPageParamsOptions, - ThrowOnError, - QueryObserverOptions, - WithRequired, - DefaultedQueryObserverOptions, - InfiniteQueryObserverOptions, - DefaultedInfiniteQueryObserverOptions, - QueryExecuteOptions, - InfiniteQueryExecuteOptions, - ResultOptions, - RefetchOptions, - InvalidateQueryFilters, - RefetchQueryFilters, - InvalidateOptions, - ResetOptions, - FetchNextPageOptions, - FetchPreviousPageOptions, - QueryStatus, - FetchStatus, - QueryObserverBaseResult, - QueryObserverPendingResult, - QueryObserverLoadingResult, - QueryObserverLoadingErrorResult, - QueryObserverRefetchErrorResult, - QueryObserverSuccessResult, - QueryObserverPlaceholderResult, - DefinedQueryObserverResult, - QueryObserverResult, - InfiniteQueryObserverBaseResult, - InfiniteQueryObserverPendingResult, - InfiniteQueryObserverLoadingResult, - InfiniteQueryObserverLoadingErrorResult, - InfiniteQueryObserverRefetchErrorResult, - InfiniteQueryObserverSuccessResult, - InfiniteQueryObserverPlaceholderResult, - DefinedInfiniteQueryObserverResult, - InfiniteQueryObserverResult, - MutationKey, - MutationStatus, - MutationScope, - MutationMeta, - MutationFunctionContext, - MutationFunction, - MutationOptions, - MutationObserverOptions, - MutateOptions, - MutateFunctionRest, - MutateFunction, - MutationObserverBaseResult, - MutationObserverIdleResult, - MutationObserverLoadingResult, - MutationObserverErrorResult, - MutationObserverSuccessResult, - MutationObserverResult, - QueryClientConfig, - DefaultOptions, - CancelOptions, - SetDataOptions, - NotifyEventType, - NotifyEvent, -} from './types' diff --git a/packages/react-query-no-core/src/runtime/notifyManager.ts b/packages/react-query-no-core/src/runtime/notifyManager.ts index ce3f61244ee..5886781bde9 100644 --- a/packages/react-query-no-core/src/runtime/notifyManager.ts +++ b/packages/react-query-no-core/src/runtime/notifyManager.ts @@ -1,6 +1,5 @@ import type { BatchCallsCallback, - BatchNotifyFunction, NotifyCallback, NotifyFunction, ScheduleFunction, @@ -23,9 +22,6 @@ export function createNotifyManager() { let notifyFn: NotifyFunction = (callback) => { callback() } - let batchNotifyFn: BatchNotifyFunction = (callback: () => void) => { - callback() - } let scheduleFn = defaultScheduler const schedule = (callback: NotifyCallback): void => { @@ -42,10 +38,8 @@ export function createNotifyManager() { queue = [] if (originalQueue.length) { scheduleFn(() => { - batchNotifyFn(() => { - originalQueue.forEach((callback) => { - notifyFn(callback) - }) + originalQueue.forEach((callback) => { + notifyFn(callback) }) }) } @@ -100,22 +94,6 @@ export function createNotifyManager() { setNotifyFunction: (fn: NotifyFunction) => { notifyFn = fn }, - /** - * Use this method to set a custom function to batch notifications together into a single tick. - * Framework adapters use this to plug in their own batching primitive, so that a single query - * update only triggers one re-render instead of one per subscriber. - * @param fn - Receives a function that runs a batch of notifications and must call it. - * @example - * ```ts - * import { notifyManager } from '@tanstack/react-query-no-core' - * import { batch } from 'solid-js' - * - * notifyManager.setBatchNotifyFunction(batch) - * ``` - */ - setBatchNotifyFunction: (fn: BatchNotifyFunction) => { - batchNotifyFn = fn - }, /** * Configures a custom callback that schedules when the next batch runs. * The default behavior is `queueMicrotask(callback)`. diff --git a/packages/react-query-no-core/src/runtime/queriesObserver.ts b/packages/react-query-no-core/src/runtime/queriesObserver.ts index 1a9392c5ca5..2b91a71a5d8 100644 --- a/packages/react-query-no-core/src/runtime/queriesObserver.ts +++ b/packages/react-query-no-core/src/runtime/queriesObserver.ts @@ -226,15 +226,6 @@ export class QueriesObserver< return this.#result } - /** - * Returns the underlying `Query` instances currently being observed, in - * the same order as the queries passed to the constructor or `setQueries`. - * @returns The observed queries. - */ - getQueries() { - return this.#observers.map((observer) => observer.getCurrentQuery()) - } - /** * Returns the underlying `QueryObserver` instances this observer manages, * in the same order as the queries passed to the constructor or diff --git a/packages/react-query-no-core/src/runtime/queryObserver.ts b/packages/react-query-no-core/src/runtime/queryObserver.ts index 6973a997b58..b36532fa9fb 100644 --- a/packages/react-query-no-core/src/runtime/queryObserver.ts +++ b/packages/react-query-no-core/src/runtime/queryObserver.ts @@ -404,9 +404,9 @@ export class QueryObserver< /** * Records that the given `QueryObserverResult` property was read, so a subsequent update only - * notifies this observer if a tracked property actually changed. Normally called indirectly via - * {@link QueryObserver#trackResult}'s proxy; exposed directly for adapters that track property - * access themselves (e.g. through their own reactivity system) instead of via the proxy. + * notifies this observer if a tracked property actually changed. The proxy returned by + * {@link QueryObserver#trackResult} records reads on this observer. For `useQueries`, + * `QueriesObserver` records the same read on every observer in the group. * @param key - The name of the property that was read. */ trackProp(key: keyof QueryObserverResult) { diff --git a/packages/react-query-no-core/src/suspense.ts b/packages/react-query-no-core/src/suspense.ts index f903592ec0a..09ff0957953 100644 --- a/packages/react-query-no-core/src/suspense.ts +++ b/packages/react-query-no-core/src/suspense.ts @@ -1,14 +1,14 @@ import { use } from 'react' -import { QueryObserver } from './runtime' -import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import { QueryObserver } from './runtime/queryObserver' import type { DefaultError, - DefaultedQueryObserverOptions, - Query, - QueryClient, QueryKey, QueryObserverResult, -} from './runtime' +} from '@tanstack/query-types/bindings' +import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import type { Query } from './runtime/query' +import type { QueryClient } from './runtime/queryClient' +import type { DefaultedQueryObserverOptions } from './runtime/types' type SuspensePromiseEntry = { fetchPromise: Promise diff --git a/packages/react-query-no-core/src/types.ts b/packages/react-query-no-core/src/types.ts index 3304cd4691d..de88256c368 100644 --- a/packages/react-query-no-core/src/types.ts +++ b/packages/react-query-no-core/src/types.ts @@ -6,22 +6,24 @@ import type { DefinedQueryObserverResult, DistributiveOmit, InfiniteData, - InfiniteQueryExecuteOptions, - InfiniteQueryObserverOptions, InfiniteQueryObserverPlaceholderResult, InfiniteQueryObserverResult, - MutateFunction, - MutationObserverOptions, - MutationObserverResult, OmitKeyof, Override, - QueryExecuteOptions, QueryKey, - QueryObserverOptions, QueryObserverPlaceholderResult, QueryObserverResult, SkipToken, -} from './runtime' +} from '@tanstack/query-types/bindings' +import type { + InfiniteQueryExecuteOptions, + InfiniteQueryObserverOptions, + MutateFunction, + MutationObserverOptions, + MutationObserverResult, + QueryExecuteOptions, + QueryObserverOptions, +} from './runtime/types' /** * {@link UseBaseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't diff --git a/packages/react-query-no-core/src/useBaseQuery.ts b/packages/react-query-no-core/src/useBaseQuery.ts index 052bd5bb8b5..7216bf66c41 100644 --- a/packages/react-query-no-core/src/useBaseQuery.ts +++ b/packages/react-query-no-core/src/useBaseQuery.ts @@ -10,11 +10,11 @@ import { } from './errorBoundaryUtils' import { useObserverSnapshot } from './useObserverSnapshot' import type { - QueryClient, QueryKey, - QueryObserver, QueryObserverResult, -} from './runtime' +} from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' +import type { QueryObserver } from './runtime/queryObserver' import type { suspenseQueryPolicy } from './suspense' import type { UseBaseQueryOptions } from './types' diff --git a/packages/react-query-no-core/src/useInfiniteQuery.ts b/packages/react-query-no-core/src/useInfiniteQuery.ts index 6ab4fde4fb3..356af76465e 100644 --- a/packages/react-query-no-core/src/useInfiniteQuery.ts +++ b/packages/react-query-no-core/src/useInfiniteQuery.ts @@ -1,17 +1,17 @@ 'use client' -import { InfiniteQueryObserver } from './runtime' +import { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' import { useBaseQuery } from './useBaseQuery' -import type { - DefinedInitialDataInfiniteOptions, - UndefinedInitialDataInfiniteOptions, -} from './infiniteQueryOptions' import type { DefaultError, InfiniteData, - QueryClient, QueryKey, - QueryObserver, -} from './runtime' +} from '@tanstack/query-types/bindings' +import type { + DefinedInitialDataInfiniteOptions, + UndefinedInitialDataInfiniteOptions, +} from './infiniteQueryOptions' +import type { QueryClient } from './runtime/queryClient' +import type { QueryObserver } from './runtime/queryObserver' import type { DefinedUseInfiniteQueryResult, UseInfiniteQueryOptions, diff --git a/packages/react-query-no-core/src/useIsFetching.ts b/packages/react-query-no-core/src/useIsFetching.ts index db39fc9ab5a..f80652f8b2e 100644 --- a/packages/react-query-no-core/src/useIsFetching.ts +++ b/packages/react-query-no-core/src/useIsFetching.ts @@ -1,8 +1,9 @@ 'use client' import * as React from 'react' import { useQueryClient } from './QueryClientProvider' -import { notifyManager } from './runtime' -import type { QueryClient, QueryFilters } from './runtime' +import { notifyManager } from './runtime/notifyManager' +import type { QueryClient } from './runtime/queryClient' +import type { QueryFilters } from './runtime/utils' /** * The `useIsFetching` hook returns the `number` of the queries that your application is loading or fetching in diff --git a/packages/react-query-no-core/src/useMutation.ts b/packages/react-query-no-core/src/useMutation.ts index e0f6adfe1bd..e14c686c472 100644 --- a/packages/react-query-no-core/src/useMutation.ts +++ b/packages/react-query-no-core/src/useMutation.ts @@ -1,13 +1,11 @@ 'use client' import * as React from 'react' import { useQueryClient } from './QueryClientProvider' -import { - MutationObserver, - noop, - notifyManager, - shouldThrowError, -} from './runtime' -import type { DefaultError, QueryClient } from './runtime' +import { MutationObserver } from './runtime/mutationObserver' +import { notifyManager } from './runtime/notifyManager' +import { noop, shouldThrowError } from './runtime/utils' +import type { DefaultError } from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' import type { UseMutateFunction, UseMutationOptions, diff --git a/packages/react-query-no-core/src/useMutationState.ts b/packages/react-query-no-core/src/useMutationState.ts index 16851724d31..07a2523779c 100644 --- a/packages/react-query-no-core/src/useMutationState.ts +++ b/packages/react-query-no-core/src/useMutationState.ts @@ -1,14 +1,13 @@ 'use client' import * as React from 'react' import { useQueryClient } from './QueryClientProvider' -import { notifyManager, replaceEqualDeep } from './runtime' -import type { - Mutation, - MutationCache, - MutationFilters, - MutationState, - QueryClient, -} from './runtime' +import { notifyManager } from './runtime/notifyManager' +import { replaceEqualDeep } from './runtime/utils' +import type { MutationState } from '@tanstack/query-types/bindings' +import type { Mutation } from './runtime/mutation' +import type { MutationCache } from './runtime/mutationCache' +import type { QueryClient } from './runtime/queryClient' +import type { MutationFilters } from './runtime/utils' /** * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending` diff --git a/packages/react-query-no-core/src/usePrefetchInfiniteQuery.tsx b/packages/react-query-no-core/src/usePrefetchInfiniteQuery.tsx index 666ebf60f2d..04d1db27fbe 100644 --- a/packages/react-query-no-core/src/usePrefetchInfiniteQuery.tsx +++ b/packages/react-query-no-core/src/usePrefetchInfiniteQuery.tsx @@ -1,11 +1,11 @@ import { useQueryClient } from './QueryClientProvider' -import { noop } from './runtime' +import { noop } from './runtime/utils' import type { DefaultError, InfiniteData, - QueryClient, QueryKey, -} from './runtime' +} from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' import type { UsePrefetchInfiniteQueryOptions } from './types' /** diff --git a/packages/react-query-no-core/src/usePrefetchQuery.tsx b/packages/react-query-no-core/src/usePrefetchQuery.tsx index 8b5971d51de..7d98c66fc34 100644 --- a/packages/react-query-no-core/src/usePrefetchQuery.tsx +++ b/packages/react-query-no-core/src/usePrefetchQuery.tsx @@ -1,6 +1,7 @@ import { useQueryClient } from './QueryClientProvider' -import { noop } from './runtime' -import type { DefaultError, QueryClient, QueryKey } from './runtime' +import { noop } from './runtime/utils' +import type { DefaultError, QueryKey } from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' import type { UsePrefetchQueryOptions } from './types' /** diff --git a/packages/react-query-no-core/src/useQueries.ts b/packages/react-query-no-core/src/useQueries.ts index b855434a110..b642c72e1b6 100644 --- a/packages/react-query-no-core/src/useQueries.ts +++ b/packages/react-query-no-core/src/useQueries.ts @@ -15,12 +15,14 @@ import type { OmitKeyof, QueriesObserverOptions, QueriesPlaceholderDataFunction, - QueryClient, - QueryFunction, QueryKey, +} from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' +import type { + QueryFunction, QueryObserverOptions, ThrowOnError, -} from './runtime' +} from './runtime/types' import type { suspenseQueriesPolicy } from './suspense' import type { DefinedUseQueryResult, diff --git a/packages/react-query-no-core/src/useQuery.ts b/packages/react-query-no-core/src/useQuery.ts index 445cc456f59..fadc6d866dc 100644 --- a/packages/react-query-no-core/src/useQuery.ts +++ b/packages/react-query-no-core/src/useQuery.ts @@ -1,11 +1,12 @@ 'use client' -import { QueryObserver } from './runtime' +import { QueryObserver } from './runtime/queryObserver' import { useBaseQuery } from './useBaseQuery' +import type { DefaultError, QueryKey } from '@tanstack/query-types/bindings' import type { DefinedInitialDataOptions, UndefinedInitialDataOptions, } from './queryOptions' -import type { DefaultError, QueryClient, QueryKey } from './runtime' +import type { QueryClient } from './runtime/queryClient' import type { DefinedUseQueryResult, UseQueryOptions, diff --git a/packages/react-query-no-core/src/useSuspenseInfiniteQuery.ts b/packages/react-query-no-core/src/useSuspenseInfiniteQuery.ts index 1c904b86c77..4b73c02c92a 100644 --- a/packages/react-query-no-core/src/useSuspenseInfiniteQuery.ts +++ b/packages/react-query-no-core/src/useSuspenseInfiniteQuery.ts @@ -1,15 +1,16 @@ 'use client' -import { InfiniteQueryObserver, skipToken } from './runtime' +import { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' +import { skipToken } from './runtime/utils' import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' import { useBaseQuery } from './useBaseQuery' import type { DefaultError, InfiniteData, OmitKeyof, - QueryClient, QueryKey, - QueryObserver, -} from './runtime' +} from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' +import type { QueryObserver } from './runtime/queryObserver' import type { UseInfiniteQueryOptions, UseInfiniteQueryResult, diff --git a/packages/react-query-no-core/src/useSuspenseQueries.ts b/packages/react-query-no-core/src/useSuspenseQueries.ts index 4d655752ef7..75f72b38067 100644 --- a/packages/react-query-no-core/src/useSuspenseQueries.ts +++ b/packages/react-query-no-core/src/useSuspenseQueries.ts @@ -1,16 +1,15 @@ 'use client' -import { skipToken } from './runtime' +import { skipToken } from './runtime/utils' import { defaultThrowOnError, suspenseQueriesPolicy } from './suspense' import { useBaseQueries } from './useQueries' import type { DefaultError, OmitKeyof, QueriesPlaceholderDataFunction, - QueryClient, - QueryFunction, QueryKey, - ThrowOnError, -} from './runtime' +} from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' +import type { QueryFunction, ThrowOnError } from './runtime/types' import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types' // `placeholderData` functions in useQueries never receive previous query data. diff --git a/packages/react-query-no-core/src/useSuspenseQuery.ts b/packages/react-query-no-core/src/useSuspenseQuery.ts index 2a65d67ca5a..45d54de3130 100644 --- a/packages/react-query-no-core/src/useSuspenseQuery.ts +++ b/packages/react-query-no-core/src/useSuspenseQuery.ts @@ -1,8 +1,14 @@ 'use client' -import { QueryObserver, skipToken } from './runtime' +import { QueryObserver } from './runtime/queryObserver' +import { skipToken } from './runtime/utils' import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' import { useBaseQuery } from './useBaseQuery' -import type { DefaultError, OmitKeyof, QueryClient, QueryKey } from './runtime' +import type { + DefaultError, + OmitKeyof, + QueryKey, +} from '@tanstack/query-types/bindings' +import type { QueryClient } from './runtime/queryClient' import type { UseQueryOptions, UseQueryResult, diff --git a/scripts/react-query-compat.config.ts b/scripts/react-query-compat.config.ts index 3769c750592..dfaf8263193 100644 --- a/scripts/react-query-compat.config.ts +++ b/scripts/react-query-compat.config.ts @@ -14,7 +14,7 @@ export default defineConfig({ resolve: { ...base.resolve, alias: { - '@tanstack/query-core': join(adapter, 'src/runtime/index.ts'), + '@tanstack/query-core': join(adapter, 'src/index.ts'), ...(basename(adapter) === 'react-query-no-core-pluggable' && { '@tanstack/query-test-utils/polling': join( adapter, diff --git a/scripts/test-react-query-compat.mjs b/scripts/test-react-query-compat.mjs index c6e76d55cab..c180baa2ea6 100644 --- a/scripts/test-react-query-compat.mjs +++ b/scripts/test-react-query-compat.mjs @@ -15,7 +15,7 @@ import { basename, join, relative, resolve, sep } from 'node:path' const adapter = process.cwd() const repository = resolve(import.meta.dirname, '..') const require = createRequire(import.meta.url) -const core = join(adapter, 'src/runtime/index.ts') +const entry = join(adapter, 'src/index.ts') const pluggable = basename(adapter) === 'react-query-no-core-pluggable' function importPath(from, to) { return './' + relative(from, to).split(sep).join('/') @@ -34,6 +34,9 @@ for (const suite of ['query-core', 'react-query']) { : join(adapter, 'src') cpSync(join(upstream, 'src/__tests__'), join(source, '__tests__'), { recursive: true, + // Only query-core exposes the extension points for non-React adapters. + filter: (path) => + suite !== 'query-core' || basename(path) !== 'frameworkAdapters', }) for (const file of readdirSync(implementation, { withFileTypes: true })) { @@ -41,6 +44,13 @@ for (const suite of ['query-core', 'react-query']) { const target = importPath(source, join(implementation, file.name)) writeFileSync(join(source, file.name), `export * from '${target}'\n`) } + if (suite === 'query-core') { + // Upstream tests use ".." for the public package and "../foo" for internals. + writeFileSync( + join(source, 'index.ts'), + `export * from '${importPath(source, entry)}'\n`, + ) + } const setup = join(repository, 'packages/react-query/test-setup.ts') const tsconfig = { @@ -52,7 +62,7 @@ for (const suite of ['query-core', 'react-query']) { emitDeclarationOnly: false, noEmit: true, paths: { - '@tanstack/query-core': [core], + '@tanstack/query-core': [entry], ...(pluggable && { '@tanstack/query-test-utils/polling': [ join(adapter, 'tests/compat-polling.ts'), From 6cf36e646aa229849762dc115289063b86800b24 Mon Sep 17 00:00:00 2001 From: Jonghyeon Ko Date: Fri, 27 Nov 2026 20:04:40 +0900 Subject: [PATCH 06/11] test(react-query): measure production bundles against the unchanged PR base --- .github/workflows/react-query-bundle-size.yml | 18 +++- integrations/react/bundle-size/README.md | 13 ++- integrations/react/bundle-size/measure.mjs | 96 ++++++++++++++++--- 3 files changed, 109 insertions(+), 18 deletions(-) diff --git a/.github/workflows/react-query-bundle-size.yml b/.github/workflows/react-query-bundle-size.yml index 5178d7f0f74..176304febec 100644 --- a/.github/workflows/react-query-bundle-size.yml +++ b/.github/workflows/react-query-bundle-size.yml @@ -34,10 +34,23 @@ jobs: 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: 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 @@ -61,7 +74,6 @@ jobs: GH_TOKEN: ${{ github.token }} REPO: ${{ github.repository }} PR_NUMBER: ${{ github.event.number }} - HEAD_SHA: ${{ github.event.pull_request.head.sha }} REPORT: ${{ needs.measure.outputs.report }} run: | comments="repos/$REPO/issues/$PR_NUMBER/comments" @@ -74,6 +86,6 @@ jobs: endpoint="repos/$REPO/issues/comments/$id" method=PATCH fi - jq -n --arg marker "$marker" --arg sha "$HEAD_SHA" --argjson report "$REPORT" \ - '{body: ($marker + "\n" + $report + "\nMeasured commit `" + $sha + "`.")}' | + jq -n --arg marker "$marker" --argjson report "$REPORT" \ + '{body: ($marker + "\n" + $report)}' | gh api --silent --method "$method" "$endpoint" --input - diff --git a/integrations/react/bundle-size/README.md b/integrations/react/bundle-size/README.md index 8a2e64d190f..df48ad318ee 100644 --- a/integrations/react/bundle-size/README.md +++ b/integrations/react/bundle-size/README.md @@ -2,13 +2,24 @@ This workspace builds three browser apps against each adapter’s public package entry point. The read-only app fetches a book list. 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 all four regular and suspense query hooks. All builds include React and React DOM and use the default client. The original and standalone adapters accept a numeric interval. The pluggable adapter imports its interval scheduler through the `refetchInterval` option helper. The benchmark checks that only the polling build of that adapter includes the scheduler. -Run from the repository root after installing the workspace dependencies: +CI builds the original adapter and its dependencies from the PR's base commit. The two alternatives, the app code, the bundler and both React packages come from the PR head. The report records both commit IDs. + +For a comparison within the current checkout, run from the repository root after installing workspace dependencies: ```sh pnpm --filter '@tanstack/query-integration-react-bundle-size^...' run build pnpm --filter @tanstack/query-integration-react-bundle-size run measure ``` +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 +``` + The report at `integrations/react/bundle-size/dist/report.md` shows total emitted JavaScript bytes and the sum of individually compressed chunks for gzip and Brotli. Each percentage uses the original adapter’s application size for that workload as its denominator. Serve a directory under `dist//` to try the built app. Run the nine production app scenarios in Chromium after measuring: diff --git a/integrations/react/bundle-size/measure.mjs b/integrations/react/bundle-size/measure.mjs index c26da85e569..c1672e35d8a 100644 --- a/integrations/react/bundle-size/measure.mjs +++ b/integrations/react/bundle-size/measure.mjs @@ -1,9 +1,15 @@ -import { readFile, writeFile } from 'node:fs/promises' +import { execFileSync } from 'node:child_process' +import { readFile, realpath, writeFile } from 'node:fs/promises' import path from 'node:path' import { brotliCompressSync, constants, gzipSync } from 'node:zlib' -import { build } from 'vite' +import { build, normalizePath } from 'vite' const root = import.meta.dirname +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-no-core-pluggable' const packages = [baseline, '@tanstack/react-query-no-core', pluggable] @@ -20,6 +26,11 @@ const workloads = [ }, ] +const excludedFromStandaloneApps = [ + /\/(?:packages|node_modules\/@tanstack)\/(?:query-core|(?:angular|lit|preact|solid|svelte|vue)-query[^/]*)\//, + /\/node_modules\/(?:@angular|@lit|@vue|lit|lit-element|lit-html|preact|solid-js|svelte|vue)\//, +] + async function measure(packageName, screen) { const outDir = path.join(root, 'dist', screen, packageName.split('/')[1]) const result = await build({ @@ -28,9 +39,24 @@ async function measure(packageName, screen) { configFile: false, mode: 'production', logLevel: 'warn', + plugins: [ + { + 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: { - '#adapter': packageName, '#polling-option': path.join( root, 'src', @@ -58,6 +84,15 @@ async function measure(packageName, screen) { .filter(([, module]) => module.renderedLength > 0) .map(([id]) => id), ) + if ( + packageName === baseline && + basePackage && + !modules.some((id) => id.startsWith(normalizePath(basePackage) + '/build/')) + ) { + throw new Error( + `Missing built @tanstack/react-query from base checkout ${basePackage}`, + ) + } if ( modules.some((id) => /\/(?:packages|node_modules\/@tanstack)\/query-types\//.test(id), @@ -67,13 +102,24 @@ async function measure(packageName, screen) { `${packageName} shipped runtime code from @tanstack/query-types`, ) } - if ( - packageName !== baseline && - modules.some((id) => - /\/(?:packages|node_modules\/@tanstack)\/query-core\//.test(id), + if (packageName !== baseline) { + const foreignRuntime = modules.find((id) => + excludedFromStandaloneApps.some((pattern) => pattern.test(id)), ) - ) { - throw new Error(`${packageName} bundled @tanstack/query-core`) + 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')), + ) + ) { + throw new Error( + `${packageName} included an internal runtime barrel in the app`, + ) + } } if (packageName === pluggable) { const includesPolling = modules.some((id) => @@ -108,11 +154,23 @@ function formatSize(bytes, baselineBytes, isBaseline) { return `${size} (${sign}${integer.format(difference)} B, ${sign}${percent}%)` } -// These public typing helpers share one callable in each standalone ESM package. +// Inspect the published ESM entry points as a consumer would. for (const name of packages.filter((name) => name !== baseline)) { - const { queryOptions, mutationOptions, infiniteQueryOptions } = await import( - name - ) + const { + queryOptions, + mutationOptions, + infiniteQueryOptions, + QueriesObserver, + notifyManager, + } = await import(name) + if ( + 'getQueries' in QueriesObserver.prototype || + 'setBatchNotifyFunction' in notifyManager + ) { + throw new Error( + `${name} exposed another adapter's observer or batch notification API`, + ) + } if ( typeof queryOptions !== 'function' || queryOptions !== mutationOptions || @@ -124,10 +182,20 @@ for (const name of packages.filter((name) => name !== baseline)) { } } +function revision(directory) { + 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 app bundle size', '', - 'Each row includes React, React DOM and the same production Vite app. Changes are relative to `@tanstack/react-query` in the same workload and commit. A negative change is a saving.', + `Baseline adapter at \`${base}\` (${baseCheckout ? 'base checkout' : 'current checkout'}). Alternatives and fixture at \`${head}\`.`, + '', + 'Each row includes the same React, React DOM and production Vite app. Changes are relative to the baseline for that workload. A negative change is a saving.', ] for (const { screen, title } of workloads) { lines.push( From 4954cd3b29d2dd6e4e0180e9dc6011f77d59ba74 Mon Sep 17 00:00:00 2001 From: Jonghyeon Ko Date: Fri, 27 Nov 2026 20:10:04 +0900 Subject: [PATCH 07/11] test(react-query): align compatibility suites with the merged v6 runtime --- .../__tests__/infiniteQueryObserver.test.tsx | 3 +- .../src/__tests__/queryClient.test-d.tsx | 3 +- .../src/__tests__/timeoutManager.test.tsx | 19 +--------- .../query-core/src/__tests__/utils.test-d.tsx | 3 +- .../src/runtime/types.ts | 35 ------------------- .../react-query-no-core/src/runtime/types.ts | 35 ------------------- 6 files changed, 4 insertions(+), 94 deletions(-) diff --git a/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx b/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx index 4deb4606da7..1b4c53f2c6c 100644 --- a/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx +++ b/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx @@ -1,10 +1,9 @@ import { createKey, sleep } from '@tanstack/query-test-utils' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { InfiniteQueryObserver, QueryClient } from '..' +import type { GetNextPageParamFunction, GetPreviousPageParamFunction } from '..' import type { DefaultedInfiniteQueryObserverOptions, - GetNextPageParamFunction, - GetPreviousPageParamFunction, InfiniteData, } from '../types' diff --git a/packages/query-core/src/__tests__/queryClient.test-d.tsx b/packages/query-core/src/__tests__/queryClient.test-d.tsx index 4a8e15d3db1..7b67b229af6 100644 --- a/packages/query-core/src/__tests__/queryClient.test-d.tsx +++ b/packages/query-core/src/__tests__/queryClient.test-d.tsx @@ -1,12 +1,12 @@ import { assertType, describe, expectTypeOf, it } from 'vitest' import { QueryClient } from '../queryClient' import { skipToken } from '../utils' +import type { DataTag, UnsetMarker } from '..' import type { Mutation } from '../mutation' import type { MutationCache } from '../mutationCache' import type { Query, QueryState } from '../query' import type { QueryCache } from '../queryCache' import type { - DataTag, DefaultError, DefaultOptions, DefaultedQueryObserverOptions, @@ -23,7 +23,6 @@ import type { QueryKey, QueryObserverOptionsBase, SetDataOptions, - UnsetMarker, } from '../types' import type { MutationFilters, QueryFilters, Updater } from '../utils' diff --git a/packages/query-core/src/__tests__/timeoutManager.test.tsx b/packages/query-core/src/__tests__/timeoutManager.test.tsx index 288e67cd9e9..2765f4815e5 100644 --- a/packages/query-core/src/__tests__/timeoutManager.test.tsx +++ b/packages/query-core/src/__tests__/timeoutManager.test.tsx @@ -1,9 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - TimeoutManager, - defaultTimeoutProvider, - timeoutManager, -} from '../timeoutManager' +import { TimeoutManager, timeoutManager } from '../timeoutManager' import type { MockInstance } from 'vitest' import type { TimeoutCallback, TimeoutProvider } from '../timeoutManager' @@ -110,17 +106,4 @@ describe('timeoutManager', () => { expect(timeoutManager).toBeInstanceOf(TimeoutManager) }) }) - - describe('exported functions', () => { - let provider: ReturnType - - beforeEach(() => { - provider = createMockProvider() - timeoutManager.setTimeoutProvider(provider) - }) - - afterEach(() => { - timeoutManager.setTimeoutProvider(defaultTimeoutProvider) - }) - }) }) diff --git a/packages/query-core/src/__tests__/utils.test-d.tsx b/packages/query-core/src/__tests__/utils.test-d.tsx index 1faad148309..216ca46492f 100644 --- a/packages/query-core/src/__tests__/utils.test-d.tsx +++ b/packages/query-core/src/__tests__/utils.test-d.tsx @@ -24,12 +24,11 @@ import { sleep, timeUntilStale, } from '../utils' +import type { DataTag, MutationStatus } from '..' import type { Mutation } from '../mutation' import type { Query } from '../query' import type { - DataTag, EqualityFn, - MutationStatus, QueryFunction, QueryKey, QueryOptions, diff --git a/packages/react-query-no-core-pluggable/src/runtime/types.ts b/packages/react-query-no-core-pluggable/src/runtime/types.ts index f0baebff3e3..df37aeba7d3 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/types.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/types.ts @@ -420,66 +420,31 @@ export type DefaultOptions = Shared.DefaultOptions< > export type { - NonUndefinedGuard, - DistributiveOmit, OmitKeyof, - Override, - Register, DefaultError, QueryKey, - 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, QueryObserverResult, InfiniteQueryObserverBaseResult, - InfiniteQueryObserverPendingResult, - InfiniteQueryObserverLoadingResult, - InfiniteQueryObserverLoadingErrorResult, - InfiniteQueryObserverRefetchErrorResult, - InfiniteQueryObserverSuccessResult, - InfiniteQueryObserverPlaceholderResult, - DefinedInfiniteQueryObserverResult, InfiniteQueryObserverResult, MutationKey, - MutationStatus, - MutationScope, MutationMeta, CancelOptions, SetDataOptions, - NotifyEventType, - NotifyEvent, } from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/types.ts b/packages/react-query-no-core/src/runtime/types.ts index f0baebff3e3..df37aeba7d3 100644 --- a/packages/react-query-no-core/src/runtime/types.ts +++ b/packages/react-query-no-core/src/runtime/types.ts @@ -420,66 +420,31 @@ export type DefaultOptions = Shared.DefaultOptions< > export type { - NonUndefinedGuard, - DistributiveOmit, OmitKeyof, - Override, - Register, DefaultError, QueryKey, - 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, QueryObserverResult, InfiniteQueryObserverBaseResult, - InfiniteQueryObserverPendingResult, - InfiniteQueryObserverLoadingResult, - InfiniteQueryObserverLoadingErrorResult, - InfiniteQueryObserverRefetchErrorResult, - InfiniteQueryObserverSuccessResult, - InfiniteQueryObserverPlaceholderResult, - DefinedInfiniteQueryObserverResult, InfiniteQueryObserverResult, MutationKey, - MutationStatus, - MutationScope, MutationMeta, CancelOptions, SetDataOptions, - NotifyEventType, - NotifyEvent, } from '@tanstack/query-types/bindings' From 15e9d5438fe67d3eb83e120bf42963291f829700 Mon Sep 17 00:00:00 2001 From: Jonghyeon Ko Date: Fri, 27 Nov 2026 22:06:35 +0900 Subject: [PATCH 08/11] feat(react-query): tree-shake optional observer and cache behavior --- .changeset/react-query-standalone-adapters.md | 2 +- integrations/react/bundle-size/README.md | 4 +- .../react/bundle-size/browser/apps.test.js | 41 ++ integrations/react/bundle-size/measure.mjs | 105 +++++- .../react/bundle-size/src/options.jsx | 67 ++++ .../bundle-size/src/pluggable-options.js | 12 + .../react/bundle-size/src/v6-options.js | 5 + knip.config.ts | 2 +- nx.json | 1 + .../src/__tests__/hydration.test.tsx | 26 +- .../query-core/src/__tests__/infiniteFetch.ts | 13 + .../__tests__/infiniteQueryBehavior.test.tsx | 13 +- .../infiniteQueryObserver.test-d.tsx | 12 +- .../__tests__/infiniteQueryObserver.test.tsx | 8 +- .../src/__tests__/mutation.test-d.tsx | 3 +- .../src/__tests__/mutation.test.tsx | 57 +-- .../src/__tests__/mutationCache.test.tsx | 7 +- .../src/__tests__/queriesObserver.test-d.tsx | 3 +- .../src/__tests__/queriesObserver.test.tsx | 37 +- .../query-core/src/__tests__/query.test.tsx | 20 +- .../src/__tests__/queryCache.test.tsx | 3 +- .../src/__tests__/queryClient.test-d.tsx | 117 +++--- .../src/__tests__/queryClient.test.tsx | 180 ++++----- .../src/__tests__/queryObserver.test-d.tsx | 65 ++-- .../src/__tests__/queryObserver.test.tsx | 143 ++++--- .../__tests__/queryObserverProjection.test.ts | 30 +- .../queryObserverResultReader.test-d.tsx | 5 +- .../queryObserverResultReader.test.tsx | 38 +- .../src/__tests__/streamedQuery.test.tsx | 7 +- .../query-core/src/__tests__/utils.test-d.tsx | 4 +- packages/query-test-utils/package.json | 5 +- .../query-test-utils/src/cacheOperations.ts | 9 + packages/query-test-utils/src/projection.ts | 23 ++ packages/query-test-utils/src/scope.ts | 8 + packages/query-types/src/queryObserver.ts | 12 +- packages/query-types/src/types.ts | 52 ++- .../react-query-no-core-pluggable/README.md | 42 ++- .../package.json | 2 +- .../src/HydrationBoundary.tsx | 6 +- .../src/__tests__/cacheOperations.test.ts | 30 ++ .../src/__tests__/infiniteQuery.test.ts | 48 +++ .../src/__tests__/projection.test-d.ts | 72 ++++ .../src/__tests__/projection.test.ts | 58 +++ .../src/__tests__/refetchInterval.test-d.ts | 3 +- .../src/__tests__/refetchInterval.test.ts | 3 +- .../src/__tests__/serialScope.test.ts | 67 ++++ .../src/index.ts | 15 + .../src/infiniteQueryOptions.ts | 6 +- .../src/runtime/cacheOperations.ts | 287 ++++++++++++++ .../src/runtime/hydration.ts | 40 +- .../src/runtime/infiniteQuery.ts | 105 ++++++ .../src/runtime/infiniteQueryBehavior.ts | 220 ++++++----- .../src/runtime/infiniteQueryObserver.ts | 16 +- .../src/runtime/mutation.ts | 10 +- .../src/runtime/mutationCache.ts | 50 +-- .../src/runtime/placeholderData.ts | 96 +++++ .../src/runtime/projectResult.ts | 89 +++++ .../src/runtime/projectionTypes.ts | 20 + .../src/runtime/query.ts | 27 +- .../src/runtime/queryClient.ts | 354 +----------------- .../src/runtime/queryObserver.ts | 166 ++------ .../src/runtime/runtimeBinding.ts | 8 + .../src/runtime/select.ts | 131 +++++++ .../src/runtime/serialScope.ts | 96 +++++ .../src/types.ts | 2 +- .../src/useInfiniteQuery.ts | 6 +- .../src/usePrefetchInfiniteQuery.tsx | 7 +- .../src/useQueries.ts | 17 +- .../src/useQuery.ts | 8 +- .../src/useSuspenseQueries.ts | 11 +- .../tests/compat-cacheOperations.ts | 30 ++ .../tests/compat-infiniteQuery.ts | 76 ++++ .../tests/compat-projection.ts | 42 +++ .../tests/compat-scope.ts | 1 + packages/react-query-no-core/README.md | 2 + .../src/runtime/infiniteQueryBehavior.ts | 191 +++++----- .../react-query-no-core/src/runtime/query.ts | 13 +- .../__tests__/infiniteQueryOptions.test-d.tsx | 20 +- .../src/__tests__/placeholderData.test.ts | 27 +- .../src/__tests__/queryOptions.test-d.tsx | 9 +- .../react-query/src/__tests__/ssr.test.tsx | 3 +- .../src/__tests__/transition.test.tsx | 12 +- .../src/__tests__/useInfiniteQuery.test-d.tsx | 6 +- .../src/__tests__/useInfiniteQuery.test.tsx | 34 +- .../src/__tests__/useMutation.test.tsx | 7 +- .../usePrefetchInfiniteQuery.test.tsx | 5 +- .../src/__tests__/usePrefetchQuery.test-d.tsx | 3 +- .../src/__tests__/useQueries.test-d.tsx | 94 ++--- .../src/__tests__/useQueries.test.tsx | 10 +- .../src/__tests__/useQuery.test-d.tsx | 3 +- .../src/__tests__/useQuery.test.tsx | 171 ++++++--- .../useSuspenseInfiniteQuery.test-d.tsx | 14 +- .../useSuspenseInfiniteQuery.test.tsx | 7 +- .../__tests__/useSuspenseQueries.test-d.tsx | 46 ++- .../src/__tests__/useSuspenseQueries.test.tsx | 21 +- .../src/__tests__/useSuspenseQuery.test-d.tsx | 16 +- .../src/__tests__/useSuspenseQuery.test.tsx | 22 +- scripts/port-query-projection-tests.mjs | 83 ++++ scripts/react-query-compat.config.ts | 16 +- scripts/test-react-query-compat.mjs | 23 +- 100 files changed, 2878 insertions(+), 1386 deletions(-) create mode 100644 integrations/react/bundle-size/src/options.jsx create mode 100644 integrations/react/bundle-size/src/pluggable-options.js create mode 100644 integrations/react/bundle-size/src/v6-options.js create mode 100644 packages/query-core/src/__tests__/infiniteFetch.ts create mode 100644 packages/query-test-utils/src/cacheOperations.ts create mode 100644 packages/query-test-utils/src/projection.ts create mode 100644 packages/query-test-utils/src/scope.ts create mode 100644 packages/react-query-no-core-pluggable/src/__tests__/cacheOperations.test.ts create mode 100644 packages/react-query-no-core-pluggable/src/__tests__/infiniteQuery.test.ts create mode 100644 packages/react-query-no-core-pluggable/src/__tests__/projection.test-d.ts create mode 100644 packages/react-query-no-core-pluggable/src/__tests__/projection.test.ts create mode 100644 packages/react-query-no-core-pluggable/src/__tests__/serialScope.test.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/cacheOperations.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/infiniteQuery.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/placeholderData.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/projectResult.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/projectionTypes.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/select.ts create mode 100644 packages/react-query-no-core-pluggable/src/runtime/serialScope.ts create mode 100644 packages/react-query-no-core-pluggable/tests/compat-cacheOperations.ts create mode 100644 packages/react-query-no-core-pluggable/tests/compat-infiniteQuery.ts create mode 100644 packages/react-query-no-core-pluggable/tests/compat-projection.ts create mode 100644 packages/react-query-no-core-pluggable/tests/compat-scope.ts create mode 100644 scripts/port-query-projection-tests.mjs diff --git a/.changeset/react-query-standalone-adapters.md b/.changeset/react-query-standalone-adapters.md index c7ac4c1120e..42d62738506 100644 --- a/.changeset/react-query-standalone-adapters.md +++ b/.changeset/react-query-standalone-adapters.md @@ -5,4 +5,4 @@ '@tanstack/react-query-no-core-pluggable': minor --- -Add experimental ESM React Query adapters with an integrated query runtime. The pluggable adapter provides optional polling through the `refetchInterval` option factory. All three runtimes share their TypeScript definitions through `@tanstack/query-types`. +Add experimental ESM React Query adapters with an integrated query runtime. The pluggable adapter lets apps import polling, selection, placeholder data, and scoped mutation queues at the point of use. It also exports imperative infinite queries and bulk cache operations as standalone functions. Both adapters and `@tanstack/query-core` share TypeScript definitions through `@tanstack/query-types`. diff --git a/integrations/react/bundle-size/README.md b/integrations/react/bundle-size/README.md index df48ad318ee..4f22b8b5d72 100644 --- a/integrations/react/bundle-size/README.md +++ b/integrations/react/bundle-size/README.md @@ -1,6 +1,6 @@ # React Query app bundle size -This workspace builds three browser apps against each adapter’s public package entry point. The read-only app fetches a book list. 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 all four regular and suspense query hooks. All builds include React and React DOM and use the default client. The original and standalone adapters accept a numeric interval. The pluggable adapter imports its interval scheduler through the `refetchInterval` option helper. The benchmark checks that only the polling build of that adapter includes the scheduler. +This workspace builds four browser apps against each adapter’s public package entry point. The read-only app fetches a book list. 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 all four regular and suspense query hooks. The options app keeps the previous page while fetching, selects the displayed titles, saves bookmarks in a serial scope, and invalidates the bookmark list. All builds include React and React DOM and use the default client. The original and standalone adapters accept a numeric interval. The pluggable adapter imports its interval scheduler through the `refetchInterval` option helper. The benchmark checks retained modules in each app and bundles individual public exports to check that selection, placeholder data and serial queues can be removed independently. The React hydration boundary only restores queries. The universal `hydrate` also restores serial queues from saved mutations. CI builds the original adapter and its dependencies from the PR's base commit. The two alternatives, the app code, the bundler and both React packages come from the PR head. The report records both commit IDs. @@ -22,7 +22,7 @@ QUERY_BASE_CHECKOUT="$PWD/../query-bundle-base" pnpm --filter @tanstack/query-in The report at `integrations/react/bundle-size/dist/report.md` shows total emitted JavaScript bytes and the sum of individually compressed chunks for gzip and Brotli. Each percentage uses the original adapter’s application size for that workload as its denominator. Serve a directory under `dist//` to try the built app. -Run the nine production app scenarios in Chromium after measuring: +Run the twelve production app scenarios in Chromium after measuring: ```sh cd integrations/react/bundle-size diff --git a/integrations/react/bundle-size/browser/apps.test.js b/integrations/react/bundle-size/browser/apps.test.js index 307b717d6df..f17aa83f987 100644 --- a/integrations/react/bundle-size/browser/apps.test.js +++ b/integrations/react/bundle-size/browser/apps.test.js @@ -20,6 +20,7 @@ async function openApp(scenario, adapter) { afterEach(() => { document.querySelector('iframe')?.remove() localStorage.removeItem('bookmark') + localStorage.removeItem('bookmarks') }) describe.each(adapters)('@tanstack/%s', (adapter) => { @@ -46,6 +47,46 @@ describe.each(adapters)('@tanstack/%s', (adapter) => { 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 + 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) => + Array.from(app.querySelectorAll('button')).find( + (item) => item.textContent === label, + ) + 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 () => { const app = await openApp('polling', adapter) const timestamps = () => diff --git a/integrations/react/bundle-size/measure.mjs b/integrations/react/bundle-size/measure.mjs index c1672e35d8a..6af9232eb94 100644 --- a/integrations/react/bundle-size/measure.mjs +++ b/integrations/react/bundle-size/measure.mjs @@ -20,6 +20,11 @@ const workloads = [ title: 'Paginated list with bookmarks · useQuery, useMutation, useInfiniteQuery', }, + { + screen: 'options', + title: + 'Selected and placeholder data, serial bookmarks and cache invalidation', + }, { screen: 'polling', title: 'Polling with the four regular and suspense query hooks', @@ -64,6 +69,11 @@ async function measure(packageName, screen) { ? 'pluggable-interval.js' : 'numeric-interval.js', ), + '#feature-options': path.join( + root, + 'src', + packageName === pluggable ? 'pluggable-options.js' : 'v6-options.js', + ), '#screen': path.join(root, 'src', `${screen}.jsx`), }, }, @@ -122,13 +132,23 @@ async function measure(packageName, screen) { } } if (packageName === pluggable) { - const includesPolling = modules.some((id) => - id.endsWith('/runtime/refetchInterval.js'), - ) - if (includesPolling !== (screen === 'polling')) { - throw new Error( - `Unexpected refetchInterval implementation in ${screen}: included=${includesPolling}`, + const features = { + refetchInterval: screen === 'polling', + infiniteQueryBehavior: screen === 'paginated' || screen === 'polling', + select: screen === 'options', + placeholderData: screen === 'options', + serialScope: screen === 'options', + cacheOperations: screen === 'options', + } + for (const [feature, expected] of Object.entries(features)) { + const included = modules.some((id) => + id.endsWith(`/runtime/${feature}.js`), ) + if (included !== expected) { + throw new Error( + `Unexpected ${feature} implementation in ${screen}: included=${included}`, + ) + } } } @@ -144,6 +164,77 @@ async function measure(packageName, screen) { return sizes } +// A combined app cannot tell whether each projection pulls in its sibling, +// or whether rendering a boundary pulls in paused-mutation restoration. +async function checkStandaloneExports() { + const expected = { + select: ['select', 'projectResult'], + placeholderData: ['placeholderData', 'projectResult'], + serialScope: ['serialScope'], + invalidateQueries: ['cacheOperations'], + HydrationBoundary: ['infiniteQueryBehavior'], + hydrate: ['infiniteQueryBehavior', 'mutation', 'serialScope'], + } + const features = new Set(Object.values(expected).flat()) + const entry = path.join(root, 'public-export-probe.js') + for (const [name, required] of Object.entries(expected)) { + const results = await build({ + root, + configFile: false, + logLevel: 'error', + plugins: [ + { + name: 'import-one-public-export', + resolveId(id) { + if (id === entry) return id + }, + load(id) { + if (id === entry) return `export { ${name} } from '${pluggable}'` + }, + }, + ], + build: { + write: false, + lib: { entry, formats: ['es'], fileName: 'probe' }, + rolldownOptions: { + external: ['react', 'react/jsx-runtime'], + checks: { moduleLevelDirective: false }, + }, + }, + }) + const modules = results + .flatMap(({ output }) => + output + .filter((file) => file.type === 'chunk') + .flatMap((chunk) => Object.entries(chunk.modules)), + ) + .filter(([, module]) => module.renderedLength > 0) + for (const feature of features) { + const included = modules.some(([id]) => + id.endsWith(`/runtime/${feature}.js`), + ) + if (included !== required.includes(feature)) { + throw new Error( + `Importing ${name} unexpectedly ${included ? 'included' : 'excluded'} ${feature}`, + ) + } + } + if (name === 'invalidateQueries') { + const [, operations] = modules.find(([id]) => + id.endsWith('/runtime/cacheOperations.js'), + ) + if ( + operations.renderedExports.some( + (item) => !['invalidateQueries', 'refetchQueries'].includes(item), + ) + ) { + throw new Error('Invalidation included unrelated bulk cache operations') + } + } + } +} +await checkStandaloneExports() + const integer = new Intl.NumberFormat('en-US') function formatSize(bytes, baselineBytes, isBaseline) { const size = `${integer.format(bytes)} B` @@ -217,7 +308,7 @@ for (const { screen, title } of workloads) { } lines.push( '', - 'Gzip level 9 and Brotli quality 11 are applied to each JavaScript chunk before summing. All workloads use the default client. Only the polling app imports the pluggable refetchInterval helper.', + 'Gzip level 9 and Brotli quality 11 are applied to each JavaScript chunk before summing. All workloads use the default client. The polling workload imports the interval scheduler. The options workload imports selection, placeholder data, serial scopes and invalidation.', '', ) const report = lines.join('\n') diff --git a/integrations/react/bundle-size/src/options.jsx b/integrations/react/bundle-size/src/options.jsx new file mode 100644 index 00000000000..b220a3ddb5a --- /dev/null +++ b/integrations/react/bundle-size/src/options.jsx @@ -0,0 +1,67 @@ +import * as React from 'react' +import { useMutation, useQuery, useQueryClient } from '#adapter' +import { + bookmarkScope, + previousPage, + refreshBookmarks, + selectTitles, +} from '#feature-options' +import { fetchBooks } from './books.js' + +function savedBooks() { + return JSON.parse(localStorage.getItem('bookmarks') ?? '[]') +} + +export function ReadingList() { + const client = useQueryClient() + const [page, setPage] = React.useState(1) + const [events, setEvents] = React.useState([]) + const books = useQuery({ + queryKey: ['books', page], + queryFn: ({ signal }) => fetchBooks(page, signal), + select: selectTitles, + placeholderData: previousPage, + }) + const saved = useQuery({ queryKey: ['bookmarks'], queryFn: savedBooks }) + const bookmark = useMutation({ + scope: bookmarkScope, + mutationFn: async (title) => { + setEvents((items) => [...items, `Saving ${title}`]) + await Promise.resolve() + localStorage.setItem( + 'bookmarks', + JSON.stringify([...savedBooks(), title]), + ) + setEvents((items) => [...items, `Saved ${title}`]) + }, + onSuccess: () => refreshBookmarks(client), + }) + if (books.isPending) return

Loading books…

+ if (books.isError) return

{books.error.message}

+ return ( + <> +
    + {books.data.map((title) => ( +
  • {title}
  • + ))} +
+ {books.isPlaceholderData && ( +

Showing the previous page

+ )} + + +

Bookmarks: {saved.data?.join(', ')}

+
    + {events.map((event, index) => ( +
  1. {event}
  2. + ))} +
+ + ) +} diff --git a/integrations/react/bundle-size/src/pluggable-options.js b/integrations/react/bundle-size/src/pluggable-options.js new file mode 100644 index 00000000000..62d8cb520fb --- /dev/null +++ b/integrations/react/bundle-size/src/pluggable-options.js @@ -0,0 +1,12 @@ +import { + invalidateQueries, + placeholderData, + select, + serialScope, +} from '#adapter' + +export const selectTitles = select((page) => page.titles) +export const previousPage = placeholderData((previous) => previous) +export const bookmarkScope = serialScope('bookmarks') +export const refreshBookmarks = (client) => + invalidateQueries(client, { queryKey: ['bookmarks'] }) diff --git a/integrations/react/bundle-size/src/v6-options.js b/integrations/react/bundle-size/src/v6-options.js new file mode 100644 index 00000000000..b6f20e37c43 --- /dev/null +++ b/integrations/react/bundle-size/src/v6-options.js @@ -0,0 +1,5 @@ +export const selectTitles = (page) => page.titles +export const previousPage = (previous) => previous +export const bookmarkScope = { id: 'bookmarks' } +export const refreshBookmarks = (client) => + client.invalidateQueries({ queryKey: ['bookmarks'] }) diff --git a/knip.config.ts b/knip.config.ts index 746a9a2c8cc..5271e7e9cbe 100644 --- a/knip.config.ts +++ b/knip.config.ts @@ -55,7 +55,7 @@ export default { ignoreDependencies: optionalPeerDependencies(reactQueryNoCore), }, 'packages/react-query-no-core-pluggable': { - entry: [...compatibilityEntries, 'tests/compat-polling.ts'], + entry: [...compatibilityEntries, 'tests/compat-*.ts'], ignoreDependencies: optionalPeerDependencies(reactQueryPluggable), }, 'packages/react-query-devtools': { diff --git a/nx.json b/nx.json index c66d9f0bfa1..0db40918265 100644 --- a/nx.json +++ b/nx.json @@ -27,6 +27,7 @@ ], "reactQueryCompatibility": [ "{workspaceRoot}/scripts/test-react-query-compat.mjs", + "{workspaceRoot}/scripts/port-query-projection-tests.mjs", "{workspaceRoot}/scripts/react-query-compat.config.ts", "{workspaceRoot}/packages/query-core/src/__tests__/**/*", "{workspaceRoot}/packages/query-core/vite.config.ts", diff --git a/packages/query-core/src/__tests__/hydration.test.tsx b/packages/query-core/src/__tests__/hydration.test.tsx index 716926661dd..8c54bfee381 100644 --- a/packages/query-core/src/__tests__/hydration.test.tsx +++ b/packages/query-core/src/__tests__/hydration.test.tsx @@ -1,4 +1,6 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' +import { serialScope } from '@tanstack/query-test-utils/scope' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { dehydrate, hydrate } from '../hydration' import { dehydrateQuery } from '../index' @@ -788,7 +790,7 @@ describe('dehydration and rehydration', () => { }) .catch(noop) - queryClient.refetchQueries({ queryKey: key }) + cacheOperations(queryClient).refetchQueries({ queryKey: key }) const dehydrated = dehydrate(queryClient) resolvePromise('string') @@ -978,9 +980,7 @@ describe('dehydration and rehydration', () => { mutationFn: () => { return Promise.resolve('mutation') }, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), }, 'vars', ) @@ -1535,7 +1535,7 @@ describe('dehydration and rehydration', () => { const queryCache = new QueryCache() const queryClient = new QueryClient({ queryCache }) - const prefetchPromise = queryClient + const prefetchPromise = cacheOperations(queryClient) .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => @@ -1576,7 +1576,7 @@ describe('dehydration and rehydration', () => { const queryCache = new QueryCache() const queryClient = new QueryClient({ queryCache }) - const prefetchPromise = queryClient + const prefetchPromise = cacheOperations(queryClient) .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => @@ -1598,7 +1598,7 @@ describe('dehydration and rehydration', () => { const hydrationClient = new QueryClient({ queryCache: hydrationCache }) hydrate(hydrationClient, dehydrated) - const resultPromise = hydrationClient.infiniteQuery({ + const resultPromise = cacheOperations(hydrationClient).infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => sleep(10).then(() => ({ @@ -1620,7 +1620,7 @@ describe('dehydration and rehydration', () => { const key = createKey() const serverClient = new QueryClient({ queryCache: new QueryCache() }) - const prefetchPromise = serverClient + const prefetchPromise = cacheOperations(serverClient) .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => @@ -1657,7 +1657,7 @@ describe('dehydration and rehydration', () => { const key = createKey() const serverClient = new QueryClient({ queryCache: new QueryCache() }) - const prefetchPromise = serverClient + const prefetchPromise = cacheOperations(serverClient) .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => @@ -1686,7 +1686,7 @@ describe('dehydration and rehydration', () => { expect(beforeRefetch?.pages).toHaveLength(1) expect(beforeRefetch?.pageParams).toHaveLength(1) - const resultPromise = clientClient.infiniteQuery({ + const resultPromise = cacheOperations(clientClient).infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => sleep(10).then(() => ({ @@ -1710,7 +1710,7 @@ describe('dehydration and rehydration', () => { const key = createKey() const serverClient = new QueryClient({ queryCache: new QueryCache() }) - const prefetchPromise = serverClient + const prefetchPromise = cacheOperations(serverClient) .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => @@ -1743,7 +1743,7 @@ describe('dehydration and rehydration', () => { const key = createKey() const serverClient = new QueryClient({ queryCache: new QueryCache() }) - const prefetchPromise = serverClient + const prefetchPromise = cacheOperations(serverClient) .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => @@ -1772,7 +1772,7 @@ describe('dehydration and rehydration', () => { }>(key) expect(beforeRefetch?.pages).toHaveLength(2) - const resultPromise = clientClient + const resultPromise = cacheOperations(clientClient) .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => diff --git a/packages/query-core/src/__tests__/infiniteFetch.ts b/packages/query-core/src/__tests__/infiniteFetch.ts new file mode 100644 index 00000000000..2e645408197 --- /dev/null +++ b/packages/query-core/src/__tests__/infiniteFetch.ts @@ -0,0 +1,13 @@ +import { infiniteQueryBehavior } from '../infiniteQueryBehavior' + +export function prepareInfiniteFetch( + ...args: Parameters< + ReturnType< + typeof infiniteQueryBehavior + >['onFetch'] + > +) { + infiniteQueryBehavior().onFetch( + ...args, + ) +} diff --git a/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx b/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx index 4549e7ecb5e..55252d7eecc 100644 --- a/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx +++ b/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { CancelledError, @@ -6,7 +7,7 @@ import { QueryClient, defaultQueryFn, } from '..' -import { infiniteQueryBehavior } from '../infiniteQueryBehavior' +import { prepareInfiniteFetch } from './infiniteFetch' import type { InfiniteData, InfiniteQueryObserverResult, @@ -351,7 +352,6 @@ describe('InfiniteQueryBehavior', () => { return pageParam }) - const behavior = infiniteQueryBehavior() const context = { client: queryClient, queryKey: key, @@ -372,7 +372,10 @@ describe('InfiniteQueryBehavior', () => { signal: abortController.signal, } - behavior.onFetch(context as any, {} as any) + prepareInfiniteFetch( + context as any, + {} as any, + ) await expect(context.fetchFn()).rejects.toBe(abortController.signal.reason) expect(queryFn).toHaveBeenCalledTimes(1) @@ -486,13 +489,13 @@ describe('InfiniteQueryBehavior', () => { return String(pageParam) } - await queryClient.infiniteQuery({ + await cacheOperations(queryClient).infiniteQuery({ queryKey: key, queryFn, initialPageParam: null, getNextPageParam: () => undefined, }) - await queryClient.infiniteQuery({ + await cacheOperations(queryClient).infiniteQuery({ queryKey: key, queryFn, initialPageParam: 'replacement', diff --git a/packages/query-core/src/__tests__/infiniteQueryObserver.test-d.tsx b/packages/query-core/src/__tests__/infiniteQueryObserver.test-d.tsx index 584ba64a256..427dbc2401c 100644 --- a/packages/query-core/src/__tests__/infiniteQueryObserver.test-d.tsx +++ b/packages/query-core/src/__tests__/infiniteQueryObserver.test-d.tsx @@ -1,4 +1,8 @@ import { createKey } from '@tanstack/query-test-utils' +import { + projectionInput, + selectOption, +} from '@tanstack/query-test-utils/projection' import { afterEach, beforeEach, describe, expectTypeOf, it } from 'vitest' import { InfiniteQueryObserver, QueryClient } from '..' import type { @@ -298,7 +302,7 @@ describe('infiniteQueryObserver', () => { queryFn: () => Promise.resolve({ value: 'data' }), initialPageParam: 1, getNextPageParam: () => 1, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf< InfiniteData<{ value: string }, number> >() @@ -313,7 +317,7 @@ describe('infiniteQueryObserver', () => { queryFn: () => Promise.resolve({ count: 1 }), initialPageParam: 1, getNextPageParam: () => 1, - select: (data) => data.pages.length, + [selectOption]: (data) => data.pages.length, }) expectTypeOf(observer.getCurrentResult().data).toEqualTypeOf< @@ -951,7 +955,7 @@ describe('infiniteQueryObserver', () => { queryFn: () => Promise.resolve({ value: 'data' }), initialPageParam: 1, getNextPageParam: () => 1, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf< InfiniteData<{ value: string }, number> >() @@ -1004,7 +1008,7 @@ describe('infiniteQueryObserver', () => { getNextPageParam: () => 1, }) - expectTypeOf(observer.options.select).toEqualTypeOf< + expectTypeOf(projectionInput(observer.options.select)).toEqualTypeOf< | (( data: InfiniteData<{ value: string }, number>, ) => InfiniteData<{ value: string }, unknown>) diff --git a/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx b/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx index 1b4c53f2c6c..4d80341e594 100644 --- a/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx +++ b/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx @@ -1,4 +1,6 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' +import { selectOption } from '@tanstack/query-test-utils/projection' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { InfiniteQueryObserver, QueryClient } from '..' import type { GetNextPageParamFunction, GetPreviousPageParamFunction } from '..' @@ -26,7 +28,7 @@ describe('InfiniteQueryObserver', () => { const observer = new InfiniteQueryObserver(queryClient, { queryKey: key, queryFn: () => sleep(10).then(() => 1), - select: (data) => ({ + [selectOption]: (data) => ({ pages: data.pages.map((x) => `${x}`), pageParams: data.pageParams, }), @@ -55,7 +57,7 @@ describe('InfiniteQueryObserver', () => { meta, queryKey: key, queryFn, - select: (data) => ({ + [selectOption]: (data) => ({ pages: data.pages.map((x) => `${x}`), pageParams: data.pageParams, }), @@ -260,7 +262,7 @@ describe('InfiniteQueryObserver', () => { const unsubscribe = observer.subscribe(() => {}) await vi.advanceTimersByTimeAsync(10) - queryClient.removeQueries({ queryKey: key }) + cacheOperations(queryClient).removeQueries({ queryKey: key }) queryClient.getQueryCache().build(queryClient, { queryKey: key, queryFn: () => sleep(10).then(() => 'recreated-page'), diff --git a/packages/query-core/src/__tests__/mutation.test-d.tsx b/packages/query-core/src/__tests__/mutation.test-d.tsx index e2e692e6269..831f84590db 100644 --- a/packages/query-core/src/__tests__/mutation.test-d.tsx +++ b/packages/query-core/src/__tests__/mutation.test-d.tsx @@ -1,6 +1,7 @@ import { describe, expectTypeOf, it } from 'vitest' import { Mutation } from '../mutation' import { QueryClient } from '../queryClient' +import type { serialScope } from '@tanstack/query-test-utils/scope' import type { Action, MutationState } from '../mutation' import type { MutationObserver } from '../mutationObserver' import type { @@ -490,7 +491,7 @@ describe('mutation', () => { describe('scope', () => { it('should be an optional scope carrying a string id', () => { expectTypeOf().toEqualTypeOf< - { id: string } | undefined + ReturnType | undefined >() }) }) diff --git a/packages/query-core/src/__tests__/mutation.test.tsx b/packages/query-core/src/__tests__/mutation.test.tsx index fd98e764e32..aab835a7da0 100644 --- a/packages/query-core/src/__tests__/mutation.test.tsx +++ b/packages/query-core/src/__tests__/mutation.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { serialScope } from '@tanstack/query-test-utils/scope' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MutationCache, QueryClient, focusManager, onlineManager } from '..' import { Mutation } from '../mutation' @@ -524,9 +525,7 @@ describe('mutation', () => { queryClient, { mutationKey: key1, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('start-A') await sleep(10) @@ -547,9 +546,7 @@ describe('mutation', () => { queryClient, { mutationKey: key2, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('start-B') await sleep(10) @@ -587,9 +584,7 @@ describe('mutation', () => { queryClient, { mutationKey: key1, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), networkMode: 'always', mutationFn: async () => { results.push('start-A') @@ -605,9 +600,7 @@ describe('mutation', () => { queryClient, { mutationKey: key2, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), networkMode: 'always', mutationFn: async () => { results.push('start-B') @@ -648,9 +641,7 @@ describe('mutation', () => { queryClient, { mutationKey: key1, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('start-A') await sleep(10) @@ -665,9 +656,7 @@ describe('mutation', () => { queryClient, { mutationKey: key2, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('start-B') await sleep(10) @@ -716,9 +705,7 @@ describe('mutation', () => { queryClient, { mutationKey: key1, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('start-A') await sleep(10) @@ -733,9 +720,7 @@ describe('mutation', () => { queryClient, { mutationKey: key2, - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('start-B') await sleep(10) @@ -781,9 +766,7 @@ describe('mutation', () => { executeMutation( queryClient, { - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: () => sleep(20).then(() => 'a'), }, 'vars1', @@ -791,9 +774,7 @@ describe('mutation', () => { executeMutation( queryClient, { - scope: { - id: 'scope', - }, + scope: serialScope('scope'), onMutate: () => sleep(10), mutationFn: () => sleep(10).then(() => 'b'), }, @@ -892,9 +873,7 @@ describe('mutation', () => { executeMutation( queryClient, { - scope: { - id: '1', - }, + scope: serialScope('1'), mutationFn: async () => { results.push('start-A1') await sleep(10) @@ -908,9 +887,7 @@ describe('mutation', () => { executeMutation( queryClient, { - scope: { - id: '1', - }, + scope: serialScope('1'), mutationFn: async () => { results.push('start-B1') await sleep(10) @@ -924,9 +901,7 @@ describe('mutation', () => { executeMutation( queryClient, { - scope: { - id: '2', - }, + scope: serialScope('2'), mutationFn: async () => { results.push('start-A2') await sleep(10) @@ -940,9 +915,7 @@ describe('mutation', () => { executeMutation( queryClient, { - scope: { - id: '2', - }, + scope: serialScope('2'), mutationFn: async () => { results.push('start-B2') await sleep(10) diff --git a/packages/query-core/src/__tests__/mutationCache.test.tsx b/packages/query-core/src/__tests__/mutationCache.test.tsx index 97f076e7f86..3e422fa3e61 100644 --- a/packages/query-core/src/__tests__/mutationCache.test.tsx +++ b/packages/query-core/src/__tests__/mutationCache.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { serialScope } from '@tanstack/query-test-utils/scope' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MutationCache, MutationObserver, QueryClient } from '..' import { Mutation } from '../mutation' @@ -618,11 +619,11 @@ describe('mutationCache', () => { const testClient = new QueryClient({ mutationCache: testCache }) const mutation1 = Mutation.build(testClient, { - scope: { id: 'scope1' }, + scope: serialScope('scope1'), mutationFn: () => Promise.resolve('data1'), }) const mutation2 = Mutation.build(testClient, { - scope: { id: 'scope1' }, + scope: serialScope('scope1'), mutationFn: () => Promise.resolve('data2'), }) @@ -639,7 +640,7 @@ describe('mutationCache', () => { const testClient = new QueryClient({ mutationCache: testCache }) const mutation = Mutation.build(testClient, { - scope: { id: 'scope1' }, + scope: serialScope('scope1'), mutationFn: () => Promise.resolve('data'), }) diff --git a/packages/query-core/src/__tests__/queriesObserver.test-d.tsx b/packages/query-core/src/__tests__/queriesObserver.test-d.tsx index 55729bc0634..e34cfa144ff 100644 --- a/packages/query-core/src/__tests__/queriesObserver.test-d.tsx +++ b/packages/query-core/src/__tests__/queriesObserver.test-d.tsx @@ -1,4 +1,5 @@ import { createKey } from '@tanstack/query-test-utils' +import { selectOption } from '@tanstack/query-test-utils/projection' import { afterEach, beforeEach, describe, expectTypeOf, it } from 'vitest' import { QueriesObserver, QueryClient, defaultQueryFn } from '..' import type { QueryObserver, QueryObserverResult } from '..' @@ -96,7 +97,7 @@ describe('queriesObserver', () => { it('should reject an option it does not declare', () => { new QueriesObserver(queryClient, [], { // @ts-expect-error combine is the only option - select: (results: Array) => results, + [selectOption]: (results: Array) => results, }) expectTypeOf< diff --git a/packages/query-core/src/__tests__/queriesObserver.test.tsx b/packages/query-core/src/__tests__/queriesObserver.test.tsx index 41463f22631..5d148cf5af4 100644 --- a/packages/query-core/src/__tests__/queriesObserver.test.tsx +++ b/packages/query-core/src/__tests__/queriesObserver.test.tsx @@ -1,6 +1,11 @@ import { setFlagsFromString } from 'node:v8' import { runInNewContext } from 'node:vm' import { createKey, sleep } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueriesObserver, QueryClient, QueryObserver, defaultQueryFn } from '..' import type { QueryObserverResult } from '..' @@ -135,7 +140,7 @@ describe('queriesObserver', () => { queryKey: keyB, queryFn: defaultQueryFn, staleTime: Infinity, - select, + [selectOption]: select, structuralSharing: false, } as const const observer = new QueriesObserver(queryClient, [optionsA]) @@ -162,7 +167,7 @@ describe('queriesObserver', () => { const options = { queryKey: key, queryFn: defaultQueryFn, - select, + [selectOption]: select, structuralSharing: false, } as const const observer = new QueriesObserver(queryClient, []) @@ -200,7 +205,7 @@ describe('queriesObserver', () => { const reader = observer.createResultReader( queries.map((query) => ({ ...query, - select: (data: number) => data * 10, + [selectOption]: (data: number) => data * 10, })), { combine }, ) @@ -234,7 +239,7 @@ describe('queriesObserver', () => { }) first.commit() const second = observer.createResultReader( - [{ ...options, select: (data: number) => data * 3 }], + [{ ...options, [selectOption]: (data: number) => data * 3 }], { combine }, ) expect(second.combineResult(second.getSnapshot())).toStrictEqual({ @@ -243,7 +248,7 @@ describe('queriesObserver', () => { expect(observer.getCurrentResult()[0]!.data).toBe(2) second.commit() const third = observer.createResultReader( - [{ ...options, select: (data: number) => data * 3 }], + [{ ...options, [selectOption]: (data: number) => data * 3 }], { combine }, ) expect(third.combineResult(third.getSnapshot())).toStrictEqual({ @@ -257,26 +262,26 @@ describe('queriesObserver', () => { const first = { queryKey: createKey(), enabled: false, - placeholderData: 1, + [placeholderOption]: 1, queryFn: defaultQueryFn, } as const const second = { queryKey: createKey(), enabled: false, - placeholderData: 2, + [placeholderOption]: 2, queryFn: defaultQueryFn, } as const const third = { queryKey: createKey(), enabled: false, - placeholderData: 3, + [placeholderOption]: 3, queryFn: defaultQueryFn, } as const const observer = new QueriesObserver(queryClient, [first, second]) const current = observer.getCurrentResult() const optimistic = observer - .createResultReader([{ ...first, placeholderData: 4 }, third]) + .createResultReader([{ ...first, [placeholderOption]: 4 }, third]) .getSnapshot() expect(optimistic.map((result) => result.data)).toStrictEqual([4, 3]) @@ -656,12 +661,12 @@ describe('queriesObserver', () => { { queryKey: key1, queryFn: queryFn1, - select: (d: any) => d + 100, + [selectOption]: (d: any) => d + 100, }, { queryKey: key2, queryFn: queryFn2, - select: (d: any) => d + 100, + [selectOption]: (d: any) => d + 100, }, ]) @@ -751,7 +756,7 @@ describe('queriesObserver', () => { const unsubscribe = observer.subscribe(() => undefined) - void queryClient.resetQueries({ queryKey: key }) + void cacheOperations(queryClient).resetQueries({ queryKey: key }) expect(combine).toHaveBeenCalledTimes(1) unsubscribe() @@ -797,7 +802,7 @@ describe('queriesObserver', () => { { combine }, ) - void queryClient.resetQueries({ queryKey: key }) + void cacheOperations(queryClient).resetQueries({ queryKey: key }) expect(combine).toHaveBeenCalledTimes(1) unsubscribe() @@ -968,7 +973,7 @@ describe('queriesObserver', () => { expect.objectContaining({ status: 'success', data: 'data' }), ]) - void queryClient.refetchQueries({ queryKey: key }) + void cacheOperations(queryClient).refetchQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(10) expect(listener).toHaveBeenCalledTimes(2) expect(listener).toHaveBeenLastCalledWith([ @@ -979,7 +984,7 @@ describe('queriesObserver', () => { }), ]) - void queryClient.refetchQueries({ queryKey: key }) + void cacheOperations(queryClient).refetchQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(0) expect(observer.getCurrentResult()[0]).toMatchObject({ status: 'error', @@ -1340,7 +1345,7 @@ describe('queriesObserver', () => { ) observer.setQueries([{ queryKey: createKey(), queryFn: () => 2 }]) - queryClient.removeQueries({ queryKey: oldKey }) + cacheOperations(queryClient).removeQueries({ queryKey: oldKey }) // A WeakRef keeps its target alive until the current job ends. await vi.advanceTimersByTimeAsync(0) gc() diff --git a/packages/query-core/src/__tests__/query.test.tsx b/packages/query-core/src/__tests__/query.test.tsx index c19d15da5d7..e2286a13c7a 100644 --- a/packages/query-core/src/__tests__/query.test.tsx +++ b/packages/query-core/src/__tests__/query.test.tsx @@ -3,6 +3,7 @@ import { mockVisibilityState, sleep, } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { CancelledError, @@ -52,7 +53,7 @@ describe('query', () => { }) initial.catch(noop) await vi.advanceTimersByTimeAsync(0) - await queryClient.cancelQueries({ queryKey: key }) + await cacheOperations(queryClient).cancelQueries({ queryKey: key }) focusManager.setFocused(false) try { const replacement = queryClient.query({ @@ -80,7 +81,7 @@ describe('query', () => { }) initial.catch(noop) await vi.advanceTimersByTimeAsync(0) - await queryClient.cancelQueries({ queryKey: key }) + await cacheOperations(queryClient).cancelQueries({ queryKey: key }) focusManager.setFocused(false) try { await vi.advanceTimersByTimeAsync(250) @@ -1151,9 +1152,9 @@ describe('query', () => { mockedData = [1, 2] // update "server" state in the background - void queryClient.invalidateQueries({ queryKey: key }) + void cacheOperations(queryClient).invalidateQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(5) - void queryClient.invalidateQueries({ queryKey: key }) + void cacheOperations(queryClient).invalidateQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(5) unsubscribe() // unsubscribe to simulate unmount await vi.advanceTimersByTimeAsync(5) @@ -1196,7 +1197,10 @@ describe('query', () => { x = 1 // cancel ongoing re-fetches - void queryClient.refetchQueries({ queryKey: key }, { cancelRefetch: true }) + void cacheOperations(queryClient).refetchQueries( + { queryKey: key }, + { cancelRefetch: true }, + ) // The promise should not reject await vi.advanceTimersByTimeAsync(100) @@ -1227,7 +1231,7 @@ describe('query', () => { ]) await vi.advanceTimersByTimeAsync(10) - void queryClient.invalidateQueries({ queryKey: key }) + void cacheOperations(queryClient).invalidateQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(100) await expect(results).resolves.toStrictEqual([ @@ -1259,9 +1263,9 @@ describe('query', () => { ]) await vi.advanceTimersByTimeAsync(10) - void queryClient.invalidateQueries({ queryKey: key }) + void cacheOperations(queryClient).invalidateQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(10) - void queryClient.invalidateQueries({ queryKey: key }) + void cacheOperations(queryClient).invalidateQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(100) await expect(results).resolves.toStrictEqual([ diff --git a/packages/query-core/src/__tests__/queryCache.test.tsx b/packages/query-core/src/__tests__/queryCache.test.tsx index 06a44f75d00..440662e04a6 100644 --- a/packages/query-core/src/__tests__/queryCache.test.tsx +++ b/packages/query-core/src/__tests__/queryCache.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueryCache, QueryClient, QueryObserver, hashKey, noop } from '..' import type { DefaultError, Query, QueryCacheNotifyEvent } from '..' @@ -248,7 +249,7 @@ describe('queryCache', () => { }) .catch(noop) await vi.advanceTimersByTimeAsync(100) - queryClient.invalidateQueries({ queryKey: key2 }) + cacheOperations(queryClient).invalidateQueries({ queryKey: key2 }) const query1 = queryCache.find({ queryKey: key1 })! const query2 = queryCache.find({ queryKey: key2 })! const query3 = queryCache.find({ queryKey: [{ a: 'a', b: 'b' }] })! diff --git a/packages/query-core/src/__tests__/queryClient.test-d.tsx b/packages/query-core/src/__tests__/queryClient.test-d.tsx index 7b67b229af6..83aec78b0c6 100644 --- a/packages/query-core/src/__tests__/queryClient.test-d.tsx +++ b/packages/query-core/src/__tests__/queryClient.test-d.tsx @@ -1,3 +1,5 @@ +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' +import { selectOption } from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { QueryClient } from '../queryClient' import { skipToken } from '../utils' @@ -80,6 +82,8 @@ const untypedMutationKey = untypedMutationOptions.mutationKey! type SuccessCallback = () => unknown +type CacheOperations = ReturnType> + describe('queryClient', () => { describe('getQueryData', () => { it('should be typed if key is tagged', () => { @@ -284,12 +288,13 @@ describe('queryClient', () => { it('should resolve QueryKey and unknown for a tagged filter', () => { const queryClient = new QueryClient() // TODO: types here are wrong and coming up undefined - const data = queryClient.setQueriesData(typedQueryFilters, { foo: '' }) + const operations = cacheOperations(queryClient) + const data = operations.setQueriesData(typedQueryFilters, { foo: '' }) expectTypeOf(data).toEqualTypeOf>() expectTypeOf< Parameters< - typeof queryClient.setQueriesData + typeof operations.setQueriesData >[1] >().toEqualTypeOf>() }) @@ -297,12 +302,13 @@ describe('queryClient', () => { it('should resolve QueryKey and unknown for an untyped filter', () => { const queryClient = new QueryClient() // TODO: types here are wrong and coming up undefined - const data = queryClient.setQueriesData(untypedQueryFilters, { foo: '' }) + const operations = cacheOperations(queryClient) + const data = operations.setQueriesData(untypedQueryFilters, { foo: '' }) expectTypeOf(data).toEqualTypeOf>() expectTypeOf< Parameters< - typeof queryClient.setQueriesData + typeof operations.setQueriesData >[1] >().toEqualTypeOf>() }) @@ -360,7 +366,7 @@ describe('queryClient', () => { const result = new QueryClient().query({ queryKey: ['key'], queryFn: () => Promise.resolve('string'), - select: (data) => data.length, + [selectOption]: (data) => data.length, }) expectTypeOf(result).toEqualTypeOf>() @@ -370,7 +376,7 @@ describe('queryClient', () => { const result = new QueryClient().query({ queryKey: ['key'], queryFn: skipToken, - select: (data: string) => data.length, + [selectOption]: (data: string) => data.length, }) expectTypeOf(result).toEqualTypeOf>() @@ -404,12 +410,12 @@ describe('queryClient', () => { describe('infiniteQuery', () => { it('should allow passing select option', () => { - const result = new QueryClient().infiniteQuery({ + const result = cacheOperations(new QueryClient()).infiniteQuery({ queryKey: ['key'], queryFn: () => Promise.resolve({ count: 1 }), initialPageParam: 1, getNextPageParam: () => 2, - select: (data) => ({ + [selectOption]: (data) => ({ pages: data.pages.map((x) => `count: ${x.count}`), }), }) @@ -418,7 +424,7 @@ describe('queryClient', () => { }) it('should allow passing pages', async () => { - const result = await new QueryClient().infiniteQuery({ + const result = await cacheOperations(new QueryClient()).infiniteQuery({ queryKey: ['key'], queryFn: () => Promise.resolve({ count: 1 }), getNextPageParam: () => 1, @@ -444,7 +450,11 @@ describe('queryClient', () => { }) it('should allow passing getNextPageParam without pages', () => { - assertType>([ + assertType< + Parameters< + ReturnType>['infiniteQuery'] + > + >([ { queryKey: ['key'], queryFn: () => Promise.resolve({ count: 1 }), @@ -455,7 +465,11 @@ describe('queryClient', () => { }) it('should require getNextPageParam even without pages', () => { - assertType>([ + assertType< + Parameters< + ReturnType>['infiniteQuery'] + > + >([ // @ts-expect-error Property 'getNextPageParam' is missing { queryKey: ['key'], @@ -467,7 +481,7 @@ describe('queryClient', () => { it('should default its page param to unknown', () => { const queryClient = new QueryClient() - const result = queryClient.infiniteQuery({ + const result = cacheOperations(queryClient).infiniteQuery({ queryKey: ['key'], queryFn: () => Promise.resolve('string'), initialPageParam: 1, @@ -478,15 +492,18 @@ describe('queryClient', () => { Promise> >() + const { infiniteQuery } = cacheOperations(queryClient) type PageParam = Parameters< - typeof queryClient.infiniteQuery + typeof infiniteQuery >[0]['initialPageParam'] expectTypeOf().toEqualTypeOf() }) it('should resolve with InfiniteData of the data type', async () => { const queryClient = new QueryClient() - const data = await queryClient.infiniteQuery(typedInfiniteQueryOptions) + const data = await cacheOperations(queryClient).infiniteQuery( + typedInfiniteQueryOptions, + ) expectTypeOf(data).toEqualTypeOf< InfiniteData | undefined @@ -495,7 +512,9 @@ describe('queryClient', () => { it('should resolve with InfiniteData of unknown when untyped', async () => { const queryClient = new QueryClient() - const data = await queryClient.infiniteQuery(untypedInfiniteQueryOptions) + const data = await cacheOperations(queryClient).infiniteQuery( + untypedInfiniteQueryOptions, + ) expectTypeOf(data).toEqualTypeOf< InfiniteData | undefined @@ -505,18 +524,18 @@ describe('queryClient', () => { describe('invalidateQueries', () => { it('should reject a non-array queryKey', () => { - assertType>([]) - assertType>([ + assertType>([]) + assertType>([ { queryKey: ['1'] }, ]) - assertType>([ + assertType>([ // @ts-expect-error { queryKey: '1' }, ]) }) it('should reject an object queryKey (#8684)', () => { - assertType>([ + assertType>([ // @ts-expect-error key is not an array { queryKey: { foo: true } }, ]) @@ -525,7 +544,7 @@ describe('queryClient', () => { it('should type the predicate if the key is tagged', () => { const key = ['key'] as DataTag, number> const queryClient = new QueryClient() - queryClient.invalidateQueries({ + cacheOperations(queryClient).invalidateQueries({ queryKey: key, predicate: (query) => { expectTypeOf(query.state.data).toEqualTypeOf() @@ -538,14 +557,14 @@ describe('queryClient', () => { it('should return a promise of void', () => { const queryClient = new QueryClient() - expectTypeOf(queryClient.invalidateQueries()).toEqualTypeOf< - Promise - >() + expectTypeOf( + cacheOperations(queryClient).invalidateQueries(), + ).toEqualTypeOf>() }) it('should accept a refetchType that QueryFilters does not have', () => { type RefetchType = NonNullable< - Parameters[0] + Parameters[0] >['refetchType'] expectTypeOf().toEqualTypeOf< 'all' | 'active' | 'inactive' | 'none' | undefined @@ -554,7 +573,7 @@ describe('queryClient', () => { it('should accept the refetch options it inherits as its second argument', () => { expectTypeOf< - NonNullable[1]> + NonNullable[1]> >().toEqualTypeOf<{ throwOnError?: boolean cancelRefetch?: boolean @@ -566,7 +585,7 @@ describe('queryClient', () => { it('should type the predicate if the key is tagged', () => { const key = ['key'] as DataTag, number> const queryClient = new QueryClient() - queryClient.cancelQueries({ + cacheOperations(queryClient).cancelQueries({ queryKey: key, predicate: (query) => { expectTypeOf(query.state.data).toEqualTypeOf() @@ -577,13 +596,15 @@ describe('queryClient', () => { }) it('should accept being called without filters', () => { - assertType>([]) + assertType>([]) }) it('should return a promise of void', () => { const queryClient = new QueryClient() - expectTypeOf(queryClient.cancelQueries()).toEqualTypeOf>() + expectTypeOf(cacheOperations(queryClient).cancelQueries()).toEqualTypeOf< + Promise + >() }) }) @@ -591,7 +612,7 @@ describe('queryClient', () => { it('should type the predicate if the key is tagged', () => { const key = ['key'] as DataTag, number> const queryClient = new QueryClient() - queryClient.removeQueries({ + cacheOperations(queryClient).removeQueries({ queryKey: key, predicate: (query) => { expectTypeOf(query.state.data).toEqualTypeOf() @@ -602,13 +623,15 @@ describe('queryClient', () => { }) it('should accept being called without filters', () => { - assertType>([]) + assertType>([]) }) it('should return void', () => { const queryClient = new QueryClient() - expectTypeOf(queryClient.removeQueries()).toEqualTypeOf() + expectTypeOf( + cacheOperations(queryClient).removeQueries(), + ).toEqualTypeOf() }) }) @@ -616,7 +639,7 @@ describe('queryClient', () => { it('should type the predicate if the key is tagged', () => { const key = ['key'] as DataTag, number> const queryClient = new QueryClient() - queryClient.refetchQueries({ + cacheOperations(queryClient).refetchQueries({ queryKey: key, predicate: (query) => { expectTypeOf(query.state.data).toEqualTypeOf() @@ -627,13 +650,15 @@ describe('queryClient', () => { }) it('should accept being called without filters', () => { - assertType>([]) + assertType>([]) }) it('should return a promise of void', () => { const queryClient = new QueryClient() - expectTypeOf(queryClient.refetchQueries()).toEqualTypeOf>() + expectTypeOf(cacheOperations(queryClient).refetchQueries()).toEqualTypeOf< + Promise + >() }) }) @@ -641,7 +666,7 @@ describe('queryClient', () => { it('should type the predicate if the key is tagged', () => { const key = ['key'] as DataTag, number> const queryClient = new QueryClient() - queryClient.resetQueries({ + cacheOperations(queryClient).resetQueries({ queryKey: key, predicate: (query) => { expectTypeOf(query.state.data).toEqualTypeOf() @@ -652,18 +677,20 @@ describe('queryClient', () => { }) it('should accept being called without filters', () => { - assertType>([]) + assertType>([]) }) it('should return a promise of void', () => { const queryClient = new QueryClient() - expectTypeOf(queryClient.resetQueries()).toEqualTypeOf>() + expectTypeOf(cacheOperations(queryClient).resetQueries()).toEqualTypeOf< + Promise + >() }) it('should accept the refetch options it inherits as its second argument', () => { expectTypeOf< - NonNullable[1]> + NonNullable[1]> >().toEqualTypeOf<{ throwOnError?: boolean cancelRefetch?: boolean @@ -800,23 +827,26 @@ describe('queryClient', () => { const queryClient = new QueryClient() expectTypeOf( - queryClient.getQueriesData({ queryKey: ['key'] }), + cacheOperations(queryClient).getQueriesData({ queryKey: ['key'] }), ).toEqualTypeOf>() // @ts-expect-error filters are required - queryClient.getQueriesData() + cacheOperations(queryClient).getQueriesData() }) it('should infer the passed generic as the tuple data', () => { const queryClient = new QueryClient() - const data = queryClient.getQueriesData({ queryKey: ['key'] }) + const data = cacheOperations(queryClient).getQueriesData({ + queryKey: ['key'], + }) expectTypeOf(data).toEqualTypeOf>() }) it('should widen the tuple to the filter key and unknown when tagged', () => { const queryClient = new QueryClient() - const data = queryClient.getQueriesData(typedQueryFilters) + const data = + cacheOperations(queryClient).getQueriesData(typedQueryFilters) expectTypeOf(data).toEqualTypeOf< Array<[ReadonlyArray, unknown]> @@ -825,7 +855,8 @@ describe('queryClient', () => { it('should resolve QueryKey and unknown when untyped', () => { const queryClient = new QueryClient() - const data = queryClient.getQueriesData(untypedQueryFilters) + const data = + cacheOperations(queryClient).getQueriesData(untypedQueryFilters) expectTypeOf(data).toEqualTypeOf>() }) diff --git a/packages/query-core/src/__tests__/queryClient.test.tsx b/packages/query-core/src/__tests__/queryClient.test.tsx index 08f56f1eb9c..a95b2a356a1 100644 --- a/packages/query-core/src/__tests__/queryClient.test.tsx +++ b/packages/query-core/src/__tests__/queryClient.test.tsx @@ -1,4 +1,7 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' +import { selectOption } from '@tanstack/query-test-utils/projection' +import { serialScope } from '@tanstack/query-test-utils/scope' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { CancelledError, @@ -423,7 +426,7 @@ describe('queryClient', () => { queryClient.setQueryData(['key', 1], 1) queryClient.setQueryData(['key', 2], 2) - const result = queryClient.setQueriesData( + const result = cacheOperations(queryClient).setQueriesData( { queryKey: ['key'] }, (old) => (old ? old + 5 : undefined), ) @@ -441,7 +444,7 @@ describe('queryClient', () => { queryClient.setQueryData(['key', 2], 2) const query1 = queryCache.find({ queryKey: ['key', 1] })! - const result = queryClient.setQueriesData( + const result = cacheOperations(queryClient).setQueriesData( { predicate: (query) => query === query1 }, (old) => old! + 5, ) @@ -452,7 +455,7 @@ describe('queryClient', () => { }) it('should not update non existing queries', () => { - const result = queryClient.setQueriesData( + const result = cacheOperations(queryClient).setQueriesData( { queryKey: ['key'] }, 'data', ) @@ -634,7 +637,7 @@ describe('queryClient', () => { pageParams: [0], }) await expect( - queryClient.infiniteQuery({ + cacheOperations(queryClient).infiniteQuery({ queryKey: [key, 'id'], queryFn, staleTime: 'static', @@ -652,7 +655,7 @@ describe('queryClient', () => { ) await expect( - queryClient.infiniteQuery({ + cacheOperations(queryClient).infiniteQuery({ queryKey: [key, 'id'], queryFn, staleTime: 'static', @@ -671,7 +674,9 @@ describe('queryClient', () => { queryClient.setQueryData([key1, 1], 1) queryClient.setQueryData([key1, 2], 2) queryClient.setQueryData([key2, 2], 2) - expect(queryClient.getQueriesData({ queryKey: [key1] })).toStrictEqual([ + expect( + cacheOperations(queryClient).getQueriesData({ queryKey: [key1] }), + ).toStrictEqual([ [[key1, 1], 1], [[key1, 2], 2], ]) @@ -679,7 +684,9 @@ describe('queryClient', () => { it('should return empty array if queries are not found', () => { const key = createKey() - expect(queryClient.getQueriesData({ queryKey: key })).toStrictEqual([]) + expect( + cacheOperations(queryClient).getQueriesData({ queryKey: key }), + ).toStrictEqual([]) }) it('should accept query filters', () => { @@ -687,7 +694,7 @@ describe('queryClient', () => { queryClient.setQueryData(['key', 2], 2) const query1 = queryCache.find({ queryKey: ['key', 1] })! - const result = queryClient.getQueriesData({ + const result = cacheOperations(queryClient).getQueriesData({ predicate: (query) => query === query1, }) @@ -797,7 +804,7 @@ describe('queryClient', () => { // @ts-expect-error enabled is not supported for imperative queries enabled: false, staleTime: 0, - select: (data) => `${data}-selected`, + [selectOption]: (data) => `${data}-selected`, }) expect(result).toBe('fetched-data-selected') expect(queryFn).toHaveBeenCalledTimes(1) @@ -832,7 +839,7 @@ describe('queryClient', () => { queryClient.query({ queryKey: key, queryFn: skipToken, - select, + [selectOption]: select, initialData, }), ).resolves.toBeUndefined() @@ -850,7 +857,7 @@ describe('queryClient', () => { const result = await queryClient.query({ queryKey: key, queryFn: skipToken, - select: (data: unknown) => (data as string).length, + [selectOption]: (data: unknown) => (data as string).length, }) expect(result).toBe('cached-data'.length) }) @@ -921,7 +928,7 @@ describe('queryClient', () => { expect(first.data).toBe('data') expect(fetchFn).toHaveBeenCalledTimes(1) - await queryClient.invalidateQueries({ + await cacheOperations(queryClient).invalidateQueries({ queryKey: key, refetchType: 'none', }) @@ -1101,7 +1108,7 @@ describe('queryClient', () => { queryKey: key, queryFn, staleTime: Infinity, - select: (data) => `${data}-selected`, + [selectOption]: (data) => `${data}-selected`, }) expect(result).toBe('cached-data-selected') expect(queryFn).not.toHaveBeenCalled() @@ -1116,7 +1123,7 @@ describe('queryClient', () => { const result = await queryClient.query({ queryKey: key, queryFn, - select: (data) => data.value.toUpperCase(), + [selectOption]: (data) => data.value.toUpperCase(), }) expect(result).toBe('FETCHED-DATA') expect(queryFn).toHaveBeenCalledTimes(1) @@ -1138,7 +1145,7 @@ describe('queryClient', () => { Promise.resolve(data.pages[0]) await expect( - queryClient.infiniteQuery< + cacheOperations(queryClient).infiniteQuery< StrictData, any, StrictData, @@ -1155,7 +1162,7 @@ describe('queryClient', () => { it('should return infinite query data', async () => { const key = createKey() - const result = await queryClient.infiniteQuery({ + const result = await cacheOperations(queryClient).infiniteQuery({ queryKey: key, getNextPageParam: () => undefined, initialPageParam: 10, @@ -1179,7 +1186,7 @@ describe('queryClient', () => { >(({ pageParam }: { pageParam: number }) => Promise.resolve(pageParam)) await expect( - queryClient.infiniteQuery({ + cacheOperations(queryClient).infiniteQuery({ queryKey: key, queryFn, getNextPageParam: () => undefined, @@ -1205,14 +1212,14 @@ describe('queryClient', () => { pageParams: [0], }) - const result = await queryClient.infiniteQuery({ + const result = await cacheOperations(queryClient).infiniteQuery({ queryKey: key, queryFn, getNextPageParam: () => undefined, initialPageParam: 0, // @ts-expect-error enabled is not supported for imperative queries enabled: false, - select: (data) => data.pages.map((page) => `${page}-selected`), + [selectOption]: (data) => data.pages.map((page) => `${page}-selected`), }) expect(result).toStrictEqual(["'fetched-0-selected"]) expect(queryFn).toHaveBeenCalledTimes(1) @@ -1226,7 +1233,7 @@ describe('queryClient', () => { pageParams: [0], }) - const result = await queryClient.infiniteQuery({ + const result = await cacheOperations(queryClient).infiniteQuery({ queryKey: key, queryFn: skipToken, getNextPageParam: () => undefined, @@ -1245,12 +1252,12 @@ describe('queryClient', () => { ) await expect( - queryClient.infiniteQuery({ + cacheOperations(queryClient).infiniteQuery({ queryKey: key, queryFn: skipToken, getNextPageParam: () => undefined, initialPageParam: 0, - select, + [selectOption]: select, }), ).resolves.toBeUndefined() @@ -1289,7 +1296,7 @@ describe('queryClient', () => { return query.state.data?.pages[0]?.staleTime ?? 0 } - const result = await queryClient.infiniteQuery({ + const result = await cacheOperations(queryClient).infiniteQuery({ queryKey: key, queryFn, getNextPageParam: () => undefined, @@ -1312,7 +1319,7 @@ describe('queryClient', () => { >(({ pageParam }: { pageParam: number }) => Promise.resolve({ value: `fetched-${String(pageParam)}` }), ) - const first = await queryClient.infiniteQuery({ + const first = await cacheOperations(queryClient).infiniteQuery({ queryKey: key, queryFn, getNextPageParam: () => undefined, @@ -1325,12 +1332,12 @@ describe('queryClient', () => { }) expect(queryFn).toHaveBeenCalledTimes(1) - await queryClient.invalidateQueries({ + await cacheOperations(queryClient).invalidateQueries({ queryKey: key, refetchType: 'none', }) - const second = await queryClient.infiniteQuery({ + const second = await cacheOperations(queryClient).infiniteQuery({ queryKey: key, queryFn, getNextPageParam: () => undefined, @@ -1344,12 +1351,12 @@ describe('queryClient', () => { it('should apply select to infinite query data', async () => { const key = createKey() - const result = await queryClient.infiniteQuery({ + const result = await cacheOperations(queryClient).infiniteQuery({ queryKey: key, getNextPageParam: () => undefined, initialPageParam: 10, queryFn: ({ pageParam }) => Number(pageParam), - select: (data) => data.pages.map((page) => page * 2), + [selectOption]: (data) => data.pages.map((page) => page * 2), }) expect(result).toStrictEqual([20]) }) @@ -1364,7 +1371,7 @@ describe('queryClient', () => { const fetchFn: QueryFunction = () => Promise.resolve('data') - await queryClient + await cacheOperations(queryClient) .infiniteQuery({ queryKey: key, queryFn: fetchFn, @@ -1384,7 +1391,7 @@ describe('queryClient', () => { it('should return infinite query data', async () => { const key = createKey() - await queryClient + await cacheOperations(queryClient) .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => Number(pageParam), @@ -1404,7 +1411,7 @@ describe('queryClient', () => { it('should prefetch multiple pages', async () => { const key = createKey() - await queryClient + await cacheOperations(queryClient) .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => String(pageParam), @@ -1427,7 +1434,7 @@ describe('queryClient', () => { const key = createKey() let count = 0 - await queryClient + await cacheOperations(queryClient) .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => String(pageParam), @@ -1516,7 +1523,10 @@ describe('queryClient', () => { // check the error doesn't occur expect(() => - queryClient.removeQueries({ queryKey: key, exact: true }), + cacheOperations(queryClient).removeQueries({ + queryKey: key, + exact: true, + }), ).not.toThrow() // check query was successful removed @@ -1535,7 +1545,7 @@ describe('queryClient', () => { }) await vi.advanceTimersByTimeAsync(10) - await queryClient.cancelQueries() + await cacheOperations(queryClient).cancelQueries() // with previous data present, imperative fetch should resolve to that data after cancel await expect(pending).resolves.toBe('data') @@ -1560,7 +1570,10 @@ describe('queryClient', () => { }) .catch(noop) await vi.advanceTimersByTimeAsync(10) - await queryClient.cancelQueries({ queryKey: key1 }, { revert: false }) + await cacheOperations(queryClient).cancelQueries( + { queryKey: key1 }, + { revert: false }, + ) const state1 = queryClient.getQueryState(key1) expect(state1).toMatchObject({ status: 'error', @@ -1576,7 +1589,7 @@ describe('queryClient', () => { }) await vi.advanceTimersByTimeAsync(10) - await queryClient.cancelQueries({ queryKey: key }) + await cacheOperations(queryClient).cancelQueries({ queryKey: key }) // we have to reject here because we can't resolve with `undefined` // the alternative would be a never-ending promise @@ -1605,7 +1618,7 @@ describe('queryClient', () => { enabled: false, }) observer1.subscribe(() => undefined) - await queryClient.refetchQueries() + await cacheOperations(queryClient).refetchQueries() observer1.destroy() expect(queryFn).toHaveBeenCalledTimes(1) }) @@ -1628,7 +1641,7 @@ describe('queryClient', () => { }) observer1.subscribe(() => undefined) observer2.subscribe(() => undefined) - await queryClient.refetchQueries() + await cacheOperations(queryClient).refetchQueries() observer1.destroy() observer2.destroy() expect(queryFn).toHaveBeenCalledTimes(2) @@ -1659,7 +1672,7 @@ describe('queryClient', () => { }) observer1.subscribe(() => undefined) observer2.subscribe(() => undefined) - await queryClient.refetchQueries() + await cacheOperations(queryClient).refetchQueries() observer1.destroy() observer2.destroy() expect(queryFn1).toHaveBeenCalledTimes(2) @@ -1683,7 +1696,10 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - await queryClient.refetchQueries({ type: 'active', stale: false }) + await cacheOperations(queryClient).refetchQueries({ + type: 'active', + stale: false, + }) unsubscribe() expect(queryFn1).toHaveBeenCalledTimes(2) expect(queryFn2).toHaveBeenCalledTimes(1) @@ -1705,8 +1721,8 @@ describe('queryClient', () => { queryFn: queryFn1, }) const unsubscribe = observer.subscribe(() => undefined) - queryClient.invalidateQueries({ queryKey: key1 }) - await queryClient.refetchQueries({ stale: true }) + cacheOperations(queryClient).invalidateQueries({ queryKey: key1 }) + await cacheOperations(queryClient).refetchQueries({ stale: true }) unsubscribe() // query, observer mount, invalidation (cancels observer mount) and refetch expect(queryFn1).toHaveBeenCalledTimes(4) @@ -1724,13 +1740,13 @@ describe('queryClient', () => { .mockReturnValue('data2') await queryClient.query({ queryKey: key1, queryFn: queryFn1 }) await queryClient.query({ queryKey: key2, queryFn: queryFn2 }) - queryClient.invalidateQueries({ queryKey: key1 }) + cacheOperations(queryClient).invalidateQueries({ queryKey: key1 }) const observer = new QueryObserver(queryClient, { queryKey: key1, queryFn: queryFn1, }) const unsubscribe = observer.subscribe(() => undefined) - await queryClient.refetchQueries( + await cacheOperations(queryClient).refetchQueries( { type: 'active', stale: true }, { cancelRefetch: false }, ) @@ -1739,7 +1755,7 @@ describe('queryClient', () => { expect(queryFn2).toHaveBeenCalledTimes(1) }) - it('should be able to refetch all active and inactive queries (queryClient.refetchQueries()', async () => { + it('should be able to refetch all active and inactive queries (cacheOperations(queryClient).refetchQueries()', async () => { const key1 = createKey() const key2 = createKey() const queryFn1 = vi @@ -1756,13 +1772,13 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - await queryClient.refetchQueries() + await cacheOperations(queryClient).refetchQueries() unsubscribe() expect(queryFn1).toHaveBeenCalledTimes(2) expect(queryFn2).toHaveBeenCalledTimes(2) }) - it('should be able to refetch all active and inactive queries (queryClient.refetchQueries({ type: "all" }))', async () => { + it('should be able to refetch all active and inactive queries (cacheOperations(queryClient).refetchQueries({ type: "all" }))', async () => { const key1 = createKey() const key2 = createKey() const queryFn1 = vi @@ -1779,7 +1795,7 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - await queryClient.refetchQueries({ type: 'all' }) + await cacheOperations(queryClient).refetchQueries({ type: 'all' }) unsubscribe() expect(queryFn1).toHaveBeenCalledTimes(2) expect(queryFn2).toHaveBeenCalledTimes(2) @@ -1802,7 +1818,7 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - await queryClient.refetchQueries({ type: 'active' }) + await cacheOperations(queryClient).refetchQueries({ type: 'active' }) unsubscribe() expect(queryFn1).toHaveBeenCalledTimes(2) expect(queryFn2).toHaveBeenCalledTimes(1) @@ -1825,7 +1841,7 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - await queryClient.refetchQueries({ type: 'inactive' }) + await cacheOperations(queryClient).refetchQueries({ type: 'inactive' }) unsubscribe() expect(queryFn1).toHaveBeenCalledTimes(1) expect(queryFn2).toHaveBeenCalledTimes(2) @@ -1843,7 +1859,7 @@ describe('queryClient', () => { } catch {} let error: any try { - await queryClient.refetchQueries( + await cacheOperations(queryClient).refetchQueries( { queryKey: key1 }, { throwOnError: true }, ) @@ -1861,7 +1877,7 @@ describe('queryClient', () => { await queryClient.query({ queryKey: key1, queryFn: queryFn1 }) mockOnlineManagerIsOnline(false) - await queryClient.refetchQueries({ queryKey: key1 }) + await cacheOperations(queryClient).refetchQueries({ queryKey: key1 }) // if we reach this point, the test succeeds because the Promise was resolved immediately expect(queryFn1).toHaveBeenCalledTimes(1) @@ -1880,7 +1896,7 @@ describe('queryClient', () => { await queryClient.query({ queryKey: key1, queryFn: () => 'data1' }) mockOnlineManagerIsOnline(false) - await queryClient.refetchQueries( + await cacheOperations(queryClient).refetchQueries( { queryKey: key1 }, { throwOnError: true }, ) @@ -1901,7 +1917,7 @@ describe('queryClient', () => { await queryClient.query({ queryKey: key1, queryFn: queryFn1 }) mockOnlineManagerIsOnline(false) - await queryClient.refetchQueries({ queryKey: key1 }) + await cacheOperations(queryClient).refetchQueries({ queryKey: key1 }) // initial fetch + refetch (even though we are offline) expect(queryFn1).toHaveBeenCalledTimes(2) @@ -1919,7 +1935,7 @@ describe('queryClient', () => { staleTime: 'static', }) const unsubscribe = observer.subscribe(() => undefined) - await queryClient.refetchQueries() + await cacheOperations(queryClient).refetchQueries() expect(queryFn).toHaveBeenCalledTimes(1) unsubscribe() @@ -1944,7 +1960,7 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - queryClient.invalidateQueries({ queryKey: key1 }) + cacheOperations(queryClient).invalidateQueries({ queryKey: key1 }) unsubscribe() expect(queryFn1).toHaveBeenCalledTimes(2) expect(queryFn2).toHaveBeenCalledTimes(1) @@ -1968,7 +1984,7 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - queryClient.invalidateQueries({ queryKey: key1 }) + cacheOperations(queryClient).invalidateQueries({ queryKey: key1 }) unsubscribe() expect(queryFn1).toHaveBeenCalledTimes(1) expect(queryFn2).toHaveBeenCalledTimes(1) @@ -1991,7 +2007,7 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - queryClient.invalidateQueries({ + cacheOperations(queryClient).invalidateQueries({ queryKey: key1, refetchType: 'none', }) @@ -2020,7 +2036,7 @@ describe('queryClient', () => { const unsubscribe = observer.subscribe(() => undefined) unsubscribe() - await queryClient.invalidateQueries({ + await cacheOperations(queryClient).invalidateQueries({ queryKey: key1, refetchType: 'inactive', }) @@ -2045,7 +2061,7 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - queryClient.invalidateQueries({ + cacheOperations(queryClient).invalidateQueries({ refetchType: 'all', }) unsubscribe() @@ -2065,7 +2081,7 @@ describe('queryClient', () => { }) const unsubscribe = observer.subscribe(() => undefined) unsubscribe() - await queryClient.invalidateQueries({ + await cacheOperations(queryClient).invalidateQueries({ refetchType: 'all', }) expect(queryFn).toHaveBeenCalledTimes(0) @@ -2085,7 +2101,7 @@ describe('queryClient', () => { unsubscribe() expect(queryClient.getQueryState(key)?.dataUpdateCount).toBe(1) - await queryClient.invalidateQueries({ + await cacheOperations(queryClient).invalidateQueries({ refetchType: 'all', }) expect(queryClient.getQueryState(key)?.dataUpdateCount).toBe(1) @@ -2107,7 +2123,7 @@ describe('queryClient', () => { }) observer.subscribe(() => undefined) - queryClient.refetchQueries() + cacheOperations(queryClient).refetchQueries() await vi.advanceTimersByTimeAsync(10) observer.destroy() expect(abortFn).toHaveBeenCalledTimes(1) @@ -2131,7 +2147,9 @@ describe('queryClient', () => { }) observer.subscribe(() => undefined) - queryClient.refetchQueries(undefined, { cancelRefetch: false }) + cacheOperations(queryClient).refetchQueries(undefined, { + cancelRefetch: false, + }) await vi.advanceTimersByTimeAsync(10) observer.destroy() expect(abortFn).toHaveBeenCalledTimes(0) @@ -2155,7 +2173,7 @@ describe('queryClient', () => { expect(queryFn).toHaveBeenCalledTimes(1) expect(queryClient.getQueryState(key)?.status).toBe('error') - await queryClient.invalidateQueries({ queryKey: key }) + await cacheOperations(queryClient).invalidateQueries({ queryKey: key }) expect(queryFn).toHaveBeenCalledTimes(2) expect(queryClient.getQueryData(key)).toBe('data') @@ -2174,7 +2192,7 @@ describe('queryClient', () => { staleTime: 'static', }) const unsubscribe = observer.subscribe(() => undefined) - await queryClient.invalidateQueries() + await cacheOperations(queryClient).invalidateQueries() expect(queryFn).toHaveBeenCalledTimes(1) unsubscribe() @@ -2195,7 +2213,7 @@ describe('queryClient', () => { const unsubscribe = observer.subscribe(noop) expect(queryFn).toHaveBeenCalledTimes(1) - await queryClient.resetQueries({ queryKey: key }) + await cacheOperations(queryClient).resetQueries({ queryKey: key }) expect(queryFn).toHaveBeenCalledTimes(2) expect(queryClient.getQueryData(key)).toBe('data') @@ -2214,7 +2232,7 @@ describe('queryClient', () => { const unsubscribe = observer.subscribe(noop) queryClient.setQueryData(key, 2) - await queryClient.resetQueries({ queryKey: key }) + await cacheOperations(queryClient).resetQueries({ queryKey: key }) expect(queryFn).not.toHaveBeenCalled() expect(queryClient.getQueryData(key)).toBe(0) @@ -2232,7 +2250,7 @@ describe('queryClient', () => { queryCache.subscribe(callback) - queryClient.resetQueries({ queryKey: key }) + cacheOperations(queryClient).resetQueries({ queryKey: key }) const query = queryCache.find({ queryKey: key }) expect(callback).toHaveBeenNthCalledWith( @@ -2256,7 +2274,7 @@ describe('queryClient', () => { expect(state?.data).toBe('data') expect(state?.status).toBe('success') - queryClient.resetQueries({ queryKey: key }) + cacheOperations(queryClient).resetQueries({ queryKey: key }) state = queryClient.getQueryState(key) @@ -2279,7 +2297,7 @@ describe('queryClient', () => { let state = queryClient.getQueryState(key) expect(state?.data).toBe('data') - queryClient.resetQueries({ queryKey: key }) + cacheOperations(queryClient).resetQueries({ queryKey: key }) state = queryClient.getQueryState(key) @@ -2309,7 +2327,7 @@ describe('queryClient', () => { }) const unsubscribe = observer.subscribe(() => undefined) - await queryClient.resetQueries({ + await cacheOperations(queryClient).resetQueries({ predicate: (query) => query.state.status === 'error', }) expect(queryFn).toHaveBeenCalledTimes(2) @@ -2346,7 +2364,7 @@ describe('queryClient', () => { observer1.subscribe(() => undefined) observer2.subscribe(() => undefined) observer3.subscribe(() => (didSkipTokenRun = true)) - await queryClient.resetQueries() + await cacheOperations(queryClient).resetQueries() observer3.destroy() observer2.destroy() observer1.destroy() @@ -2487,9 +2505,7 @@ describe('queryClient', () => { const orders: Array = [] const observer1 = new MutationObserver(queryClient, { - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { orders.push('1start') await sleep(50) @@ -2499,9 +2515,7 @@ describe('queryClient', () => { }) const observer2 = new MutationObserver(queryClient, { - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { orders.push('2start') await sleep(20) @@ -2621,9 +2635,7 @@ describe('queryClient', () => { void observer.mutate() const observer2 = new MutationObserver(queryClient, { - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('mutation2-start') await sleep(50) @@ -2635,9 +2647,7 @@ describe('queryClient', () => { void observer2.mutate() const observer3 = new MutationObserver(queryClient, { - scope: { - id: 'scope', - }, + scope: serialScope('scope'), mutationFn: async () => { results.push('mutation3-start') await sleep(50) diff --git a/packages/query-core/src/__tests__/queryObserver.test-d.tsx b/packages/query-core/src/__tests__/queryObserver.test-d.tsx index d85a714f5e0..4ac993c7f0a 100644 --- a/packages/query-core/src/__tests__/queryObserver.test-d.tsx +++ b/packages/query-core/src/__tests__/queryObserver.test-d.tsx @@ -1,5 +1,10 @@ import { createKey } from '@tanstack/query-test-utils' import { refetchInterval } from '@tanstack/query-test-utils/polling' +import { + placeholderOption, + projectionInput, + selectOption, +} from '@tanstack/query-test-utils/projection' import { afterEach, assertType, @@ -10,6 +15,7 @@ import { } from 'vitest' import { QueryClient, QueryObserver, defaultQueryFn } from '..' import type { IntervalInput } from '@tanstack/query-test-utils/polling' +import type { ProjectionInput } from '@tanstack/query-test-utils/projection' import type { DefaultError, DefinedQueryObserverResult, @@ -71,7 +77,7 @@ describe('queryObserver', () => { it('should derive its remaining type parameters from the data type', () => { expectTypeOf< - QueryObserverOptions<{ value: string }>['select'] + ProjectionInput['select']> >().toEqualTypeOf< ((data: { value: string }) => { value: string }) | undefined >() @@ -476,7 +482,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: createKey(), queryFn: () => Promise.resolve({ count: 1 }), - select: (data) => data.count, + [selectOption]: (data) => data.count, }) expectTypeOf(observer.getCurrentResult().data).toEqualTypeOf< @@ -488,7 +494,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: createKey(), queryFn: () => ({ count: 1 }), - select: (data) => ({ myCount: data.count }), + [selectOption]: (data) => ({ myCount: data.count }), }) observer.subscribe((result) => { @@ -502,7 +508,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: createKey(), queryFn: () => ({ count: 1 }), - select: (data) => ({ myCount: data.count }), + [selectOption]: (data) => ({ myCount: data.count }), }) const observerResult = await observer.refetch() @@ -516,8 +522,8 @@ describe('queryObserver', () => { new QueryObserver(queryClient, { queryKey: createKey(), queryFn: () => Promise.resolve({ count: 1 }), - select: (data) => data.count, - placeholderData: (previousData) => { + [selectOption]: (data) => data.count, + [placeholderOption]: (previousData) => { expectTypeOf(previousData).toEqualTypeOf< { count: number } | undefined >() @@ -532,12 +538,14 @@ describe('queryObserver', () => { }) expectTypeOf< - QueryObserverOptions< - { count: number }, - DefaultError, - number, - { count: number } - >['placeholderData'] + ProjectionInput< + QueryObserverOptions< + { count: number }, + DefaultError, + number, + { count: number } + >['placeholderData'] + > >() .extract<(...args: Array) => any>() .parameter(0) @@ -582,12 +590,14 @@ describe('queryObserver', () => { new QueryObserver(queryClient, { queryKey: createKey(), queryFn: () => Promise.resolve({ value: 'data' }), - placeholderData: { value: 'placeholder' }, + [placeholderOption]: { value: 'placeholder' }, }) expectTypeOf< Exclude< - QueryObserverOptions<{ value: string }>['placeholderData'], + ProjectionInput< + QueryObserverOptions<{ value: string }>['placeholderData'] + >, (...args: Array) => any > >().toEqualTypeOf<{ value: string } | undefined>() @@ -599,7 +609,7 @@ describe('queryObserver', () => { new QueryObserver(queryClient, { queryKey: testQueryKey, queryFn: defaultQueryFn, - placeholderData: (_, previousQuery) => { + [placeholderOption]: (_, previousQuery) => { if (previousQuery) { expectTypeOf(previousQuery.queryKey).toEqualTypeOf< typeof testQueryKey @@ -613,7 +623,7 @@ describe('queryObserver', () => { new QueryObserver(queryClient, { queryKey: createKey(), queryFn: defaultQueryFn, - placeholderData: (_, previousQuery) => { + [placeholderOption]: (_, previousQuery) => { if (previousQuery) { expectTypeOf( previousQuery.state.error, @@ -630,8 +640,8 @@ describe('queryObserver', () => { new QueryObserver(queryClient, { queryKey: createKey(), queryFn: () => queryData, - select: (data) => data.foo, - placeholderData: (previousData) => { + [selectOption]: (data) => data.foo, + [placeholderOption]: (previousData) => { expectTypeOf(previousData).toEqualTypeOf< typeof queryData | undefined >() @@ -1443,7 +1453,7 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: createKey(), queryFn: () => Promise.resolve({ value: 'data' }), - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf<{ value: string }>() return data }, @@ -1475,7 +1485,7 @@ describe('queryObserver', () => { >() .parameter(0) .toEqualTypeOf() - expectTypeOf(observer.options.select).toEqualTypeOf< + expectTypeOf(projectionInput(observer.options.select)).toEqualTypeOf< ((data: { value: string }) => { value: string }) | undefined >() }) @@ -1597,7 +1607,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: createKey(), queryFn: () => Promise.resolve({ count: 1 }), - select: (data) => data.count, + [selectOption]: (data) => data.count, }) expectTypeOf(observer.getCurrentQuery().state.data).toEqualTypeOf< @@ -1768,12 +1778,13 @@ describe('queryObserver', () => { Promise> >() - expectTypeOf(observer.fetchOptimistic) - .parameter(0) - .toHaveProperty('select') - .toEqualTypeOf< - ((data: { value: string }) => { value: string }) | undefined - >() + expectTypeOf< + ProjectionInput< + Parameters[0]['select'] + > + >().toEqualTypeOf< + ((data: { value: string }) => { value: string }) | undefined + >() }) }) diff --git a/packages/query-core/src/__tests__/queryObserver.test.tsx b/packages/query-core/src/__tests__/queryObserver.test.tsx index dad6075c650..6d78c46a24f 100644 --- a/packages/query-core/src/__tests__/queryObserver.test.tsx +++ b/packages/query-core/src/__tests__/queryObserver.test.tsx @@ -1,5 +1,10 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { refetchInterval } from '@tanstack/query-test-utils/polling' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueryClient, @@ -38,7 +43,7 @@ describe('queryObserver', () => { queryKey, queryFn: defaultQueryFn, enabled: false, - select: () => { + [selectOption]: () => { throw new Error('selection failed') }, } as const @@ -153,7 +158,10 @@ describe('queryObserver', () => { it('should not be re-fetched when invalidated with refetchType: all', async () => { const unsubscribe = observer.subscribe(vi.fn()) - queryClient.invalidateQueries({ queryKey: key, refetchType: 'all' }) + cacheOperations(queryClient).invalidateQueries({ + queryKey: key, + refetchType: 'all', + }) // So we still expect it to not have fetched and not be fetching expect(count).toBe(0) @@ -223,7 +231,10 @@ describe('queryObserver', () => { unsubscribe() - queryClient.invalidateQueries({ queryKey: key, refetchType: 'active' }) + cacheOperations(queryClient).invalidateQueries({ + queryKey: key, + refetchType: 'active', + }) expect(observer.getCurrentResult()).toMatchObject({ status: 'pending', fetchStatus: 'idle', @@ -238,7 +249,10 @@ describe('queryObserver', () => { // Toggle enabled enabled = true - queryClient.invalidateQueries({ queryKey: key, refetchType: 'active' }) + cacheOperations(queryClient).invalidateQueries({ + queryKey: key, + refetchType: 'active', + }) expect(observer.getCurrentResult()).toMatchObject({ status: 'pending', fetchStatus: 'fetching', @@ -256,13 +270,19 @@ describe('queryObserver', () => { // Toggle enabled enabled = true - queryClient.invalidateQueries({ queryKey: key, refetchType: 'inactive' }) + cacheOperations(queryClient).invalidateQueries({ + queryKey: key, + refetchType: 'inactive', + }) // should not refetch since it was active and we only refetch inactive await vi.advanceTimersByTimeAsync(10) expect(count).toBe(0) - queryClient.invalidateQueries({ queryKey: key, refetchType: 'active' }) + cacheOperations(queryClient).invalidateQueries({ + queryKey: key, + refetchType: 'active', + }) // should refetch since it was active and we refetch active await vi.advanceTimersByTimeAsync(10) @@ -272,7 +292,10 @@ describe('queryObserver', () => { enabled = false // should not refetch since it is not active and we only refetch active - queryClient.invalidateQueries({ queryKey: key, refetchType: 'active' }) + cacheOperations(queryClient).invalidateQueries({ + queryKey: key, + refetchType: 'active', + }) await vi.advanceTimersByTimeAsync(10) expect(count).toBe(1) @@ -344,7 +367,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => ({ count: 1 }), - select: (data) => ({ myCount: data.count }), + [selectOption]: (data) => ({ myCount: data.count }), }) let observerResult const unsubscribe = observer.subscribe((result) => { @@ -360,7 +383,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => ({ count: 1 }), - select: (data) => ({ myCount: data.count }), + [selectOption]: (data) => ({ myCount: data.count }), }) const observerResult = await observer.refetch() expect(observerResult.data).toMatchObject({ myCount: 1 }) @@ -371,7 +394,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => ({ count: 1 }), - select: (data) => ({ myCount: data.count }), + [selectOption]: (data) => ({ myCount: data.count }), }) let observerResult const unsubscribe = observer.subscribe((result) => { @@ -388,7 +411,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => ({ count }), - select: (data) => { + [selectOption]: (data) => { count++ return { myCount: data.count } }, @@ -416,7 +439,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn, - select: select1, + [selectOption]: select1, }) const unsubscribe = observer.subscribe((result) => { results.push(result) @@ -425,7 +448,7 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: key, queryFn, - select: select2, + [selectOption]: select2, }) await observer.refetch() unsubscribe() @@ -470,7 +493,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn, - select, + [selectOption]: select, }) const unsubscribe = observer.subscribe((result) => { results.push(result) @@ -479,7 +502,7 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: key, queryFn, - select, + [selectOption]: select, }) await observer.refetch() unsubscribe() @@ -513,7 +536,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => ({ count: 1 }), - select: (data) => { + [selectOption]: (data) => { count++ return { myCount: data.count } }, @@ -532,7 +555,7 @@ describe('queryObserver', () => { queryFn: defaultQueryFn, initialData: 'data', enabled: false, - select: () => { + [selectOption]: () => { throw error }, }) @@ -553,7 +576,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn, - select: () => { + [selectOption]: () => { throw new Error('selector error') }, }) @@ -592,8 +615,8 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn, - placeholderData: { count: 0 }, - select: () => { + [placeholderOption]: { count: 0 }, + [selectOption]: () => { throw new Error('selector error') }, }) @@ -614,7 +637,7 @@ describe('queryObserver', () => { queryKey: key, retry: 0, queryFn: () => sleep(10).then(() => (shouldError ? 2 : 1)), - select: (num) => { + [selectOption]: (num) => { if (shouldError) { throw error } @@ -663,7 +686,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key1, queryFn: () => sleep(10).then(() => ({ count: 1 })), - select: (): { count: number } => { + [selectOption]: (): { count: number } => { throw new Error('selector error') }, }) @@ -676,7 +699,7 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: key2, queryFn: () => sleep(10).then(() => ({ count: 2 })), - select: (data) => data, + [selectOption]: (data) => data, }) expect(observer.getCurrentResult()).toMatchObject({ status: 'pending', @@ -700,8 +723,8 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: keyA, queryFn: () => sleep(10).then(() => ({ count: 1 })), - placeholderData: placeholder, - select: (data) => ({ selected: data.count }), + [placeholderOption]: placeholder, + [selectOption]: (data) => ({ selected: data.count }), }) const unsubscribe = observer.subscribe(() => {}) await vi.advanceTimersByTimeAsync(10) @@ -713,8 +736,8 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: keyB, queryFn: () => sleep(10).then(() => ({ count: 2 })), - placeholderData: placeholder, - select: (): { selected: number } => { + [placeholderOption]: placeholder, + [selectOption]: (): { selected: number } => { throw new Error('selector error') }, }) @@ -725,8 +748,8 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: keyC, queryFn: () => sleep(10).then(() => ({ count: 3 })), - placeholderData: placeholder, - select: (data) => ({ selected: data.count }), + [placeholderOption]: placeholder, + [selectOption]: (data) => ({ selected: data.count }), }) expect(observer.getCurrentResult()).toMatchObject({ status: 'success', @@ -749,7 +772,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => sleep(10).then(() => ({ count: 1 })), - select: (data): { count: number } => { + [selectOption]: (data): { count: number } => { if (shouldThrow) { throw new Error('selector error') } @@ -763,7 +786,7 @@ describe('queryObserver', () => { }) shouldThrow = false - queryClient.resetQueries({ queryKey: key }) + cacheOperations(queryClient).resetQueries({ queryKey: key }) expect(observer.getCurrentResult()).toMatchObject({ status: 'pending', data: undefined, @@ -784,7 +807,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => ({ count: ++count }), - select: () => ({ myCount: 1 }), + [selectOption]: () => ({ myCount: 1 }), }) const observerResult1 = await observer.refetch() const observerResult2 = await observer.refetch() @@ -1040,7 +1063,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => 'data', - placeholderData: 'placeholder', + [placeholderOption]: 'placeholder', }) expect(observer.getCurrentResult()).toMatchObject({ @@ -1067,7 +1090,7 @@ describe('queryObserver', () => { queryKey: key, enabled: false, queryFn: () => 'data', - placeholderData: {}, + [placeholderOption]: {}, }) const firstData = observer.getCurrentResult().data @@ -1075,7 +1098,7 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: key, queryFn: defaultQueryFn, - placeholderData: {}, + [placeholderOption]: {}, }) const secondData = observer.getCurrentResult().data @@ -1159,7 +1182,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => data, - select: () => data, + [selectOption]: () => data, }) const unsubscribe = observer.subscribe(() => undefined) @@ -1170,7 +1193,7 @@ describe('queryObserver', () => { queryKey: key, queryFn: () => data, structuralSharing: false, - select: () => selectedData, + [selectOption]: () => selectedData, }) await observer.refetch() @@ -1191,25 +1214,25 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => data, - select: () => data, + [selectOption]: () => data, }) observer.setOptions({ queryKey: key, queryFn: () => data, - select: () => { + [selectOption]: () => { return selectedData1 }, - placeholderData: placeholderData1, + [placeholderOption]: placeholderData1, }) observer.setOptions({ queryKey: key, queryFn: () => data, - select: () => { + [selectOption]: () => { return selectedData2 }, - placeholderData: placeholderData2, + [placeholderOption]: placeholderData2, structuralSharing: false, }) expect(observer.getCurrentResult().data).toBe(selectedData2) @@ -1228,11 +1251,11 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key1, queryFn: () => data1, - placeholderData: (prev, prevQuery) => { + [placeholderOption]: (prev, prevQuery) => { keys.push(prevQuery?.queryKey || null) return prev }, - select: (data) => data.value, + [selectOption]: (data) => data.value, }) const unsubscribe = observer.subscribe((result) => { @@ -1243,11 +1266,11 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: key2, queryFn: () => data2, - placeholderData: (prev, prevQuery) => { + [placeholderOption]: (prev, prevQuery) => { keys.push(prevQuery?.queryKey || null) return prev }, - select: (data) => data.value, + [selectOption]: (data) => data.value, }) await vi.advanceTimersByTimeAsync(0) unsubscribe() @@ -1293,8 +1316,8 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key1, queryFn: () => data1, - placeholderData: (prev) => prev, - select: (data) => { + [placeholderOption]: (prev) => prev, + [selectOption]: (data) => { selectCount++ return data.value }, @@ -1308,8 +1331,8 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: key2, queryFn: () => data2, - placeholderData: (prev) => prev, - select: (data) => { + [placeholderOption]: (prev) => prev, + [selectOption]: (data) => { selectCount++ return data.value }, @@ -1359,8 +1382,8 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, { queryKey: key1, queryFn: () => data1, - placeholderData: (prev) => prev, - select: stableSelect, + [placeholderOption]: (prev) => prev, + [selectOption]: stableSelect, }) const unsubscribe = observer.subscribe((result) => { @@ -1371,8 +1394,8 @@ describe('queryObserver', () => { observer.setOptions({ queryKey: key2, queryFn: () => data2, - placeholderData: (prev) => prev, - select: stableSelect, + [placeholderOption]: (prev) => prev, + [selectOption]: stableSelect, }) await vi.advanceTimersByTimeAsync(0) unsubscribe() @@ -1679,7 +1702,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, options) const unsubscribe = observer.subscribe(noop) - queryClient.removeQueries({ queryKey: key }) + cacheOperations(queryClient).removeQueries({ queryKey: key }) // Broadcast can recreate the query without a queryFn before the observer updates. queryClient.getQueryCache().build(queryClient, { queryKey: key, @@ -2062,8 +2085,9 @@ describe('queryObserver', () => { queryKey: [...key, id], queryFn: () => [id], enabled: id !== '', - placeholderData: keepPreviousData, - select: (items: Array) => items.find((item) => item === id), + [placeholderOption]: keepPreviousData, + [selectOption]: (items: Array) => + items.find((item) => item === id), }) const observer = new QueryObserver(queryClient, options('a')) const unsubscribe = observer.subscribe(() => undefined) @@ -2087,7 +2111,10 @@ describe('queryObserver', () => { } // A new placeholderData is not memoized, so its undefined means pending - observer.setOptions({ ...options(''), placeholderData: () => undefined }) + observer.setOptions({ + ...options(''), + [placeholderOption]: () => undefined, + }) expect(observer.getCurrentResult()).toMatchObject({ status: 'pending', isPlaceholderData: false, diff --git a/packages/query-core/src/__tests__/queryObserverProjection.test.ts b/packages/query-core/src/__tests__/queryObserverProjection.test.ts index 558c04f0e2b..51728c55a91 100644 --- a/packages/query-core/src/__tests__/queryObserverProjection.test.ts +++ b/packages/query-core/src/__tests__/queryObserverProjection.test.ts @@ -1,4 +1,9 @@ import { createKey } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueryClient, QueryObserver, defaultQueryFn, noop } from '..' @@ -21,8 +26,8 @@ describe('observer data outcome after reset', () => { queryKey: key, queryFn: () => new Promise<{ label: string | null }>(() => {}), enabled: false, - placeholderData: placeholder, - select: (row) => { + [placeholderOption]: placeholder, + [selectOption]: (row) => { if (row.label === null) throw new Error('label not ready') return row.label }, @@ -35,7 +40,7 @@ describe('observer data outcome after reset', () => { isPlaceholderData: false, }) - await queryClient.resetQueries({ queryKey: key }) + await cacheOperations(queryClient).resetQueries({ queryKey: key }) expect(queryClient.getQueryData(key)).toBeUndefined() expect(observer.getCurrentResult()).toMatchObject({ @@ -57,8 +62,8 @@ describe('observer data outcome after reset', () => { queryKey: key, queryFn: defaultQueryFn, enabled: false, - placeholderData: { label: null }, - select, + [placeholderOption]: { label: null }, + [selectOption]: select, } as const queryClient.setQueryData(key, { label: 'first' }) const observer = new QueryObserver(queryClient, options) @@ -74,7 +79,7 @@ describe('observer data outcome after reset', () => { }) expect(select).toHaveBeenCalledTimes(2) - await queryClient.resetQueries({ queryKey: key }) + await cacheOperations(queryClient).resetQueries({ queryKey: key }) expect(queryClient.getQueryData(key)).toBeUndefined() const callsAfterReset = select.mock.calls.length @@ -104,7 +109,10 @@ describe('observer callback errors', () => { const placeholderData = vi.fn<() => never>(() => { throw new Error('placeholder failed') }) - const reader = observer.createResultReader({ ...options, placeholderData }) + const reader = observer.createResultReader({ + ...options, + [placeholderOption]: placeholderData, + }) try { const result = reader.getSnapshot() @@ -143,7 +151,7 @@ describe('observer callback errors', () => { } as const const observer = new QueryObserver(client, { ...options, - select: () => { + [selectOption]: () => { throw undefined }, }) @@ -170,7 +178,7 @@ describe('observer callback errors', () => { queryKey: createKey(), initialData: 1, enabled: false, - select: (value: number) => value * 2, + [selectOption]: (value: number) => value * 2, }) const observer = new QueryObserver(client, options) const reader = observer.createResultReader({ @@ -196,7 +204,7 @@ describe('observer callback errors', () => { const options = client.defaultQueryOptions<{ value: number }>({ queryKey: createKey(), enabled: false, - placeholderData, + [placeholderOption]: placeholderData, structuralSharing: false, }) const observer = new QueryObserver(client, options) @@ -213,7 +221,7 @@ describe('observer callback errors', () => { const secondReader = observer.createResultReader({ ...options, - placeholderData: () => placeholderData(), + [placeholderOption]: () => placeholderData(), }) const second = secondReader.getSnapshot() expect(secondReader.getSnapshot()).toBe(second) diff --git a/packages/query-core/src/__tests__/queryObserverResultReader.test-d.tsx b/packages/query-core/src/__tests__/queryObserverResultReader.test-d.tsx index 03a5a85fe1e..ce0a3bfca2f 100644 --- a/packages/query-core/src/__tests__/queryObserverResultReader.test-d.tsx +++ b/packages/query-core/src/__tests__/queryObserverResultReader.test-d.tsx @@ -1,3 +1,4 @@ +import { selectOption } from '@tanstack/query-test-utils/projection' import { describe, expectTypeOf, it } from 'vitest' import { InfiniteQueryObserver, QueryClient, QueryObserver } from '..' import type { @@ -23,7 +24,7 @@ describe('result reader types', () => { >({ queryKey: ['value'], queryFn: () => 1, - select: String, + [selectOption]: String, }) const observer = new QueryObserver(client, options) const reader = observer.createResultReader(options) @@ -46,7 +47,7 @@ describe('result reader types', () => { > = { queryKey: ['value'], queryFn: ({ pageParam }) => pageParam, - select: (data) => data.pages.join(','), + [selectOption]: (data) => data.pages.join(','), initialPageParam: 0, getNextPageParam: (last) => last + 1, queryHash: 'value', diff --git a/packages/query-core/src/__tests__/queryObserverResultReader.test.tsx b/packages/query-core/src/__tests__/queryObserverResultReader.test.tsx index b87d8233c2b..d8b7de29a13 100644 --- a/packages/query-core/src/__tests__/queryObserverResultReader.test.tsx +++ b/packages/query-core/src/__tests__/queryObserverResultReader.test.tsx @@ -1,4 +1,8 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { InfiniteQueryObserver, @@ -35,7 +39,7 @@ describe('query observer result readers', () => { const options = client.defaultQueryOptions({ queryKey: keyA, enabled: false, - select, + [selectOption]: select, }) const observer = new QueryObserver(client, options) const listener = vi.fn<() => void>() @@ -51,7 +55,7 @@ describe('query observer result readers', () => { ...options, queryKey: keyB, queryHash: undefined, - select: (data) => ({ selected: data.value * 10 }), + [selectOption]: (data) => ({ selected: data.value * 10 }), }), ) @@ -177,7 +181,7 @@ describe('query observer result readers', () => { queryKey: createKey(), initialData: { value: 1 }, enabled: false, - select: (data: { value: number }) => data.value, + [selectOption]: (data: { value: number }) => data.value, }) const observer = new QueryObserver(client, options) const current = observer.getCurrentResult() @@ -185,7 +189,10 @@ describe('query observer result readers', () => { const select = vi.fn<() => never>(() => { throw error }) - const reader = observer.createResultReader({ ...options, select }) + const reader = observer.createResultReader({ + ...options, + [selectOption]: select, + }) const snapshot = reader.getSnapshot() await vi.advanceTimersByTimeAsync(10) expect(reader.getSnapshot()).toBe(snapshot) @@ -207,7 +214,7 @@ describe('query observer result readers', () => { const options = client.defaultQueryOptions({ queryKey: key, enabled: false, - select, + [selectOption]: select, structuralSharing: false, }) const observer = new QueryObserver(client, options) @@ -243,7 +250,7 @@ describe('query observer result readers', () => { const options = client.defaultQueryOptions({ queryKey: key, enabled: false, - select, + [selectOption]: select, }) const observer = new QueryObserver(client, options) const reader = observer.createResultReader(options) @@ -261,7 +268,7 @@ describe('query observer result readers', () => { queryKey: createKey(), queryFn: () => ({ value: 1 }), enabled: false, - select: (data: { value: number }) => data.value, + [selectOption]: (data: { value: number }) => data.value, }) const observer = new QueryObserver(client, options) const placeholderData = vi.fn<() => { value: number }>(() => ({ value: 2 })) @@ -270,8 +277,8 @@ describe('query observer result readers', () => { }) const reader = observer.createResultReader({ ...options, - placeholderData, - select, + [placeholderOption]: placeholderData, + [selectOption]: select, }) const snapshot = reader.getSnapshot() await vi.advanceTimersByTimeAsync(10) @@ -285,7 +292,7 @@ describe('query observer result readers', () => { queryKey: createKey(), initialData: { value: 1 }, enabled: false, - select: (data: { value: number }) => ({ selected: data.value }), + [selectOption]: (data: { value: number }) => ({ selected: data.value }), }) const observer = new QueryObserver(client, options) const select = vi.fn<(data: { value: number }) => { selected: number }>( @@ -295,7 +302,10 @@ describe('query observer result readers', () => { ) const listener = vi.fn<() => void>() const unsubscribe = observer.subscribe(listener) - const reader = observer.createResultReader({ ...options, select }) + const reader = observer.createResultReader({ + ...options, + [selectOption]: select, + }) const snapshot = reader.getSnapshot() reader.commit() expect(observer.getCurrentResult().data).toBe(snapshot.data) @@ -323,7 +333,7 @@ describe('query observer result readers', () => { initialData: undefined, queryKey: createKey(), enabled: false, - placeholderData, + [placeholderOption]: placeholderData, }), ) const snapshot = reader.getSnapshot() @@ -349,7 +359,7 @@ describe('query observer result readers', () => { queryKey: createKey(), queryFn: () => ({ value: 0 }), enabled: false, - placeholderData, + [placeholderOption]: placeholderData, }) const observer = new QueryObserver(client, options) expect( @@ -359,7 +369,7 @@ describe('query observer result readers', () => { }) const withoutPlaceholder = observer.createResultReader({ ...options, - placeholderData: undefined, + [placeholderOption]: undefined, }) withoutPlaceholder.commit() expect(withoutPlaceholder.getSnapshot().data).toBeUndefined() diff --git a/packages/query-core/src/__tests__/streamedQuery.test.tsx b/packages/query-core/src/__tests__/streamedQuery.test.tsx index 75e3307b61b..38256c1f455 100644 --- a/packages/query-core/src/__tests__/streamedQuery.test.tsx +++ b/packages/query-core/src/__tests__/streamedQuery.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueryClient, QueryObserver, streamedQuery } from '..' @@ -411,7 +412,7 @@ describe('streamedQuery', () => { const unsubscribe = observer.subscribe(vi.fn()) await vi.advanceTimersByTimeAsync(50) - await queryClient.cancelQueries({ queryKey: key }) + await cacheOperations(queryClient).cancelQueries({ queryKey: key }) const cancelledData = queryClient.getQueryData(key) expect(cancelledData).toStrictEqual( refetchMode === 'append' ? [99, 0] : [99], @@ -491,7 +492,7 @@ describe('streamedQuery', () => { const unsubscribe = observer.subscribe(vi.fn()) await vi.advanceTimersByTimeAsync(0) resolveChunk({ done: false, value: 1 }) - void queryClient.cancelQueries({ queryKey: key }) + void cacheOperations(queryClient).cancelQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(0) expect(queryClient.getQueryData(key)).toStrictEqual([99]) @@ -527,7 +528,7 @@ describe('streamedQuery', () => { }) const unsubscribe = observer.subscribe(vi.fn()) - await queryClient.cancelQueries({ queryKey: key }) + await cacheOperations(queryClient).cancelQueries({ queryKey: key }) queryClient.setQueryData(key, [100]) await vi.advanceTimersByTimeAsync(100) diff --git a/packages/query-core/src/__tests__/utils.test-d.tsx b/packages/query-core/src/__tests__/utils.test-d.tsx index 216ca46492f..94695fd5d89 100644 --- a/packages/query-core/src/__tests__/utils.test-d.tsx +++ b/packages/query-core/src/__tests__/utils.test-d.tsx @@ -1,3 +1,4 @@ +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { assertType, describe, expectTypeOf, it } from 'vitest' import { QueryClient } from '../queryClient' import { @@ -124,9 +125,10 @@ describe('QueryFilters', () => { const queryKey: Key = ['foo', 'bar'] as any as Key - expectTypeOf(new QueryClient().invalidateQueries).toBeCallableWith({ + const result = cacheOperations(new QueryClient()).invalidateQueries({ queryKey, }) + expectTypeOf(result).toEqualTypeOf>() }) it('should error on invalid query keys', () => { diff --git a/packages/query-test-utils/package.json b/packages/query-test-utils/package.json index 5aa3f7ef427..1753a93efe8 100644 --- a/packages/query-test-utils/package.json +++ b/packages/query-test-utils/package.json @@ -24,7 +24,10 @@ "default": "./src/index.ts" }, "./package.json": "./package.json", - "./polling": "./src/polling.ts" + "./polling": "./src/polling.ts", + "./cacheOperations": "./src/cacheOperations.ts", + "./scope": "./src/scope.ts", + "./projection": "./src/projection.ts" }, "scripts": { "clean": "premove ./build ./coverage ./dist-ts ./.cache/test-types", diff --git a/packages/query-test-utils/src/cacheOperations.ts b/packages/query-test-utils/src/cacheOperations.ts new file mode 100644 index 00000000000..1c040648ca2 --- /dev/null +++ b/packages/query-test-utils/src/cacheOperations.ts @@ -0,0 +1,9 @@ +/** + * Selects this client's cache operations in the shared behavior and type tests. + * The pluggable adapter supplies its named exports through the same fixture. + * @param client - Client under test. + * @returns The client's cache operations. + */ +export function cacheOperations(client: TClient): TClient { + return client +} diff --git a/packages/query-test-utils/src/projection.ts b/packages/query-test-utils/src/projection.ts new file mode 100644 index 00000000000..59a47430228 --- /dev/null +++ b/packages/query-test-utils/src/projection.ts @@ -0,0 +1,23 @@ +/** Marks a query selector in suites shared by adapters with different option syntax. */ +export const selectOption = 'select' + +/** Marks a query placeholder in suites shared by adapters with different option syntax. */ +export const placeholderOption = 'placeholderData' + +/** Input of a projection option in the standard observer. */ +export type ProjectionInput = T + +/** + * Reads the selector or placeholder supplied to the standard observer. + * @param option - Value exposed through the observer options. + * @returns The original input for a projection type assertion. + */ +export function projectionInput(option: T): T { + return option +} + +/** A stored selection option for an adapter-agnostic React test. */ +export type SelectSetting = TValue + +/** A stored placeholder option for an adapter-agnostic React test. */ +export type PlaceholderSetting = TValue diff --git a/packages/query-test-utils/src/scope.ts b/packages/query-test-utils/src/scope.ts new file mode 100644 index 00000000000..713b159d246 --- /dev/null +++ b/packages/query-test-utils/src/scope.ts @@ -0,0 +1,8 @@ +/** + * Creates a serial scope for the canonical and integrated v6 runtimes. + * @param id - The shared queue ID. + * @returns The scope option used by the v6 mutation cache. + */ +export function serialScope(id: string): { id: string } { + return { id } +} diff --git a/packages/query-types/src/queryObserver.ts b/packages/query-types/src/queryObserver.ts index f5a38d82f0e..74f76ffd7f3 100644 --- a/packages/query-types/src/queryObserver.ts +++ b/packages/query-types/src/queryObserver.ts @@ -3,6 +3,7 @@ import type { FetchOptions, QueryState } from './query' import type { DefaultError, DefaultedQueryObserverOptions, + PlaceholderValue, QueryKey, QueryObserverOptions, QueryObserverResult, @@ -65,14 +66,9 @@ export interface QueryObserverResultContext< /** The unselected placeholder or factory error. */ placeholder?: { key: { - placeholderData: QueryObserverOptions< - TRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >['placeholderData'] + placeholderData: + | PlaceholderValue + | undefined structuralSharing: QueryOptions< TRuntime, TQueryFnData, diff --git a/packages/query-types/src/types.ts b/packages/query-types/src/types.ts index 97810bddcf4..6e421e2d2b5 100644 --- a/packages/query-types/src/types.ts +++ b/packages/query-types/src/types.ts @@ -537,6 +537,28 @@ export type ThrowOnError< query: QueryOf, ) => boolean) +/** A raw placeholder value or the callback that supplies it for a query. */ +export type PlaceholderValue< + TRuntime extends RuntimeBinding, + TQueryData, + TError, + TQueryKey extends QueryKey, +> = + | NonFunctionGuard + | PlaceholderDataFunction< + TRuntime, + NonFunctionGuard, + TError, + NonFunctionGuard, + TQueryKey + > + +// An adapter can pair an option with its optional runtime implementation. +type ProjectionOption = + TRuntime extends Record + ? readonly [feature: TImplementation, value: TValue] + : TValue + /** * Shared options for default resolution and resolved observer state. * @internal @@ -687,7 +709,11 @@ export interface QueryObserverOptionsBase< * changes. To optimize, memoize the function so its reference stays stable across calls. * If the selector throws, the observer reports the error and can keep the last valid selection. */ - select?: (data: TQueryData) => TData + select?: ProjectionOption< + TRuntime, + 'selectFeature', + (data: TQueryData) => TData + > /** * If set to `true`, the query will suspend when `status === 'pending'` * and throw errors when `status === 'error'`. @@ -698,15 +724,11 @@ export interface QueryObserverOptionsBase< * If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. * If the placeholder function throws, the observer reports the error with no data. The query state in the cache is unaffected. */ - placeholderData?: - | NonFunctionGuard - | PlaceholderDataFunction< - TRuntime, - NonFunctionGuard, - TError, - NonFunctionGuard, - TQueryKey - > + placeholderData?: ProjectionOption< + TRuntime, + 'placeholderFeature', + PlaceholderValue + > /** @internal */ _optimisticResults?: 'optimistic' | 'isRestoring' @@ -849,7 +871,11 @@ export interface QueryExecuteOptions< * This option can be used to transform or select a part of the data returned by the query function. It affects * the value this call resolves with, but does not affect what gets stored in the query cache. */ - select?: (data: TQueryData) => TData + select?: ProjectionOption< + TRuntime, + 'selectFeature', + (data: TQueryData) => TData + > /** * The time in milliseconds after data is considered stale. * If the data is fresh it will be returned from the cache. @@ -2027,7 +2053,9 @@ export interface MutationOptions< * Mutations sharing the same `scope.id` run serially, in the order they were started. * Without a scope, a mutation runs as soon as it is triggered. */ - scope?: MutationScope + scope?: TRuntime extends { mutationScope: infer TScope } + ? TScope + : MutationScope } /** diff --git a/packages/react-query-no-core-pluggable/README.md b/packages/react-query-no-core-pluggable/README.md index eaebe6d070f..464ecf53e82 100644 --- a/packages/react-query-no-core-pluggable/README.md +++ b/packages/react-query-no-core-pluggable/README.md @@ -1,6 +1,6 @@ # @tanstack/react-query-no-core-pluggable -An experimental ESM React Query adapter for React 19. Create a regular `QueryClient` to use queries, infinite queries and mutations. Import `refetchInterval` to enable polling for an observer. +An experimental ESM React Query adapter for React 19. Create a regular `QueryClient` to use queries, infinite queries and mutations. Import optional features where you use them. ```tsx import { @@ -42,3 +42,43 @@ useQuery({ ``` Polling runs while an enabled observer has subscribers and the window is focused. Set `refetchIntervalInBackground: true` to keep polling in the background. Each observer manages its own timer, including when several observers share a client default. + +## Selecting and keeping data + +`select` maps the cached value for one observer. `placeholderData` supplies a temporary value for a pending query. Wrap a typed selector in `select(getTitle)`, or use the tuple form to infer an inline callback's argument from the query. For example, this hook keeps displaying the previous post title while the next post loads. + +```tsx +import { + keepPreviousData, + placeholderData, + select, + useQuery, +} from '@tanstack/react-query-no-core-pluggable' + +function usePostTitle(id: number) { + return useQuery({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), // Promise<{ title: string }> + select: [select, (post) => post.title], + placeholderData: placeholderData(keepPreviousData), + }) +} +``` + +## Mutations and cache operations + +Pass `scope: serialScope('orders')` to `useMutation` to run mutations with that ID one at a time within a cache. Multiple calls to `serialScope('orders')` share the queue. The scope ID survives dehydration and hydration. + +Imperative infinite queries and bulk cache operations are named exports. Pass the client as the first argument. + +```ts +import { + infiniteQuery, + invalidateQueries, +} from '@tanstack/react-query-no-core-pluggable' + +await infiniteQuery(client, orderPageOptions) +await invalidateQueries(client, { queryKey: ['orders'] }) +``` + +The other bulk operations are `getQueriesData`, `setQueriesData`, `removeQueries`, `resetQueries`, `cancelQueries`, and `refetchQueries`. Single-query access such as `client.getQueryData(key)` stays on the client. All three option helpers (`queryOptions`, `infiniteQueryOptions`, and `mutationOptions`) return their argument unchanged and share one JavaScript implementation. diff --git a/packages/react-query-no-core-pluggable/package.json b/packages/react-query-no-core-pluggable/package.json index 9e5d3b4083c..bb44c15d920 100644 --- a/packages/react-query-no-core-pluggable/package.json +++ b/packages/react-query-no-core-pluggable/package.json @@ -1,7 +1,7 @@ { "name": "@tanstack/react-query-no-core-pluggable", "version": "5.108.4", - "description": "React Query with a standalone runtime and opt-in polling per query observer", + "description": "Experimental ESM React Query adapter with per-option features and tree-shakable cache operations", "author": "tannerlinsley", "license": "MIT", "repository": { diff --git a/packages/react-query-no-core-pluggable/src/HydrationBoundary.tsx b/packages/react-query-no-core-pluggable/src/HydrationBoundary.tsx index 3b22e90597a..d88e7601a54 100644 --- a/packages/react-query-no-core-pluggable/src/HydrationBoundary.tsx +++ b/packages/react-query-no-core-pluggable/src/HydrationBoundary.tsx @@ -1,7 +1,7 @@ 'use client' import * as React from 'react' import { useQueryClient } from './QueryClientProvider' -import { hydrate } from './runtime/hydration' +import { hydrateQueries } from './runtime/hydration' import type { DehydratedState, OmitKeyof } from '@tanstack/query-types/bindings' import type { HydrateOptions } from './runtime/hydration' import type { QueryClient } from './runtime/queryClient' @@ -122,14 +122,14 @@ export const HydrationBoundary = ({ if (newQueries.length > 0) { // oxlint-disable-next-line react-hooks-js/refs -- new queries are hydrated during render on purpose, and 'options' is read through a ref so that a new 'options' object does not rerun this memo - hydrate(client, { queries: newQueries }, optionsRef.current) + hydrateQueries(client, newQueries, optionsRef.current) } return existingQueries.length > 0 ? existingQueries : undefined }, [client, state]) React.useEffect(() => { if (hydrationQueue) { - hydrate(client, { queries: hydrationQueue }, optionsRef.current) + hydrateQueries(client, hydrationQueue, optionsRef.current) } }, [client, hydrationQueue]) diff --git a/packages/react-query-no-core-pluggable/src/__tests__/cacheOperations.test.ts b/packages/react-query-no-core-pluggable/src/__tests__/cacheOperations.test.ts new file mode 100644 index 00000000000..4aac92faf61 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/__tests__/cacheOperations.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest' +import { + QueryClient, + getQueriesData, + invalidateQueries, + removeQueries, + setQueriesData, +} from '..' + +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'] } + client.setQueryData(['posts', 1], 2) + client.setQueryData(['posts', 2], 3) + otherClient.setQueryData(['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(client.getQueryState(['posts', 1])?.isInvalidated).toBe(true) + removeQueries(client, filters) + expect(getQueriesData(client, filters)).toStrictEqual([]) + expect(otherClient.getQueryData(['posts', 1])).toBe(10) + }) +}) diff --git a/packages/react-query-no-core-pluggable/src/__tests__/infiniteQuery.test.ts b/packages/react-query-no-core-pluggable/src/__tests__/infiniteQuery.test.ts new file mode 100644 index 00000000000..9cf9afe9e57 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/__tests__/infiniteQuery.test.ts @@ -0,0 +1,48 @@ +import { describe, expect, expectTypeOf, it, vi } from 'vitest' +import { + QueryClient, + dehydrate, + hydrate, + infiniteQuery, + refetchQueries, +} from '..' +import type { InfiniteData } from '..' + +describe('infiniteQuery', () => { + 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 + + client.setQueryDefaults(queryKey, options) + hydrate(client, dehydrate(server)) + fetchPage.mockClear() + await refetchQueries(client, { queryKey }) + expect( + fetchPage.mock.calls.map(([context]) => context.pageParam), + ).toStrictEqual([0, 1]) + expect(client.getQueryData(queryKey)).toStrictEqual({ + pages: [0, 1], + pageParams: [0, 1], + }) + client.clear() + server.clear() + }) +}) diff --git a/packages/react-query-no-core-pluggable/src/__tests__/projection.test-d.ts b/packages/react-query-no-core-pluggable/src/__tests__/projection.test-d.ts new file mode 100644 index 00000000000..d0c99bd77e5 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/__tests__/projection.test-d.ts @@ -0,0 +1,72 @@ +import { describe, expectTypeOf, it } from 'vitest' +import { + keepPreviousData, + placeholderData, + select, + useInfiniteQuery, + useQuery, + useSuspenseInfiniteQuery, + useSuspenseQuery, +} from '..' +import type { InfiniteData } from '..' + +describe('projection feature types', () => { + const options = { queryKey: ['orders'], queryFn: () => ({ count: 2 }) } + const count = (order: { count: number }) => order.count + + it('infers the output of a typed selector and preserves the query function data', () => { + const result = useQuery({ + ...options, + placeholderData: placeholderData(keepPreviousData), + select: select(count), + }) + expectTypeOf(result.data).toEqualTypeOf() + const suspense = useSuspenseQuery({ + ...options, + select: [ + select, + (order) => { + expectTypeOf(order).toEqualTypeOf<{ count: number }>() + return order.count + }, + ], + }) + expectTypeOf(suspense.data).toEqualTypeOf() + }) + + it('infers cached pages and the page parameter before selection', () => { + const paging = { + ...options, + initialPageParam: 0, + getNextPageParam: () => 1, + } + const regular = useInfiniteQuery({ + ...paging, + select: [ + select, + (data) => { + expectTypeOf(data).toEqualTypeOf< + InfiniteData<{ count: number }, number> + >() + return data.pages.length + }, + ], + }) + const suspense = useSuspenseInfiniteQuery({ + ...paging, + select: [select, (data) => data.pageParams.join(',')], + }) + expectTypeOf(regular.data).toEqualTypeOf() + expectTypeOf(suspense.data).toEqualTypeOf() + }) + + it('requires the feature for observer selectors and placeholders', () => { + expectTypeOf(select(count)).toEqualTypeOf< + readonly [typeof select, typeof count] + >() + // @ts-expect-error Plain selector callbacks do not install the projection feature. + useQuery({ ...options, select: count }) + // @ts-expect-error Plain placeholder data does not install the placeholder feature. + useQuery({ ...options, placeholderData: { count: 1 } }) + }) +}) diff --git a/packages/react-query-no-core-pluggable/src/__tests__/projection.test.ts b/packages/react-query-no-core-pluggable/src/__tests__/projection.test.ts new file mode 100644 index 00000000000..5c69a2149a5 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/__tests__/projection.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it, vi } from 'vitest' +import { QueryClient, QueryObserver, placeholderData, select } from '..' + +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) + client.setQueryData(['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 + } + client.setQueryDefaults(['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(client.getQueryData(['entry', 'b'])).toBe('invalid') + }) +}) diff --git a/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test-d.ts b/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test-d.ts index 6d76dde2046..cbb12bed457 100644 --- a/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test-d.ts +++ b/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test-d.ts @@ -1,6 +1,7 @@ import { describe, expectTypeOf, it } from 'vitest' import { refetchInterval, + select, useInfiniteQuery, useQuery, useSuspenseInfiniteQuery, @@ -13,7 +14,7 @@ describe('refetchInterval types', () => { const options = { queryKey: ['book'], queryFn: () => 'Dune' } useQuery({ ...options, - select: (book) => book.length, + select: [select, (book) => book.length], refetchInterval: (query) => { expectTypeOf(query.state.data).toEqualTypeOf() return refetchInterval(query.state.data ? false : 3000) diff --git a/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test.ts b/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test.ts index b5c62ca3998..b9a89dc2a6c 100644 --- a/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test.ts +++ b/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test.ts @@ -5,6 +5,7 @@ import { QueryObserver, environmentManager, focusManager, + infiniteQuery, refetchInterval, } from '..' @@ -139,7 +140,7 @@ describe('refetchInterval', () => { }) await expect(mutation.mutate()).resolves.toBe(42) await expect( - client.infiniteQuery({ + infiniteQuery(client, { queryKey: ['pages'], initialPageParam: 1, pages: 2, diff --git a/packages/react-query-no-core-pluggable/src/__tests__/serialScope.test.ts b/packages/react-query-no-core-pluggable/src/__tests__/serialScope.test.ts new file mode 100644 index 00000000000..d01fc94e903 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/__tests__/serialScope.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from 'vitest' +import { + MutationObserver, + QueryClient, + dehydrate, + hydrate, + onlineManager, + serialScope, +} from '..' + +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 = target.resumePausedMutations() + await started.promise + expect(events).toStrictEqual(['start 1']) + release.resolve() + await resumed + expect(events).toStrictEqual([ + 'start 1', + 'finish 1', + 'start 2', + 'finish 2', + ]) + await source.resumePausedMutations() + await Promise.all([first, second]) + } finally { + release.resolve() + onlineManager.setOnline(wasOnline) + source.clear() + target.clear() + } + }) +}) diff --git a/packages/react-query-no-core-pluggable/src/index.ts b/packages/react-query-no-core-pluggable/src/index.ts index 66030409a7a..a5dddd66238 100644 --- a/packages/react-query-no-core-pluggable/src/index.ts +++ b/packages/react-query-no-core-pluggable/src/index.ts @@ -11,6 +11,7 @@ export { dehydrateQuery, hydrate, } from './runtime/hydration' +export { infiniteQuery } from './runtime/infiniteQuery' export { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' export { MutationCache } from './runtime/mutationCache' export type { @@ -28,7 +29,21 @@ export type { QueryCacheConfig, } from './runtime/queryCache' export { QueryClient } from './runtime/queryClient' +export { + getQueriesData, + setQueriesData, + removeQueries, + resetQueries, + cancelQueries, + invalidateQueries, + refetchQueries, +} from './runtime/cacheOperations' export type { QueryRuntime } from './runtime/runtimeBinding' +export { serialScope } from './runtime/serialScope' +export type { SerialScope } from './runtime/serialScope' +export { select } from './runtime/select' +export { placeholderData } from './runtime/placeholderData' +export type { Select, PlaceholderData } from './runtime/projectionTypes' export { refetchInterval } from './runtime/refetchInterval' export type { RefetchInterval } from './runtime/refetchInterval' export { QueryObserver } from './runtime/queryObserver' diff --git a/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts b/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts index 1cf0bc837d5..198111f07dd 100644 --- a/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts +++ b/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts @@ -121,7 +121,7 @@ export type DefinedInitialDataInfiniteOptions< type InfiniteQueryOptionsFn = { /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(client, options)`. * `options.queryKey` is required and is the query key to generate options for. * * This overload is selected when `initialData` is known to be defined. @@ -183,7 +183,7 @@ type InfiniteQueryOptionsFn = { /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(client, options)`. * `options.queryKey` is required and is the query key to generate options for. * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. * @returns The same options object, typed so that `queryKey` carries the inferred data type. @@ -242,7 +242,7 @@ type InfiniteQueryOptionsFn = { /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `infiniteQuery(client, options)`. * `options.queryKey` is required and is the query key to generate options for. * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. * @returns The same options object, typed so that `queryKey` carries the inferred data type. diff --git a/packages/react-query-no-core-pluggable/src/runtime/cacheOperations.ts b/packages/react-query-no-core-pluggable/src/runtime/cacheOperations.ts new file mode 100644 index 00000000000..5f315440d0d --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/cacheOperations.ts @@ -0,0 +1,287 @@ +import { notifyManager } from './notifyManager' +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 QueryClient#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 client + .getQueryCache() + .findAll(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 QueryClient#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 QueryClient#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(() => + client + .getQueryCache() + .findAll(filters) + .map(({ queryKey }) => [ + queryKey, + client.setQueryData(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 = client.getQueryCache() + notifyManager.batch(() => { + queryCache.findAll(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 = client.getQueryCache() + + return notifyManager.batch(() => { + const matched = queryCache.findAll(filters) + const queriesToRefetch = new Set(matched) + matched.forEach((query) => { + query.reset() + }) + 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(() => + client + .getQueryCache() + .findAll(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(() => { + client + .getQueryCache() + .findAll(filters) + .forEach((query) => { + query.invalidate() + }) + + 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(() => + client + .getQueryCache() + .findAll(filters) + .filter((query) => !query.isDisabled() && !query.isStatic()) + .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/react-query-no-core-pluggable/src/runtime/hydration.ts b/packages/react-query-no-core-pluggable/src/runtime/hydration.ts index bafec476b72..bfa78711e61 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/hydration.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/hydration.ts @@ -1,4 +1,6 @@ +import { prepareInfiniteFetch } from './infiniteQueryBehavior' import { Mutation } from './mutation' +import { serialScope } from './serialScope' import { noop } from './utils' import type * as Shared from '@tanstack/query-types/bindings' import type { @@ -54,7 +56,7 @@ function dehydrateMutation(mutation: Mutation): DehydratedMutation { return { mutationKey: mutation.options.mutationKey, state: mutation.state, - ...(mutation.options.scope && { scope: mutation.options.scope }), + ...(mutation.options.scope && { scope: { id: mutation.options.scope.id } }), ...(mutation.meta && { meta: mutation.meta }), } } @@ -241,24 +243,41 @@ export function hydrate( dehydratedState: Partial, options?: HydrateOptions, ): void { - const queryCache = client.getQueryCache() - const deserializeData = - options?.defaultOptions?.deserializeData ?? - client.getDefaultOptions().hydrate?.deserializeData - - dehydratedState.mutations?.forEach(({ state, ...mutationOptions }) => { + dehydratedState.mutations?.forEach(({ state, scope, ...mutationOptions }) => { Mutation.build( client, { ...client.getDefaultOptions().hydrate?.mutations, ...options?.defaultOptions?.mutations, ...mutationOptions, + ...(scope && { scope: serialScope(scope.id) }), }, state, ) }) - dehydratedState.queries?.forEach( + 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 = client.getQueryCache() + const deserializeData = + options?.defaultOptions?.deserializeData ?? + client.getDefaultOptions().hydrate?.deserializeData + + queries.forEach( ({ queryKey, state, @@ -320,7 +339,10 @@ export function hydrate( queryKey, queryHash, meta, - _type: queryType, + ...(queryType === 'infinite' && { + _type: queryType, + _prepareInfiniteFetch: prepareInfiniteFetch, + }), }, // Reset fetch status to idle to avoid // query being stuck in fetching state upon hydration diff --git a/packages/react-query-no-core-pluggable/src/runtime/infiniteQuery.ts b/packages/react-query-no-core-pluggable/src/runtime/infiniteQuery.ts new file mode 100644 index 00000000000..60fcdf25d0b --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/infiniteQuery.ts @@ -0,0 +1,105 @@ +import { infiniteFetchOptions } from './infiniteQueryBehavior' +import type { WithoutSkipToken } from '@tanstack/query-types/bindings' +import type { QueryClient } 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 QueryClient#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 client.query(infiniteFetchOptions(options) as any) +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryBehavior.ts b/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryBehavior.ts index ce7137c31b7..87e4df7626a 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryBehavior.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryBehavior.ts @@ -4,119 +4,116 @@ import { ensureQueryFn, fetchSignal, } from './utils' -import type { QueryBehavior } from './query' +import type { FetchContext, Query } from './query' import type { InfiniteData, InfiniteQueryPageParamsOptions } from './types' import type { FetchSignalContext } from './utils' /** - * Creates the behavior that fetches the pages of an infinite query: the next or previous page for - * `fetchNextPage`/`fetchPreviousPage`, or all pages again from the start on a refetch. - * @param pages - The number of pages to fetch from the start when all pages are fetched again, - * e.g. from the `pages` option of `queryClient.infiniteQuery`. Defaults to the number of cached - * pages. - * @returns The query behavior to set on an infinite query. + * Installs 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. */ -export function infiniteQueryBehavior( - pages?: number, -): QueryBehavior> { - return { - onFetch: (context, query) => { - const options = context.options as InfiniteQueryPageParamsOptions - 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), - } - } +export function prepareInfiniteFetch( + context: FetchContext>, + query: Query, +): void { + 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 - // 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 = 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) - } + const fetchFn = async () => { + let cancelled = false + const signalContext: FetchSignalContext = context + const queryFn = ensureQueryFn(context.options, context.fetchOptions) - return result + // 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 (context.options.persister) { - context.fetchFn = () => { - return context.options.persister?.( - fetchFn as any, - { - client: context.client, - queryKey: context.queryKey, - meta: context.options.meta, - signal: context.signal, - }, - query, - ) - } - } else { - context.fetchFn = fetchFn + + 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) { + context.fetchFn = () => { + return context.options.persister?.( + fetchFn as any, + { + client: context.client, + queryKey: context.queryKey, + meta: context.options.meta, + signal: context.signal, + }, + query, + ) + } + } else { + context.fetchFn = fetchFn } } @@ -185,3 +182,18 @@ export function hasPreviousPage( 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: prepareInfiniteFetch, + } +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryObserver.ts b/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryObserver.ts index 8fbd5546791..7b51284dfe9 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryObserver.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryObserver.ts @@ -1,4 +1,8 @@ -import { hasNextPage, hasPreviousPage } from './infiniteQueryBehavior' +import { + hasNextPage, + hasPreviousPage, + infiniteFetchOptions, +} from './infiniteQueryBehavior' import { QueryObserver } from './queryObserver' import type * as Shared from '@tanstack/query-types/bindings' import type { @@ -135,8 +139,7 @@ export class InfiniteQueryObserver< TPageParam >, ): void { - options._type = 'infinite' - super.setOptions(options) + super.setOptions(infiniteFetchOptions(options)) } /** @@ -153,10 +156,9 @@ export class InfiniteQueryObserver< TPageParam >, ): QueryObserverResultReader> { - return super.createResultReader({ - ...options, - _type: 'infinite', - }) as QueryObserverResultReader> + return super.createResultReader( + infiniteFetchOptions(options), + ) as QueryObserverResultReader> } /** diff --git a/packages/react-query-no-core-pluggable/src/runtime/mutation.ts b/packages/react-query-no-core-pluggable/src/runtime/mutation.ts index 79a3c27bf95..2a8bfe30d88 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/mutation.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/mutation.ts @@ -98,7 +98,8 @@ export class Mutation< this.#observers = [] this.state = config.state || getDefaultState() - this.setOptions(config.options) + this.options = config.options + this.updateGcTime(config.options.gcTime) this.scheduleGc() } @@ -110,9 +111,10 @@ export class Mutation< setOptions( options: MutationOptions, ): void { - this.options = options - - this.updateGcTime(this.options.gcTime) + // 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) } /** diff --git a/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts b/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts index c1d718aef25..e3e341b42f0 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts @@ -33,13 +33,11 @@ type MutationCacheListener = Shared.MutationCacheListener */ export class MutationCache extends Subscribable { #mutations: Set> - #scopes: Map>> #mutationId: number constructor(public config: MutationCacheConfig = {}) { super() this.#mutations = new Set() - this.#scopes = new Map() this.#mutationId = 0 } @@ -64,15 +62,7 @@ export class MutationCache extends Subscribable { */ add(mutation: Mutation): void { this.#mutations.add(mutation) - const scope = scopeFor(mutation) - if (typeof scope === 'string') { - const scopedMutations = this.#scopes.get(scope) - if (scopedMutations) { - scopedMutations.push(mutation) - } else { - this.#scopes.set(scope, [mutation]) - } - } + mutation.options.scope?.add(this, mutation) this.notify({ type: 'added', mutation }) } @@ -84,17 +74,7 @@ export class MutationCache extends Subscribable { remove(mutation: Mutation): void { if (this.#mutations.delete(mutation)) { mutation.destroy() - const scope = scopeFor(mutation) - const scopedMutations = this.#scopes.get(scope) - if (scopedMutations) { - const index = scopedMutations.indexOf(mutation) - if (index !== -1) { - scopedMutations.splice(index, 1) - if (!scopedMutations.length) { - this.#scopes.delete(scope) - } - } - } + mutation.options.scope?.remove(this, mutation) } // Currently we notify the removal even if the mutation was already removed. @@ -120,10 +100,7 @@ export class MutationCache extends Subscribable { * ahead of it. */ canRun(mutation: Mutation): boolean { - const firstPendingMutation = this.#scopes - .get(scopeFor(mutation)) - ?.find((candidate) => candidate.state.status === 'pending') - return !firstPendingMutation || firstPendingMutation === mutation + return mutation.options.scope?.canRun(this, mutation) ?? true } /** @@ -134,11 +111,7 @@ export class MutationCache extends Subscribable { * or immediately if there is none. */ runNext(mutation: Mutation): Promise { - const next = this.#scopes - .get(scopeFor(mutation)) - ?.find((entry) => entry !== mutation && entry.state.isPaused) - - return next?.continue() ?? Promise.resolve() + return mutation.options.scope?.runNext(this, mutation) ?? Promise.resolve() } /** @@ -155,8 +128,10 @@ export class MutationCache extends Subscribable { notifyManager.batch(() => { const mutations = this.getAll() this.#mutations.clear() - this.#scopes.clear() - mutations.forEach((mutation) => mutation.destroy()) + mutations.forEach((mutation) => { + mutation.options.scope?.remove(this, mutation) + mutation.destroy() + }) mutations.forEach((mutation) => { this.notify({ type: 'removed', mutation }) }) @@ -261,12 +236,3 @@ export class MutationCache extends Subscribable { ) } } - -/** - * Returns the scope id of a mutation, used to run mutations with the same scope one after another. - * @param mutation - The mutation to read the scope of. - * @returns The mutation's `scope.id`, or `undefined` if it has no scope. - */ -function scopeFor(mutation: Mutation) { - return mutation.options.scope?.id -} diff --git a/packages/react-query-no-core-pluggable/src/runtime/placeholderData.ts b/packages/react-query-no-core-pluggable/src/runtime/placeholderData.ts new file mode 100644 index 00000000000..71cba8df062 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/placeholderData.ts @@ -0,0 +1,96 @@ +import { projectResult } from './projectResult' +import { replaceData, shallowEqualObjects } from './utils' +import type { ProjectionFailure } from '@tanstack/query-types/bindings' +import type { Query } from './query' +import type { 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/react-query-no-core-pluggable/src/runtime/projectResult.ts b/packages/react-query-no-core-pluggable/src/runtime/projectResult.ts new file mode 100644 index 00000000000..ecdf5182269 --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/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/react-query-no-core-pluggable/src/runtime/projectionTypes.ts b/packages/react-query-no-core-pluggable/src/runtime/projectionTypes.ts new file mode 100644 index 00000000000..856fb0dfc7f --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/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/react-query-no-core-pluggable/src/runtime/query.ts b/packages/react-query-no-core-pluggable/src/runtime/query.ts index d874a18146c..023a10530c9 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/query.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/query.ts @@ -1,4 +1,3 @@ -import { infiniteQueryBehavior } from './infiniteQueryBehavior' import { notifyManager } from './notifyManager' import { Removable } from './removable' import { CancelledError, canFetch, createRetryer } from './retryer' @@ -17,6 +16,7 @@ import type { QueryAction, QueryState, } from '@tanstack/query-types/bindings' +import type { prepareInfiniteFetch } from './infiniteQueryBehavior' import type { QueryCache } from './queryCache' import type { QueryClient } from './queryClient' import type { QueryObserver } from './queryObserver' @@ -86,7 +86,7 @@ export class Query< queryHash: string options!: QueryOptions state: QueryState - #queryType?: 'infinite' + #prepareInfiniteFetch?: typeof prepareInfiniteFetch #initialState: QueryState #revertState?: QueryState @@ -124,10 +124,10 @@ export class Query< /** * `'infinite'` for an infinite query, otherwise `undefined`. * @internal - * @returns The type of the query, set from the `_type` option (e.g. `'infinite'`). + * @returns The type of the query, determined by its page fetcher. */ - get queryType() { - return this.#queryType + get queryType(): 'infinite' | undefined { + return this.#prepareInfiniteFetch ? 'infinite' : undefined } /** @@ -150,9 +150,10 @@ export class Query< ): void { this.options = { ...this.#defaultOptions, ...options } - if (options?._type) { - this.#queryType = options._type - } + const internalOptions = options as + | { _prepareInfiniteFetch?: typeof prepareInfiniteFetch } + | undefined + this.#prepareInfiniteFetch ??= internalOptions?._prepareInfiniteFetch this.updateGcTime(this.options.gcTime) @@ -604,12 +605,10 @@ export class Query< } addSignalProperty(context) - if (this.#queryType === 'infinite') { - const behavior = infiniteQueryBehavior( - (this.options as { pages?: number }).pages, - ) as QueryBehavior - behavior.onFetch(context, this as unknown as Query) - } + const prepare = this.#prepareInfiniteFetch as + | QueryBehavior['onFetch'] + | undefined + prepare?.(context, this as unknown as Query) // Store state in case the current fetch needs to be reverted this.#revertState = this.state diff --git a/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts b/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts index 27030624dc6..e0fc33effe0 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts @@ -1,13 +1,11 @@ import { focusManager } from './focusManager' import { MutationCache } from './mutationCache' -import { notifyManager } from './notifyManager' import { onlineManager } from './onlineManager' import { QueryCache } from './queryCache' import { defaultQueryFn, functionalUpdate, hashKeyByOptions, - noop, partialMatchKey, resolveQueryValue, skipToken, @@ -16,16 +14,11 @@ import type { WithoutSkipToken } from '@tanstack/query-types/bindings' import type { QueryState } from './query' import type { CacheKeyConfig, - CancelOptions, DefaultError, DefaultOptions, DefaultedQueryObserverOptions, InferDataFromTag, InferErrorFromTag, - InfiniteData, - InfiniteQueryExecuteOptions, - InvalidateOptions, - InvalidateQueryFilters, MutationKey, MutationObserverOptions, MutationOptions, @@ -35,9 +28,6 @@ import type { QueryKey, QueryObserverOptionsBase, QueryOptions, - RefetchOptions, - RefetchQueryFilters, - ResetOptions, SetDataOptions, } from './types' import type { MutationFilters, QueryFilters, Updater } from './utils' @@ -191,7 +181,7 @@ export class QueryClient { * Use `useQuery` to create a `QueryObserver` that subscribes to changes. * @param queryKey - The query key of the query to read. * @returns The cached data for the query, or `undefined` if no query with this key has been observed yet. - * @see {@link QueryClient#getQueriesData} + * @see {@link getQueriesData} */ getQueryData< TQueryFnData = unknown, @@ -204,39 +194,11 @@ export class QueryClient { .data } - /** - * 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 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 QueryClient#getQueryData} - * @example - * ```ts - * const data = queryClient.getQueriesData({ queryKey: ['posts'] }) - * ``` - */ - getQueriesData< - TQueryFnData = unknown, - TQueryFilters extends QueryFilters = QueryFilters, - >(filters: TQueryFilters): Array<[QueryKey, TQueryFnData | undefined]> { - return this.#queryCache.findAll(filters).map(({ queryKey, state }) => { - const data = state.data as TQueryFnData | undefined - return [queryKey, data] - }) - } - /** * Synchronous way to immediately update a query's cached data. If the updater (or the value * passed) resolves to `undefined`, the cache is left untouched and no query is created; * otherwise, if the query does not exist yet, it will be created. To update multiple queries - * at once by partially matching query keys, use {@link QueryClient#setQueriesData} instead. + * at once by partially matching query keys, import `setQueriesData`. * * Updates must be performed immutably: do not mutate `oldData`, or data previously retrieved * via {@link QueryClient#getQueryData}, in place. @@ -289,45 +251,6 @@ export class QueryClient { .setData(data, { ...options, manual: true }) } - /** - * 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 QueryClient#setQueryData} for each matching query. - * @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 QueryClient#setQueryData}. - * @example - * ```ts - * queryClient.setQueriesData({ queryKey: ['posts'] }, (oldPosts) => - * oldPosts ? oldPosts.filter((post) => post.id !== deletedId) : oldPosts, - * ) - * ``` - */ - setQueriesData< - TQueryFnData, - TQueryFilters extends QueryFilters = QueryFilters, - >( - filters: TQueryFilters, - updater: Updater< - NoInfer | undefined, - NoInfer | undefined - >, - options?: SetDataOptions, - ): Array<[QueryKey, TQueryFnData | undefined]> { - return notifyManager.batch(() => - this.#queryCache - .findAll(filters) - .map(({ queryKey }) => [ - queryKey, - this.setQueryData(queryKey, updater, options), - ]), - ) - } - /** * Imperative (non-reactive) way to retrieve an existing query's state. If the query does not * exist, `undefined` is returned. @@ -354,185 +277,6 @@ export class QueryClient { )?.state } - /** - * Removes queries from the cache that match the given filters. Unlike - * {@link QueryClient#invalidateQueries} or {@link QueryClient#refetchQueries}, this removes - * matching queries from the cache instead of refetching them. Without filters, every query in - * the cache is removed. - * @param filters - The filters that select which queries to remove. Without filters, every query - * is removed. - * @example - * ```ts - * queryClient.removeQueries({ queryKey: ['posts'], exact: true }) - * ``` - */ - removeQueries( - filters?: QueryFilters, - ): void { - const queryCache = this.#queryCache - notifyManager.batch(() => { - queryCache.findAll(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 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 queryClient.resetQueries({ queryKey: ['posts'], exact: true }) - * ``` - */ - resetQueries( - filters?: QueryFilters, - options?: ResetOptions, - ): Promise { - const queryCache = this.#queryCache - - return notifyManager.batch(() => { - const matched = queryCache.findAll(filters) - const queriesToRefetch = new Set(matched) - matched.forEach((query) => { - query.reset() - }) - return this.refetchQueries( - { - 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 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 queryClient.cancelQueries({ queryKey: ['posts'], exact: true }) - * ``` - */ - cancelQueries( - filters?: QueryFilters, - cancelOptions: CancelOptions = {}, - ): Promise { - const defaultedCancelOptions = { revert: true, ...cancelOptions } - - const promises = notifyManager.batch(() => - this.#queryCache - .findAll(filters) - .map((query) => query.cancel(defaultedCancelOptions)), - ) - - return Promise.all(promises).then(noop, noop) - } - - /** - * Marks queries matching the given filters as invalidated. Unlike - * {@link QueryClient#removeQueries}, invalidated queries stay in the cache. - * - * Unless `filters.refetchType` is `'none'`, matching queries are then refetched via - * {@link QueryClient#refetchQueries}, using `filters.refetchType` if set, otherwise - * `filters.type`, otherwise `'active'`. - * @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 QueryClient#refetchQueries}, e.g. `cancelRefetch` and - * `throwOnError`. - * @returns A promise that resolves once the refetch settles, or immediately if `refetchType` is - * `'none'`. - * @example - * ```ts - * await queryClient.invalidateQueries({ queryKey: ['posts'], refetchType: 'active' }) - * ``` - */ - invalidateQueries( - filters?: InvalidateQueryFilters, - options: InvalidateOptions = {}, - ): Promise { - return notifyManager.batch(() => { - this.#queryCache.findAll(filters).forEach((query) => { - query.invalidate() - }) - - if (filters?.refetchType === 'none') { - return Promise.resolve() - } - return this.refetchQueries( - { - ...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 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 queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' }) - * ``` - */ - refetchQueries( - filters?: RefetchQueryFilters, - options: RefetchOptions = {}, - ): Promise { - const fetchOptions = { - ...options, - cancelRefetch: options.cancelRefetch ?? true, - } - const promises = notifyManager.batch(() => - this.#queryCache - .findAll(filters) - .filter((query) => !query.isDisabled() && !query.isStatic()) - .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) - } - /** * Asynchronous method to fetch and cache a query, resolving with the data or throwing with * the error. @@ -653,104 +397,12 @@ export class QueryClient { const select = defaultedOptions.select if (select) { - return select(queryData) + return select[1](queryData) } return queryData as unknown as TData } - /** - * 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 QueryClient#getQueryData} - * to read the cache directly. - * @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 queryClient.infiniteQuery({ - * queryKey, - * queryFn, - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextCursor, - * }) - * console.log(data.pages) - * } catch (error) { - * console.log(error) - * } - * ``` - */ - infiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: WithoutSkipToken< - InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - > - >, - ): Promise< - Array extends Array> - ? InfiniteData - : TData - > - infiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - ): Promise< - | undefined - | (Array extends Array> - ? InfiniteData - : TData) - > - infiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - ): Promise< - | undefined - | (Array extends Array> - ? InfiniteData - : TData) - > { - return this.query({ ...options, _type: 'infinite' } as any) - } - /** * Resumes mutations that were paused because there was no network connection. Does nothing * (resolving immediately) if the client is currently offline. diff --git a/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts b/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts index c304f9c5ca9..2cfc3ed04a5 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts @@ -6,7 +6,6 @@ import { timeoutManager } from './timeoutManager' import { isValidTimeout, noop, - replaceData, resolveQueryValue, shallowEqualObjects, timeUntilStale, @@ -14,10 +13,10 @@ import { import type * as Shared from '@tanstack/query-types/bindings' import type { ObserverFetchOptions, - ProjectionFailure, QueryObserverListener, QueryObserverResultReader, } from '@tanstack/query-types/bindings' +import type { projectResult } from './projectResult' import type { Query, QueryState } from './query' import type { QueryClient } from './queryClient' import type { PollingTimer } from './refetchInterval' @@ -26,7 +25,6 @@ import type { ManagedTimerId } from './timeoutManager' import type { DefaultError, DefaultedQueryObserverOptions, - PlaceholderDataFunction, QueryKey, QueryObserverBaseResult, QueryObserverOptionsBase, @@ -48,7 +46,7 @@ export type QueryObserverResultContext< TData, TQueryData, TQueryKey -> +> & { project?: typeof projectResult } /** {@inheritDoc Shared.ObserverOptionsInput} */ export type ObserverOptionsInput< @@ -306,7 +304,6 @@ export class QueryObserver< >, ): QueryObserverResultReader> { const readerOptions = { ...options } - const { select, structuralSharing } = readerOptions const context = { ...this.#resultContext } let result = this.#currentResult @@ -314,21 +311,12 @@ export class QueryObserver< const query = this.#client .getQueryCache() .build(this.#client, readerOptions) - const { selection, selected } = this.#resultContext - const input = query.state.data - - // A query update may already have selected this data. - if ( - input !== undefined && - select && - shallowEqualObjects( - { input, select, structuralSharing }, - selection?.key, - ) - ) { - context.selection = selection - context.selected = selected - } + readerOptions.select?.[0].reuse( + readerOptions, + query, + this.#resultContext, + context, + ) const nextResult = this.createResult( query, @@ -582,67 +570,6 @@ export class QueryObserver< } } - #resolvePlaceholder( - options: QueryObserverOptionsBase< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >, - previousResultData: TData | undefined, - context = this.#resultContext, - ) { - const { placeholderData, structuralSharing } = options - const memo = context.placeholder - const previousQuery = this.#lastQueryWithDefinedData - const previousState = previousQuery?.state - const key = { - placeholderData, - structuralSharing, - previousQuery, - previousState, - previousOptions: previousQuery?.options, - } - if (shallowEqualObjects(key, memo?.key)) { - return memo - } - - let failure: ProjectionFailure | undefined - let input: TQueryData | undefined - let sourceQuery: typeof previousQuery - if (typeof placeholderData === 'function') { - try { - input = ( - placeholderData as unknown as PlaceholderDataFunction< - TQueryFnData, - TError, - TQueryData, - TQueryKey - > - )(previousState?.data, previousQuery) - } catch (error) { - failure = { error: error as TError, errorUpdatedAt: Date.now() } - } - if (previousState?.data !== undefined) { - sourceQuery = previousQuery - } - } else { - input = placeholderData - } - - if (input !== undefined) { - input = replaceData( - previousResultData, - input as unknown, - options, - ) as TQueryData - } - return input !== undefined || failure - ? { key, input, sourceQuery, failure } - : undefined - } - /** * Computes the result for a query and options from the query's state, applying `select`, * `placeholderData`, and the derived flags. Subclasses override it to add their own fields. @@ -686,68 +613,21 @@ export class QueryObserver< options._optimisticResults === 'isRestoring' ? 'idle' : newState.fetchStatus - const selectedQuery = context.selected?.query - if (selectedQuery && selectedQuery.state.data === undefined) { - context.selected = undefined - // Keep a cached error stable, but a successful selection needs its data. - if (!context.selection?.failure) { - context.selection = undefined - } - } - - const { placeholderData, select, structuralSharing } = options - if ( - newState.data === undefined && - newState.status === 'pending' && - placeholderData !== undefined - ) { - context.placeholder = this.#resolvePlaceholder( - options, - prevResult?.data, - context, - ) - } else { - context.placeholder = undefined - } - - const placeholder = context.placeholder - const input = placeholder ? placeholder.input : newState.data - if (!select || input === undefined) { - context.selection = undefined - } else { - const key = { input, select, structuralSharing } - if (!shallowEqualObjects(key, context.selection?.key)) { - try { - const data = replaceData(prevResult?.data, select(input), options) - context.selected = { - data, - query: placeholder ? placeholder.sourceQuery : query, - } - context.selection = { key } - } catch (error) { - context.selection = { - key, - failure: { - error: error as TError, - errorUpdatedAt: Date.now(), - }, - } - } - } - } - - const failure = placeholder?.failure ?? context.selection?.failure - const data = context.selection - ? context.selected?.data - : (input as unknown as TData | undefined) - const isPlaceholderData = - placeholder !== undefined && input !== undefined && !failure - const { error, errorUpdatedAt } = failure ?? newState - const status = failure - ? 'error' - : isPlaceholderData - ? 'success' - : newState.status + const feature = options.select?.[0] ?? options.placeholderData?.[0] + const project = feature?.project ?? context.project + const projection = project?.( + query, + newState, + options, + context, + prevResult?.data, + this.#lastQueryWithDefinedData, + ) + const { error, errorUpdatedAt, status } = projection ?? newState + const data = projection + ? projection.data + : (newState.data as unknown as TData | undefined) + const isPlaceholderData = projection?.isPlaceholderData ?? false const isFetching = fetchStatus === 'fetching' const isPending = status === 'pending' const isError = status === 'error' diff --git a/packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts b/packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts index c8e2a6691d2..6afd2eaf048 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts @@ -2,14 +2,22 @@ import type { RuntimeBinding } from '@tanstack/query-types/bindings' import type { Mutation } from './mutation' import type { MutationCache } from './mutationCache' import type { MutationObserver } from './mutationObserver' +import type { PlaceholderData, Select } from './projectionTypes' import type { Query } from './query' import type { QueryCache } from './queryCache' import type { QueryClient } from './queryClient' import type { QueryObserver } from './queryObserver' import type { RefetchInterval } from './refetchInterval' +import type { SerialScope } from './serialScope' /** Binds shared option and callback types to the concrete classes in this runtime. */ export interface QueryRuntime extends RuntimeBinding { + /** The optional selector implementation carried by a select option. */ + selectFeature: Select[0] + /** The optional placeholder implementation carried by a placeholderData option. */ + placeholderFeature: PlaceholderData[0] + /** Per-mutation queueing behavior, installed with serialScope. */ + mutationScope: SerialScope /** Polling can be installed independently on each observed query. */ refetchInterval: | false diff --git a/packages/react-query-no-core-pluggable/src/runtime/select.ts b/packages/react-query-no-core-pluggable/src/runtime/select.ts new file mode 100644 index 00000000000..7b69dbecc7e --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/select.ts @@ -0,0 +1,131 @@ +import { projectResult } from './projectResult' +import { replaceData, shallowEqualObjects } from './utils' +import type { Select } from './projectionTypes' +import type { Query } from './query' +import type { QueryObserverResultContext } from './queryObserver' +import type { QueryKey, QueryObserverOptionsBase } from './types' + +/* #__NO_SIDE_EFFECTS__ */ +/** + * Derives observer data from the cached query data. + * @param transform - Computes the selected data from the cached value. + * @returns A query selection option. + */ +export function select( + transform: (input: TInput) => TData, +): Select { + return [select, transform] +} + +select.project = projectResult +select.reuse = reuseSelection +select.resolve = resolveSelection + +/** + * Reuses the last committed selection when a reader sees the same input and selector. + * @param options - The reader's options. + * @param query - The query being read. + * @param committed - Memoized selections for the active observer. + * @param context - Selections local to this result reader. + */ +function reuseSelection< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + query: Query, + committed: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + context: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, +): void { + const transform = options.select?.[1] + const input = query.state.data + if ( + input !== undefined && + transform && + shallowEqualObjects( + { + input, + select: transform, + structuralSharing: options.structuralSharing, + }, + committed.selection?.key, + ) + ) { + context.selection = committed.selection + context.selected = committed.selected + } +} + +/** + * Memoizes the result or error of applying a selector to query or placeholder data. + * @param options - Options controlling structural sharing. + * @param transform - The caller's selector. + * @param context - Selection state for this observer or render. + * @param previousData - The previous data for structural sharing. + * @param input - The value passed to the selector. + * @param sourceQuery - The query supplying the selected data, if any. + */ +function resolveSelection< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +>( + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + transform: (data: TQueryData) => TData, + context: QueryObserverResultContext< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >, + previousData: TData | undefined, + input: TQueryData, + sourceQuery: Query | undefined, +): void { + const key = { + input, + select: transform, + structuralSharing: options.structuralSharing, + } + if (shallowEqualObjects(key, context.selection?.key)) return + try { + const data = replaceData(previousData, transform(input), options) + context.selected = { data, query: sourceQuery } + context.selection = { key } + } catch (error) { + context.selection = { + key, + failure: { error: error as TError, errorUpdatedAt: Date.now() }, + } + } +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/serialScope.ts b/packages/react-query-no-core-pluggable/src/runtime/serialScope.ts new file mode 100644 index 00000000000..96f042d860a --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/runtime/serialScope.ts @@ -0,0 +1,96 @@ +import type { Mutation } from './mutation' +import type { MutationCache } from './mutationCache' + +type QueuedMutation = Mutation + +// Each cache owns its own queues, even when clients reuse the same option. +const queues = new WeakMap>>() + +/** Runs mutations with the same ID in registration order within one cache. */ +class SerialScope { + constructor(readonly id: string) {} + + /** + * Registers a mutation in this cache's queue. + * @internal + * @param cache - The cache owning this queue. + * @param mutation - The mutation to register. + */ + add(cache: MutationCache, mutation: QueuedMutation): void { + let scopes = queues.get(cache) + if (!scopes) { + scopes = new Map() + queues.set(cache, scopes) + } + let queue = scopes.get(this.id) + if (!queue) { + queue = new Set() + scopes.set(this.id, queue) + } + queue.add(mutation) + } + + /** + * Releases the mutation and any empty queue. + * @internal + * @param cache - The cache owning this queue. + * @param mutation - The mutation to remove. + */ + remove(cache: MutationCache, mutation: QueuedMutation): void { + const scopes = queues.get(cache) + if (!scopes) return + const queue = scopes.get(this.id) + if (queue?.delete(mutation) && !queue.size) { + scopes.delete(this.id) + if (!scopes.size) queues.delete(cache) + } + } + + /** + * Checks whether this mutation is the first pending member. + * @internal + * @param cache - The cache owning this queue. + * @param mutation - The mutation to check. + * @returns Whether this mutation can start or continue. + */ + canRun(cache: MutationCache, mutation: QueuedMutation): boolean { + const queue = queues.get(cache)?.get(this.id) + if (queue) { + for (const entry of queue) { + if (entry.state.status === 'pending') return entry === mutation + } + } + return true + } + + /** + * Resumes the first waiting mutation after its predecessor settles. + * @internal + * @param cache - The cache owning this queue. + * @param mutation - The mutation to finish. + * @returns The next waiting mutation’s promise, if present. + */ + runNext( + cache: MutationCache, + mutation: QueuedMutation, + ): Promise | undefined { + const queue = queues.get(cache)?.get(this.id) + if (queue) { + for (const entry of queue) { + if (entry !== mutation && entry.state.isPaused) return entry.continue() + } + } + return undefined + } +} + +/** + * Selects FIFO execution for mutations sharing this ID in the same cache. + * @param id - The queue identifier, preserved in dehydrated mutation snapshots. + * @returns The value to pass to the mutation's `scope` option. + */ +export function serialScope(id: string): SerialScope { + return new SerialScope(id) +} + +export type { SerialScope } diff --git a/packages/react-query-no-core-pluggable/src/types.ts b/packages/react-query-no-core-pluggable/src/types.ts index ee037a36c4d..cd45fee106b 100644 --- a/packages/react-query-no-core-pluggable/src/types.ts +++ b/packages/react-query-no-core-pluggable/src/types.ts @@ -104,7 +104,7 @@ export type UsePrefetchQueryOptions< } /** - * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `queryClient.infiniteQuery`, + * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `infiniteQuery(client, options)`, * with a required `queryFn`. Pass `defaultQueryFn` to use the client defaults. * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. * @template TError - The type of errors your `queryFn` may throw. diff --git a/packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts b/packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts index ab42edd48b8..967af141bf0 100644 --- a/packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts +++ b/packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts @@ -33,7 +33,7 @@ import type { * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `infiniteQuery(client, options)`. * @example * ```tsx * import { useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' @@ -90,7 +90,7 @@ export function useInfiniteQuery< * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `infiniteQuery(client, options)`. * @example * Fetching the next page from a "Load More" button click: * ```tsx @@ -213,7 +213,7 @@ export function useInfiniteQuery< * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `infiniteQuery(client, options)`. * @example * Fetching the next page from a "Load More" button click: * ```tsx diff --git a/packages/react-query-no-core-pluggable/src/usePrefetchInfiniteQuery.tsx b/packages/react-query-no-core-pluggable/src/usePrefetchInfiniteQuery.tsx index ef9463f348d..0637ec05b99 100644 --- a/packages/react-query-no-core-pluggable/src/usePrefetchInfiniteQuery.tsx +++ b/packages/react-query-no-core-pluggable/src/usePrefetchInfiniteQuery.tsx @@ -1,4 +1,5 @@ import { useQueryClient } from './QueryClientProvider' +import { infiniteQuery } from './runtime/infiniteQuery' import { noop } from './runtime/utils' import type { DefaultError, @@ -11,7 +12,7 @@ import type { UsePrefetchInfiniteQueryOptions } from './types' /** * `usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render, * before a suspense boundary that wraps a component that uses `useSuspenseInfiniteQuery`. You can pass - * everything to `usePrefetchInfiniteQuery` that you can pass to `queryClient.infiniteQuery`, though + * everything to `usePrefetchInfiniteQuery` that you can pass to `infiniteQuery(client, options)`, though * `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required. Pass `defaultQueryFn` to use the client defaults. * * `getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages, @@ -21,7 +22,7 @@ import type { UsePrefetchInfiniteQueryOptions } from './types' * The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left * over from a previous attempt — so calling this on every render is cheap and won't refetch data that's * already there or already in flight. - * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `queryClient.infiniteQuery`. + * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `infiniteQuery(client, options)`. * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will * be used. * @example @@ -67,6 +68,6 @@ export function usePrefetchInfiniteQuery< const client = useQueryClient(queryClient) if (!client.getQueryState(options.queryKey)) { - void client.infiniteQuery(options).catch(noop) + void infiniteQuery(client, options).catch(noop) } } diff --git a/packages/react-query-no-core-pluggable/src/useQueries.ts b/packages/react-query-no-core-pluggable/src/useQueries.ts index 7270df47dc8..8c74bf2909e 100644 --- a/packages/react-query-no-core-pluggable/src/useQueries.ts +++ b/packages/react-query-no-core-pluggable/src/useQueries.ts @@ -17,6 +17,8 @@ import type { QueriesPlaceholderDataFunction, QueryKey, } from '@tanstack/query-types/bindings' +import type { placeholderData } from './runtime/placeholderData' +import type { Select } from './runtime/projectionTypes' import type { QueryClient } from './runtime/queryClient' import type { QueryFunction, @@ -41,7 +43,10 @@ type UseQueryOptionsForUseQueries< UseQueryOptions, 'placeholderData' | 'subscribed' > & { - placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction + placeholderData?: readonly [ + typeof placeholderData, + TQueryFnData | QueriesPlaceholderDataFunction, + ] } // Avoid TS depth-limit error in case of large array literal @@ -74,7 +79,7 @@ type GetUseQueryOptionsForUseQueries = queryFn?: | QueryFunction | SkipTokenForUseQueries - select?: (data: any) => infer TData + select?: Select throwOnError?: ThrowOnError } ? UseQueryOptionsForUseQueries< @@ -123,7 +128,7 @@ type GetUseQueryResult = queryFn?: | QueryFunction | SkipTokenForUseQueries - select?: (data: any) => infer TData + select?: Select throwOnError?: ThrowOnError } ? GetDefinedOrUndefinedQueryResult< @@ -335,7 +340,7 @@ type UseQueriesInput, TCombinedResult> = { * `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is * resolved before it reaches `useQueries`: * ```tsx - * import { queryOptions, useQueries } from '@tanstack/react-query-no-core-pluggable' + * import { queryOptions, select, useQueries } from '@tanstack/react-query-no-core-pluggable' * * const postOptions = (id: number) => * queryOptions({ @@ -349,7 +354,7 @@ type UseQueriesInput, TCombinedResult> = { * { * ...postOptions(id), * // ❌ `data` is `unknown` here - * select: (data) => data.title, + * select: [select, (data) => data.title], * }, * ], * }) @@ -359,7 +364,7 @@ type UseQueriesInput, TCombinedResult> = { * queryOptions({ * ...postOptions(id), * // ✅ `data` is `Post` - * select: (data) => data.title, + * select: [select, (data) => data.title], * }), * ], * }) diff --git a/packages/react-query-no-core-pluggable/src/useQuery.ts b/packages/react-query-no-core-pluggable/src/useQuery.ts index 070724dabf8..59896724e2e 100644 --- a/packages/react-query-no-core-pluggable/src/useQuery.ts +++ b/packages/react-query-no-core-pluggable/src/useQuery.ts @@ -168,13 +168,13 @@ export function useQuery< * `select` derives whatever `data` a component needs from the cached value, without changing what's * actually stored in the cache — the cache still holds the full `Post[]`, but `data` here is a `number`: * ```tsx - * import { useQuery } from '@tanstack/react-query-no-core-pluggable' + * import { select, useQuery } from '@tanstack/react-query-no-core-pluggable' * * function PostCount() { * const { data, isPending, isError, error } = useQuery({ * queryKey: ['posts'], * queryFn: fetchPosts, - * select: (posts) => posts.length, + * select: [select, (posts) => posts.length], * }) * * if (isPending) return 'Loading...' @@ -253,7 +253,7 @@ export function useQuery< * @example * Paginated data, keeping the previous page's data visible while the next page loads: * ```tsx - * import { keepPreviousData, useQuery } from '@tanstack/react-query-no-core-pluggable' + * import { keepPreviousData, placeholderData, useQuery } from '@tanstack/react-query-no-core-pluggable' * import { useState } from 'react' * * function Posts() { @@ -262,7 +262,7 @@ export function useQuery< * const { data, isPlaceholderData, isError, error } = useQuery({ * queryKey: ['posts', page], * queryFn: () => fetchPosts(page), - * placeholderData: keepPreviousData, + * placeholderData: placeholderData(keepPreviousData), * }) * * if (isError) return Error: {error.message} diff --git a/packages/react-query-no-core-pluggable/src/useSuspenseQueries.ts b/packages/react-query-no-core-pluggable/src/useSuspenseQueries.ts index 7265653bb3b..c5a75816eed 100644 --- a/packages/react-query-no-core-pluggable/src/useSuspenseQueries.ts +++ b/packages/react-query-no-core-pluggable/src/useSuspenseQueries.ts @@ -8,6 +8,8 @@ import type { QueriesPlaceholderDataFunction, QueryKey, } from '@tanstack/query-types/bindings' +import type { placeholderData } from './runtime/placeholderData' +import type { Select } from './runtime/projectionTypes' import type { QueryClient } from './runtime/queryClient' import type { QueryFunction, ThrowOnError } from './runtime/types' import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types' @@ -22,7 +24,10 @@ type UseSuspenseQueryOptionsForUseSuspenseQueries< UseSuspenseQueryOptions, 'placeholderData' > & { - placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction + placeholderData?: readonly [ + typeof placeholderData, + TQueryFnData | QueriesPlaceholderDataFunction, + ] } // Avoid TS depth-limit error in case of large array literal @@ -59,7 +64,7 @@ type GetUseSuspenseQueryOptions = queryFn?: | QueryFunction | SkipTokenForUseQueries - select?: (data: any) => infer TData + select?: Select throwOnError?: ThrowOnError } ? UseSuspenseQueryOptionsForUseSuspenseQueries< @@ -103,7 +108,7 @@ type GetUseSuspenseQueryResult = queryFn?: | QueryFunction | SkipTokenForUseQueries - select?: (data: any) => infer TData + select?: Select throwOnError?: ThrowOnError } ? UseSuspenseQueryResult< diff --git a/packages/react-query-no-core-pluggable/tests/compat-cacheOperations.ts b/packages/react-query-no-core-pluggable/tests/compat-cacheOperations.ts new file mode 100644 index 00000000000..bba5a0616b9 --- /dev/null +++ b/packages/react-query-no-core-pluggable/tests/compat-cacheOperations.ts @@ -0,0 +1,30 @@ +import { + cancelQueries, + getQueriesData, + invalidateQueries, + refetchQueries, + removeQueries, + resetQueries, + setQueriesData, +} from '../src/runtime/cacheOperations' +import { bindInfiniteQuery } from './compat-infiniteQuery' +import type { QueryClient } from '../src/runtime/queryClient' + +export function cacheOperations(client: TClient) { + function bind, TResult>( + operation: (client: QueryClient, ...args: TArgs) => TResult, + ) { + return (...args: TArgs) => operation(client, ...args) + } + + return { + infiniteQuery: bindInfiniteQuery(client), + getQueriesData: bind(getQueriesData), + setQueriesData: bind(setQueriesData), + removeQueries: bind(removeQueries), + resetQueries: bind(resetQueries), + cancelQueries: bind(cancelQueries), + invalidateQueries: bind(invalidateQueries), + refetchQueries: bind(refetchQueries), + } +} diff --git a/packages/react-query-no-core-pluggable/tests/compat-infiniteQuery.ts b/packages/react-query-no-core-pluggable/tests/compat-infiniteQuery.ts new file mode 100644 index 00000000000..2dffedf0a79 --- /dev/null +++ b/packages/react-query-no-core-pluggable/tests/compat-infiniteQuery.ts @@ -0,0 +1,76 @@ +import { infiniteQuery } from '../src/runtime/infiniteQuery' +import type { WithoutSkipToken } from '@tanstack/query-types/bindings' +import type { QueryClient } from '../src/runtime/queryClient' +import type { + DefaultError, + InfiniteData, + InfiniteQueryExecuteOptions, + QueryKey, +} from '../src/runtime/types' + +export function bindInfiniteQuery(client: QueryClient) { + function run< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: WithoutSkipToken< + InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + >, + ): Promise< + Array extends Array> + ? InfiniteData + : TData + > + function run< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): Promise< + | undefined + | (Array extends Array> + ? InfiniteData + : TData) + > + function run< + TQueryFnData, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, + >( + options: InfiniteQueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + ): Promise< + | undefined + | (Array extends Array> + ? InfiniteData + : TData) + > { + return infiniteQuery(client, options) + } + return run +} diff --git a/packages/react-query-no-core-pluggable/tests/compat-projection.ts b/packages/react-query-no-core-pluggable/tests/compat-projection.ts new file mode 100644 index 00000000000..c8c3b4c7de7 --- /dev/null +++ b/packages/react-query-no-core-pluggable/tests/compat-projection.ts @@ -0,0 +1,42 @@ +import { placeholderData, select } from '../src' + +export { select, placeholderData } +export const selectOption = 'select' +export const placeholderOption = 'placeholderData' +export type ProjectionInput = T extends readonly [unknown, infer Input] + ? Input + : T + +/** Returns the input supplied to a projection feature. */ +export function projectionInput( + option: readonly [unknown, T] | undefined, +): T | undefined { + return option?.[1] +} + +/** Preserves a shared test's optional callback when migrating a stored reference. */ +export function portSelect( + input: T, +): T extends undefined ? undefined : readonly [typeof select, T] { + return ( + input === undefined ? undefined : [select, input] + ) as T extends undefined ? undefined : readonly [typeof select, T] +} + +/** Preserves a shared test's optional placeholder when migrating a stored reference. */ +export function portPlaceholder( + input: T, +): T extends undefined ? undefined : readonly [typeof placeholderData, T] { + return ( + input === undefined ? undefined : [placeholderData, input] + ) as T extends undefined ? undefined : readonly [typeof placeholderData, T] +} + +/** A stored pluggable selection option for a shared React test. */ +export type SelectSetting = readonly [typeof select, TValue] + +/** A stored pluggable placeholder option for a shared React test. */ +export type PlaceholderSetting = readonly [ + typeof placeholderData, + TValue, +] diff --git a/packages/react-query-no-core-pluggable/tests/compat-scope.ts b/packages/react-query-no-core-pluggable/tests/compat-scope.ts new file mode 100644 index 00000000000..7dc29d882ba --- /dev/null +++ b/packages/react-query-no-core-pluggable/tests/compat-scope.ts @@ -0,0 +1 @@ +export { serialScope } from '../src/runtime/serialScope' diff --git a/packages/react-query-no-core/README.md b/packages/react-query-no-core/README.md index 8d49a7fca37..7140b4f9f42 100644 --- a/packages/react-query-no-core/README.md +++ b/packages/react-query-no-core/README.md @@ -30,4 +30,6 @@ export function App() { The original adapter and both experimental adapters share their TypeScript definitions through `@tanstack/query-types`. Each React adapter owns its provider context and each client owns its caches. +Use v6 option values directly, including `select: (data) => data.title`, `refetchInterval: 3000`, and `scope: { id: 'orders' }`. Imperative operations stay on the client, for example `client.infiniteQuery(options)` and `client.invalidateQueries({ queryKey: ['orders'] })`. The `queryOptions`, `infiniteQueryOptions`, and `mutationOptions` helpers all return their argument unchanged and share one JavaScript implementation. + React batches subscriber updates. Use `notifyManager.setScheduler` to choose when notifications run, or `setNotifyFunction` to wrap them in `act` during tests. To inspect the queries in a `QueriesObserver`, call `observer.getObservers().map((item) => item.getCurrentQuery())`. diff --git a/packages/react-query-no-core/src/runtime/infiniteQueryBehavior.ts b/packages/react-query-no-core/src/runtime/infiniteQueryBehavior.ts index ce7137c31b7..f7774ecfb81 100644 --- a/packages/react-query-no-core/src/runtime/infiniteQueryBehavior.ts +++ b/packages/react-query-no-core/src/runtime/infiniteQueryBehavior.ts @@ -4,119 +4,116 @@ import { ensureQueryFn, fetchSignal, } from './utils' -import type { QueryBehavior } from './query' +import type { FetchContext, Query } from './query' import type { InfiniteData, InfiniteQueryPageParamsOptions } from './types' import type { FetchSignalContext } from './utils' /** - * Creates the behavior that fetches the pages of an infinite query: the next or previous page for - * `fetchNextPage`/`fetchPreviousPage`, or all pages again from the start on a refetch. - * @param pages - The number of pages to fetch from the start when all pages are fetched again, - * e.g. from the `pages` option of `queryClient.infiniteQuery`. Defaults to the number of cached - * pages. - * @returns The query behavior to set on an infinite query. + * Installs 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. */ -export function infiniteQueryBehavior( - pages?: number, -): QueryBehavior> { - return { - onFetch: (context, query) => { - const options = context.options as InfiniteQueryPageParamsOptions - 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 +export function prepareInfiniteFetch( + context: FetchContext>, + query: Query, +): void { + 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) + 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) - } + // 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) - } + 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 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 page = await queryFn(queryFnContext) - const { maxPages } = context.options - return { - pages: addToArray(data.pages, page, maxPages, previous), - pageParams: addToArray(data.pageParams, param, maxPages, previous), - } - } + 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) + // 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 = pages ?? oldPages.length + 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) + // 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) { - context.fetchFn = () => { - return context.options.persister?.( - fetchFn as any, - { - client: context.client, - queryKey: context.queryKey, - meta: context.options.meta, - signal: context.signal, - }, - query, - ) - } - } else { - context.fetchFn = fetchFn - } - }, + return result + } + if (context.options.persister) { + context.fetchFn = () => { + return context.options.persister?.( + fetchFn as any, + { + client: context.client, + queryKey: context.queryKey, + meta: context.options.meta, + signal: context.signal, + }, + query, + ) + } + } else { + context.fetchFn = fetchFn } } diff --git a/packages/react-query-no-core/src/runtime/query.ts b/packages/react-query-no-core/src/runtime/query.ts index d874a18146c..befd4dfdd16 100644 --- a/packages/react-query-no-core/src/runtime/query.ts +++ b/packages/react-query-no-core/src/runtime/query.ts @@ -1,4 +1,4 @@ -import { infiniteQueryBehavior } from './infiniteQueryBehavior' +import { prepareInfiniteFetch } from './infiniteQueryBehavior' import { notifyManager } from './notifyManager' import { Removable } from './removable' import { CancelledError, canFetch, createRetryer } from './retryer' @@ -605,10 +605,13 @@ export class Query< addSignalProperty(context) if (this.#queryType === 'infinite') { - const behavior = infiniteQueryBehavior( - (this.options as { pages?: number }).pages, - ) as QueryBehavior - behavior.onFetch(context, this as unknown as Query) + const prepare = prepareInfiniteFetch as QueryBehavior< + TQueryFnData, + TError, + TData, + TQueryKey + >['onFetch'] + prepare(context, this as unknown as Query) } // Store state in case the current fetch needs to be reverted diff --git a/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx b/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx index b9e0ccc680f..ca56a81d79c 100644 --- a/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx +++ b/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx @@ -1,5 +1,7 @@ import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' +import { selectOption } from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { defaultQueryFn } from '..' import { infiniteQueryOptions } from '../infiniteQueryOptions' @@ -43,7 +45,7 @@ describe('infiniteQueryOptions', () => { staleTime: 1000, getNextPageParam: () => 1, initialPageParam: 1, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf>() }, }) @@ -71,7 +73,7 @@ describe('infiniteQueryOptions', () => { queryFn: () => Promise.resolve('string'), getNextPageParam: () => 1, initialPageParam: 1, - select: (data) => data.pages, + [selectOption]: (data) => data.pages, }) const { data } = useInfiniteQuery(options) @@ -99,7 +101,7 @@ describe('infiniteQueryOptions', () => { queryFn: () => Promise.resolve('string'), getNextPageParam: () => 1, initialPageParam: 1, - select: (data) => data.pages, + [selectOption]: (data) => data.pages, }) const { data } = useSuspenseInfiniteQuery(options) @@ -115,7 +117,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 1, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await cacheOperations(new QueryClient()).infiniteQuery(options) expectTypeOf(data).toEqualTypeOf>() }) @@ -126,10 +128,10 @@ describe('infiniteQueryOptions', () => { queryFn: () => Promise.resolve('string'), getNextPageParam: () => 1, initialPageParam: 1, - select: (data) => data.pages, + [selectOption]: (data) => data.pages, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await cacheOperations(new QueryClient()).infiniteQuery(options) expectTypeOf(data).toEqualTypeOf>() }) @@ -143,7 +145,7 @@ describe('infiniteQueryOptions', () => { enabled: false, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await cacheOperations(new QueryClient()).infiniteQuery(options) expectTypeOf(data).toEqualTypeOf>() }) @@ -156,7 +158,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 1, }) - const data = await new QueryClient().infiniteQuery(options) + const data = await cacheOperations(new QueryClient()).infiniteQuery(options) expectTypeOf(data).toEqualTypeOf< InfiniteData | undefined @@ -189,7 +191,7 @@ describe('infiniteQueryOptions', () => { const { queryKey: tagged } = infiniteQueryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve('string'), - select: (data) => data.pages, + [selectOption]: (data) => data.pages, getNextPageParam: () => 1, initialPageParam: 1, }) diff --git a/packages/react-query/src/__tests__/placeholderData.test.ts b/packages/react-query/src/__tests__/placeholderData.test.ts index 17b5e7a4d89..9dbdae7eb21 100644 --- a/packages/react-query/src/__tests__/placeholderData.test.ts +++ b/packages/react-query/src/__tests__/placeholderData.test.ts @@ -1,7 +1,15 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { renderHook } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueryClient, useQueries, useQuery } from '..' +import type { + PlaceholderSetting, + SelectSetting, +} from '@tanstack/query-test-utils/projection' class Placeholder { constructor(readonly value: number) {} @@ -10,8 +18,8 @@ class Placeholder { type Options = { queryKey: ReadonlyArray queryFn: () => Promise - placeholderData: Placeholder - select?: (data: Placeholder) => Placeholder | Set + placeholderData: PlaceholderSetting + select?: SelectSetting<(data: Placeholder) => Placeholder | Set> } function useMultiple(options: Options, client: QueryClient) { @@ -78,8 +86,8 @@ describe('placeholder updates', () => { { queryKey: key, queryFn: () => new Promise(() => {}), - placeholderData: input, - select, + [placeholderOption]: input, + [selectOption]: select, }, client, ) @@ -108,7 +116,16 @@ describe('placeholder updates', () => { const queryFn = () => sleep(10).then(() => ({ value: 1 })) const { result, rerender } = renderHook(() => { const [{ data, error }] = useQueries( - { queries: [{ queryKey, queryFn, placeholderData, select }] }, + { + queries: [ + { + queryKey, + queryFn, + [placeholderOption]: placeholderData, + [selectOption]: select, + }, + ], + }, client, ) return { data, error } diff --git a/packages/react-query/src/__tests__/queryOptions.test-d.tsx b/packages/react-query/src/__tests__/queryOptions.test-d.tsx index b48d2dd7259..7eadbb77a48 100644 --- a/packages/react-query/src/__tests__/queryOptions.test-d.tsx +++ b/packages/react-query/src/__tests__/queryOptions.test-d.tsx @@ -1,5 +1,6 @@ import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' +import { selectOption } from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { defaultQueryFn } from '..' import { queryOptions } from '../queryOptions' @@ -38,7 +39,7 @@ describe('queryOptions', () => { queryKey: createKey(), queryFn: () => Promise.resolve(5), staleTime: 1000, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf() }, }) @@ -78,7 +79,7 @@ describe('queryOptions', () => { const options = queryOptions({ queryKey: ['key'], queryFn: () => Promise.resolve(5), - select: (data) => data.toString(), + [selectOption]: (data) => data.toString(), }) const data = await new QueryClient().query(options) @@ -100,7 +101,7 @@ describe('queryOptions', () => { const options = queryOptions({ queryKey: ['key'], queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5), - select: (data) => data.toFixed(), + [selectOption]: (data) => data.toFixed(), }) const data = await new QueryClient().query(options) @@ -151,7 +152,7 @@ describe('queryOptions', () => { const { queryKey: tagged } = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(5), - select: (data) => data.toString(), + [selectOption]: (data) => data.toString(), }) expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf() diff --git a/packages/react-query/src/__tests__/ssr.test.tsx b/packages/react-query/src/__tests__/ssr.test.tsx index 8bd86910673..9329be7dd6b 100644 --- a/packages/react-query/src/__tests__/ssr.test.tsx +++ b/packages/react-query/src/__tests__/ssr.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import * as React from 'react' import { renderToString } from 'react-dom/server' import { @@ -175,7 +176,7 @@ describe('Server Side Rendering', () => { ) } - void queryClient + void cacheOperations(queryClient) .infiniteQuery({ queryKey: key, queryFn, diff --git a/packages/react-query/src/__tests__/transition.test.tsx b/packages/react-query/src/__tests__/transition.test.tsx index b541cdd03c7..cf561c3d2af 100644 --- a/packages/react-query/src/__tests__/transition.test.tsx +++ b/packages/react-query/src/__tests__/transition.test.tsx @@ -1,4 +1,8 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { act, fireEvent } from '@testing-library/react' import * as React from 'react' import { startTransition, useDeferredValue } from 'react' @@ -33,7 +37,7 @@ describe('react transitions', () => { queryKey: [key, id], queryFn: () => Promise.resolve({ value: id }), staleTime: Infinity, - select, + [selectOption]: select, }) if (id === 2) { renderB(data) @@ -167,7 +171,7 @@ describe('react transitions', () => { const query = useSuspenseQuery({ queryKey: [key, queryCount], queryFn: () => queryFn(queryCount), - placeholderData: + [placeholderOption]: placeholderMode === 'static' ? 'placeholder' : keepPreviousData, }) @@ -242,7 +246,7 @@ describe('react transitions', () => { const query = useSuspenseQuery({ queryKey: [...key, 'placeholder', count], queryFn: () => placeholderQueryFn(count), - placeholderData: + [placeholderOption]: placeholderMode === 'static' ? 'placeholder' : keepPreviousData, }) return
{query.data}
@@ -324,7 +328,7 @@ describe('react transitions', () => { const placeholderQuery = useSuspenseQuery({ queryKey: [...key, 'placeholder', count], queryFn: () => placeholderQueryFn(count), - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) const suspenseQuery = useSuspenseQuery({ queryKey: [...key, 'suspense', count], diff --git a/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx b/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx index 82eaaaf3a0e..c32399f4a04 100644 --- a/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx @@ -1,5 +1,7 @@ import { QueryClient } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' +import { selectOption } from '@tanstack/query-test-utils/projection' import { describe, expectTypeOf, it } from 'vitest' import { useInfiniteQuery } from '../useInfiniteQuery' import type { InfiniteData } from '@tanstack/query-core' @@ -19,7 +21,7 @@ describe('pageParam', () => { it('should define type of param passed to queryFunctionContext with initialPageParam for infiniteQuery', () => { const queryClient = new QueryClient() - queryClient.infiniteQuery({ + cacheOperations(queryClient).infiniteQuery({ queryKey: ['key'], queryFn: ({ pageParam }) => { expectTypeOf(pageParam).toEqualTypeOf() @@ -56,7 +58,7 @@ describe('select', () => { }, initialPageParam: 1, getNextPageParam: () => undefined, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf>() return 'selected' as const }, diff --git a/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx b/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx index 95b596bc1b2..07a85bd20f7 100644 --- a/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx +++ b/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx @@ -1,4 +1,9 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { fireEvent, render } from '@testing-library/react' import { createRenderStream } from '@testing-library/react-render-stream' import * as React from 'react' @@ -187,7 +192,7 @@ describe('useInfiniteQuery', () => { sleep(10).then(() => `${pageParam}-${order}`), getNextPageParam: () => 1, initialPageParam: 0, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, notifyOnChangeProps: 'all', }) @@ -271,7 +276,7 @@ describe('useInfiniteQuery', () => { const state = useInfiniteQuery({ queryKey: key, queryFn: () => sleep(10).then(() => ({ count: 1 })), - select: (data) => ({ + [selectOption]: (data) => ({ pages: data.pages.map((x) => `count: ${x.count}`), pageParams: data.pageParams, }), @@ -310,13 +315,16 @@ describe('useInfiniteQuery', () => { const state = useInfiniteQuery({ queryKey: key, queryFn: () => sleep(10).then(() => ({ count: 1 })), - select: React.useCallback((data: InfiniteData<{ count: number }>) => { - selectCalled++ - return { - pages: data.pages.map((x) => ({ ...x, id: Math.random() })), - pageParams: data.pageParams, - } - }, []), + [selectOption]: React.useCallback( + (data: InfiniteData<{ count: number }>) => { + selectCalled++ + return { + pages: data.pages.map((x) => ({ ...x, id: Math.random() })), + pageParams: data.pageParams, + } + }, + [], + ), getNextPageParam: () => undefined, initialPageParam: 0, }) @@ -356,7 +364,7 @@ describe('useInfiniteQuery', () => { const state = useInfiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => sleep(10).then(() => pageParam), - select: (data) => ({ + [selectOption]: (data) => ({ pages: [...data.pages].reverse(), pageParams: [...data.pageParams].reverse(), }), @@ -1429,7 +1437,7 @@ describe('useInfiniteQuery', () => { queryKey: key, queryFn: ({ pageParam }) => sleep(10).then(() => pageParam), getNextPageParam: (lastPage) => (lastPage === 1 ? 2 : undefined), - select: (data) => ({ + [selectOption]: (data) => ({ pages: data.pages.map((x) => x.toString()), pageParams: data.pageParams, }), @@ -1534,7 +1542,9 @@ describe('useInfiniteQuery', () => { // makes an actual network request // and calls invalidateQueries in an onSuccess items.splice(4, 1) - queryClient.invalidateQueries({ queryKey: key }) + cacheOperations(queryClient).invalidateQueries({ + queryKey: key, + }) }} > Remove item diff --git a/packages/react-query/src/__tests__/useMutation.test.tsx b/packages/react-query/src/__tests__/useMutation.test.tsx index 64dd1034206..011c12a1e12 100644 --- a/packages/react-query/src/__tests__/useMutation.test.tsx +++ b/packages/react-query/src/__tests__/useMutation.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { act, fireEvent, render } from '@testing-library/react' import * as React from 'react' import { ErrorBoundary } from 'react-error-boundary' @@ -2314,7 +2315,7 @@ describe('useMutation', () => { mutationFn: () => sleep(10).then(() => Promise.reject(new Error('Some error'))), onMutate: async (newTodo: string) => { - await queryClient.cancelQueries({ queryKey: key }) + await cacheOperations(queryClient).cancelQueries({ queryKey: key }) const previousTodos = queryClient.getQueryData>(key) queryClient.setQueryData>(key, (old) => [ @@ -2351,7 +2352,7 @@ describe('useMutation', () => { const { mutate } = useMutation({ mutationFn: (newTodo: string) => sleep(10).then(() => newTodo), onMutate: async (newTodo: string) => { - await queryClient.cancelQueries({ queryKey: key }) + await cacheOperations(queryClient).cancelQueries({ queryKey: key }) const previousTodos = queryClient.getQueryData>(key) queryClient.setQueryData>(key, (old) => [ @@ -2610,7 +2611,7 @@ describe('useMutation', () => { const { mutate } = useMutation({ mutationFn: () => sleep(10).then(() => 'mutated'), onSuccess: (_data, _variables, _onMutateResult, context) => { - context.client.invalidateQueries({ queryKey: key }) + cacheOperations(context.client).invalidateQueries({ queryKey: key }) }, }) diff --git a/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx b/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx index 7ca8f841e6f..221cdd710d9 100644 --- a/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx +++ b/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { act, fireEvent } from '@testing-library/react' import * as React from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -113,7 +114,9 @@ describe('usePrefetchInfiniteQuery', () => { allPages.length < data.length ? allPages.length : undefined, } - void queryClient.infiniteQuery({ ...queryOpts, pages: 3 }).catch(noop) + void cacheOperations(queryClient) + .infiniteQuery({ ...queryOpts, pages: 3 }) + .catch(noop) await vi.advanceTimersByTimeAsync(30) queryOpts.queryFn.mockClear() diff --git a/packages/react-query/src/__tests__/usePrefetchQuery.test-d.tsx b/packages/react-query/src/__tests__/usePrefetchQuery.test-d.tsx index f48b05158b1..e156bc4cf03 100644 --- a/packages/react-query/src/__tests__/usePrefetchQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/usePrefetchQuery.test-d.tsx @@ -1,5 +1,6 @@ import { createKey } from '@tanstack/query-test-utils' import { refetchInterval } from '@tanstack/query-test-utils/polling' +import { selectOption } from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { skipToken, usePrefetchQuery } from '..' @@ -63,7 +64,7 @@ describe('usePrefetchQuery', () => { usePrefetchQuery({ queryKey: createKey(), queryFn: () => Promise.resolve('data'), - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf<{ value: string }>() return data.value.length diff --git a/packages/react-query/src/__tests__/useQueries.test-d.tsx b/packages/react-query/src/__tests__/useQueries.test-d.tsx index 5c153b0c504..05c1ce0125a 100644 --- a/packages/react-query/src/__tests__/useQueries.test-d.tsx +++ b/packages/react-query/src/__tests__/useQueries.test-d.tsx @@ -1,4 +1,8 @@ import { createKey } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { describe, expectTypeOf, it } from 'vitest' import { skipToken } from '..' import { queryOptions } from '../queryOptions' @@ -67,13 +71,13 @@ describe('useQueries', () => { const query1 = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data > 1, + [selectOption]: (data) => data > 1, }) const query2 = { queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data: number) => data > 1, + [selectOption]: (data: number) => data > 1, } const queryResults = useQueries({ queries: [query1, query2] }) @@ -223,7 +227,7 @@ describe('useQueries', () => { { queryKey: key1, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return a.toLowerCase() }, @@ -231,7 +235,7 @@ describe('useQueries', () => { { queryKey: key2, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return parseInt(a) }, @@ -253,22 +257,22 @@ describe('useQueries', () => { { queryKey: key1, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return a.toLowerCase() }, - placeholderData: 'string', + [placeholderOption]: 'string', // @ts-expect-error (initialData: string) initialData: 123, }, { queryKey: key2, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return parseInt(a) }, - placeholderData: 'string', + [placeholderOption]: 'string', // @ts-expect-error (initialData: string) initialData: 123, }, @@ -343,7 +347,7 @@ describe('useQueries', () => { { queryKey: key1, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return a.toLowerCase() }, @@ -351,7 +355,7 @@ describe('useQueries', () => { { queryKey: key2, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return parseInt(a) }, @@ -373,7 +377,7 @@ describe('useQueries', () => { { queryKey: key1, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return a as string }, @@ -381,7 +385,7 @@ describe('useQueries', () => { { queryKey: key2, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return a as number }, @@ -408,22 +412,22 @@ describe('useQueries', () => { { queryKey: key1, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return a.toLowerCase() }, - placeholderData: 'string', + [placeholderOption]: 'string', // @ts-expect-error (initialData: string) initialData: 123, }, { queryKey: key2, queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return parseInt(a) }, - placeholderData: 'string', + [placeholderOption]: 'string', // @ts-expect-error (initialData: string) initialData: 123, }, @@ -453,7 +457,7 @@ describe('useQueries', () => { queryOptions({ queryKey: createKey(), queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return a.toLowerCase() }, @@ -461,7 +465,7 @@ describe('useQueries', () => { queryOptions({ queryKey: createKey(), queryFn: () => 'string', - select: (a) => { + [selectOption]: (a) => { expectTypeOf(a).toEqualTypeOf() return parseInt(a) }, @@ -522,7 +526,7 @@ describe('useQueries', () => { queries: Array(50).map((_, i) => ({ queryKey: ['key', i] as const, queryFn: () => i + 10, - select: (data: number) => data.toString(), + [selectOption]: (data: number) => data.toString(), })), }) expectTypeOf(result2).toEqualTypeOf< @@ -533,7 +537,7 @@ describe('useQueries', () => { queries: Array(50).map((_, i) => ({ queryKey: ['key', i] as const, queryFn: () => i + 10, - select: (data: number) => data.toString(), + [selectOption]: (data: number) => data.toString(), throwOnError, })), }) @@ -554,7 +558,7 @@ describe('useQueries', () => { { queryKey: key3, queryFn: () => ['string[]'], - select: () => 123, + [selectOption]: () => 123, }, { queryKey: key5, @@ -580,7 +584,7 @@ describe('useQueries', () => { { queryKey: key1, queryFn: () => 'string', - placeholderData: 'string', + [placeholderOption]: 'string', // @ts-expect-error (initialData: string) initialData: 123, }, @@ -588,7 +592,7 @@ describe('useQueries', () => { queryKey: key2, queryFn: () => 123, // @ts-expect-error (placeholderData: number) - placeholderData: 'string', + [placeholderOption]: 'string', initialData: 123, }, ], @@ -615,7 +619,7 @@ describe('useQueries', () => { { queryKey: key4, queryFn: () => 'string', - select: (a: string) => parseInt(a), + [selectOption]: (a: string) => parseInt(a), }, { queryKey: key5, @@ -630,14 +634,14 @@ describe('useQueries', () => { queries: Array(50).map((_, i) => ({ queryKey: ['key', i] as const, queryFn: () => i + 10, - select: (data: number) => data.toString(), + [selectOption]: (data: number) => data.toString(), })), }) useQueries({ queries: Array(50).map((_, i) => ({ queryKey: ['key', i] as const, queryFn: () => i + 10, - select: (data: number) => data.toString(), + [selectOption]: (data: number) => data.toString(), })), }) @@ -655,12 +659,12 @@ describe('useQueries', () => { { queryKey: key4, queryFn: () => 'string', - select: (a: string) => parseInt(a), + [selectOption]: (a: string) => parseInt(a), }, { queryKey: key5, queryFn: () => 'string', - select: (a: string) => parseInt(a), + [selectOption]: (a: string) => parseInt(a), throwOnError, }, ], @@ -838,12 +842,12 @@ describe('useQueries', () => { { queryKey: getQueryKeyA(), queryFn: getQueryFunctionA(), - select: getSelectorA(), + [selectOption]: getSelectorA(), }, { queryKey: getQueryKeyB('id'), queryFn: getQueryFunctionB(), - select: getSelectorB(), + [selectOption]: getSelectorB(), }, ], }) @@ -858,7 +862,7 @@ describe('useQueries', () => { Array(10).map(() => ({ queryKey: getQueryKeyA(), queryFn: getQueryFunctionA(), - select: getSelectorA(), + [selectOption]: getSelectorA(), })), ) @@ -884,7 +888,7 @@ describe('useQueries', () => { { queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toBeUnknown() // @ts-expect-error `data` is `unknown`, not the expected `number` return data.toFixed() @@ -900,7 +904,7 @@ describe('useQueries', () => { { queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data: number) => data.toFixed(), + [selectOption]: (data: number) => data.toFixed(), }, ], }) @@ -922,7 +926,7 @@ describe('useQueries', () => { const options = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf() return data.toFixed() }, @@ -940,7 +944,7 @@ describe('useQueries', () => { queries: [ queryOptions({ ...baseOptions, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf() return data.toFixed() }, @@ -956,13 +960,13 @@ describe('useQueries', () => { const baseOptions = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data + 1, + [selectOption]: (data) => data + 1, }) const queryResults = useQueries({ queries: [ queryOptions({ ...baseOptions, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf() return data.toFixed() }, @@ -984,7 +988,7 @@ describe('useQueries', () => { // @ts-expect-error Without an annotation the inline `select` receives `data: unknown`, which makes the whole spread query object unassignable to the expected options type { ...options, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toBeUnknown() return data }, @@ -999,7 +1003,9 @@ describe('useQueries', () => { queryFn: () => Promise.resolve(1), }) const queryResults = useQueries({ - queries: [{ ...options, select: (data: number) => data.toFixed() }], + queries: [ + { ...options, [selectOption]: (data: number) => data.toFixed() }, + ], }) expectTypeOf(queryResults[0].data).toEqualTypeOf() }) @@ -1008,14 +1014,14 @@ describe('useQueries', () => { const options = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data + 1, + [selectOption]: (data) => data + 1, }) useQueries({ queries: [ // @ts-expect-error Without an annotation the inline `select` receives `data: unknown`, which makes the whole spread query object unassignable to the expected options type { ...options, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toBeUnknown() return data }, @@ -1028,10 +1034,12 @@ describe('useQueries', () => { const options = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data + 1, + [selectOption]: (data) => data + 1, }) const queryResults = useQueries({ - queries: [{ ...options, select: (data: number) => data.toFixed() }], + queries: [ + { ...options, [selectOption]: (data: number) => data.toFixed() }, + ], }) expectTypeOf(queryResults[0].data).toEqualTypeOf() }) diff --git a/packages/react-query/src/__tests__/useQueries.test.tsx b/packages/react-query/src/__tests__/useQueries.test.tsx index 2987133043c..3b9d5d56b54 100644 --- a/packages/react-query/src/__tests__/useQueries.test.tsx +++ b/packages/react-query/src/__tests__/useQueries.test.tsx @@ -1,4 +1,6 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' +import { selectOption } from '@tanstack/query-test-utils/projection' import { fireEvent, render } from '@testing-library/react' import * as React from 'react' import { ErrorBoundary } from 'react-error-boundary' @@ -70,7 +72,7 @@ describe('useQueries', () => { { queryKey: key, queryFn: () => Promise.resolve([1, 2, 3]), - select, + [selectOption]: select, staleTime: Infinity, structuralSharing: false, }, @@ -141,7 +143,7 @@ describe('useQueries', () => { { queryKey, queryFn, - select: (value: string) => { + [selectOption]: (value: string) => { if (throws) throw new Error(value + ' with a select error') return new Set([value]) }, @@ -901,7 +903,7 @@ describe('useQueries', () => { // both pending, one pending, both resolved expect(spy).toHaveBeenCalledTimes(3) - client.refetchQueries() + cacheOperations(client).refetchQueries() await vi.advanceTimersByTimeAsync(21) // no increase because result hasn't changed @@ -914,7 +916,7 @@ describe('useQueries', () => { value = 1 - client.refetchQueries() + cacheOperations(client).refetchQueries() await vi.advanceTimersByTimeAsync(21) expect( diff --git a/packages/react-query/src/__tests__/useQuery.test-d.tsx b/packages/react-query/src/__tests__/useQuery.test-d.tsx index 3299b16fd4d..2c53fea4242 100644 --- a/packages/react-query/src/__tests__/useQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/useQuery.test-d.tsx @@ -1,4 +1,5 @@ import { createKey } from '@tanstack/query-test-utils' +import { selectOption } from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { defaultQueryFn } from '..' import { queryOptions } from '../queryOptions' @@ -229,7 +230,7 @@ describe('useQuery', () => { const query = useQuery({ ...options, - select: (data) => data > 1, + [selectOption]: (data) => data > 1, }) expectTypeOf(query.data).toEqualTypeOf() diff --git a/packages/react-query/src/__tests__/useQuery.test.tsx b/packages/react-query/src/__tests__/useQuery.test.tsx index 457658026bc..ff46ddab48a 100644 --- a/packages/react-query/src/__tests__/useQuery.test.tsx +++ b/packages/react-query/src/__tests__/useQuery.test.tsx @@ -3,7 +3,12 @@ import { mockVisibilityState, sleep, } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { refetchInterval } from '@tanstack/query-test-utils/polling' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { act, fireEvent, render, renderHook } from '@testing-library/react' import * as React from 'react' import { ErrorBoundary } from 'react-error-boundary' @@ -90,7 +95,7 @@ describe('useQuery', () => { queryKey: [key, id], queryFn: () => Promise.resolve({ value: id }), staleTime: Infinity, - select, + [selectOption]: select, }) results.push(data) return
{data?.selected}
@@ -127,7 +132,7 @@ describe('useQuery', () => { queryKey: key, queryFn: () => Promise.resolve(todos), staleTime: Infinity, - select: React.useCallback( + [selectOption]: React.useCallback( (items: typeof todos) => items.filter((todo) => todo.completed === completed), [completed], @@ -177,7 +182,9 @@ describe('useQuery', () => { ) try { await act(() => vi.advanceTimersByTimeAsync(0)) - await act(() => queryClient.cancelQueries({ queryKey: key })) + await act(() => + cacheOperations(queryClient).cancelQueries({ queryKey: key }), + ) await act(() => vi.advanceTimersByTimeAsync(1)) expect(view.result.current.fetchStatus).toBe('idle') focusManager.setFocused(false) @@ -665,7 +672,7 @@ describe('useQuery', () => { @@ -1010,7 +1021,11 @@ describe('useQuery', () => { return (
- @@ -1125,7 +1140,11 @@ describe('useQuery', () => { return (
isFetching: {result.isFetching}
- data: {result.data} @@ -1161,7 +1180,9 @@ describe('useQuery', () => { return (
@@ -1209,7 +1230,7 @@ describe('useQuery', () => { React.useEffect(() => { setActTimeout(() => { - queryClient.refetchQueries({ queryKey: key }) + cacheOperations(queryClient).refetchQueries({ queryKey: key }) }, 20) }, []) @@ -1248,7 +1269,7 @@ describe('useQuery', () => { React.useEffect(() => { setActTimeout(() => { - queryClient.invalidateQueries({ queryKey: key }) + cacheOperations(queryClient).invalidateQueries({ queryKey: key }) }, 10) }, []) @@ -1332,7 +1353,7 @@ describe('useQuery', () => { const state = useQuery({ queryKey: [key, count], queryFn: () => sleep(10).then(() => count), - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) states.push(state) @@ -1394,10 +1415,10 @@ describe('useQuery', () => { const state = useQuery({ queryKey: [key, count], queryFn: () => sleep(10).then(() => ({ count })), - select(data) { + [selectOption](data) { return data.count }, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) states.push(state) @@ -1460,10 +1481,10 @@ describe('useQuery', () => { const state = useQuery({ queryKey: [key, count], queryFn: () => sleep(10).then(() => ({ count })), - select(data) { + [selectOption](data) { return data.count }, - placeholderData: (prevData, prevQuery) => { + [placeholderOption]: (prevData, prevQuery) => { if (prevQuery) { keys.push(prevQuery.queryKey) } @@ -1509,10 +1530,10 @@ describe('useQuery', () => { const state = useQuery({ queryKey: [key, count], queryFn: () => sleep(10).then(() => ({ count })), - select(data) { + [selectOption](data) { return data.count }, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) states.push(state) @@ -1594,7 +1615,7 @@ describe('useQuery', () => { return Promise.resolve(count) }), retry: false, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) states.push(state) @@ -1685,7 +1706,7 @@ describe('useQuery', () => { queryKey: [key, count], queryFn: () => sleep(10).then(() => count), initialData: 99, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) states.push(state) @@ -1753,7 +1774,7 @@ describe('useQuery', () => { queryKey: [key, count], queryFn: () => sleep(10).then(() => count), enabled: false, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, notifyOnChangeProps: 'all', }) @@ -1845,7 +1866,7 @@ describe('useQuery', () => { queryKey: [key, count], queryFn: () => sleep(10).then(() => count), enabled: false, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, notifyOnChangeProps: 'all', }) @@ -2153,7 +2174,7 @@ describe('useQuery', () => { const state = useQuery({ queryKey: key, queryFn: () => ({ name: 'test' }), - select: (data) => data.name, + [selectOption]: (data) => data.name, }) states.push(state) @@ -2983,7 +3004,11 @@ describe('useQuery', () => { return (
- {show && } @@ -3797,7 +3822,7 @@ describe('useQuery', () => { initialData() { return filter === '' ? initialTodos : undefined }, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, staleTime: 5000, }) @@ -4224,7 +4249,7 @@ describe('useQuery', () => { const state = useQuery({ queryKey: key1, queryFn: () => 'data', - placeholderData: 'placeholder', + [placeholderOption]: 'placeholder', }) states.push(state) @@ -4267,7 +4292,7 @@ describe('useQuery', () => { const state = useQuery({ queryKey: key1, queryFn: () => 'data', - placeholderData: 'placeholder', + [placeholderOption]: 'placeholder', enabled: count === 0, }) @@ -4327,8 +4352,8 @@ describe('useQuery', () => { const state = useQuery({ queryKey: key1, queryFn: () => 1, - placeholderData: 23, - select: (data) => String(data * 2), + [placeholderOption]: 23, + [selectOption]: (data) => String(data * 2), }) states.push(state) @@ -4370,11 +4395,11 @@ describe('useQuery', () => { const state = useQuery({ queryKey: key1, queryFn: () => 1, - placeholderData: () => { + [placeholderOption]: () => { placeholderFunctionRunCount++ return 23 }, - select: (data) => String(data * 2), + [selectOption]: (data) => String(data * 2), }) states.push(state) @@ -4426,14 +4451,14 @@ describe('useQuery', () => { const state = useQuery({ queryKey: key1, queryFn: () => sleep(10).then(() => 0), - select: React.useCallback( + [selectOption]: React.useCallback( (data: number) => { selectRun++ return `selected ${data + count}` }, [count], ), - placeholderData: 99, + [placeholderOption]: 99, }) return ( @@ -4469,13 +4494,13 @@ describe('useQuery', () => { queryKey: key1, queryFn: () => sleep(10).then(() => 0), - select: React.useCallback( + [selectOption]: React.useCallback( (data: number) => { return `selected ${data + count}` }, [count], ), - placeholderData: 99, + [placeholderOption]: 99, }) return ( @@ -4516,7 +4541,7 @@ describe('useQuery', () => { queryKey: key1, queryFn: () => sleep(10).then(() => [1, 2]), - select: (res) => res.map((x) => x + 1), + [selectOption]: (res) => res.map((x) => x + 1), }) React.useEffect(() => { @@ -4719,7 +4744,11 @@ describe('useQuery', () => { return (
-
data: {state.data ?? 'null'}
@@ -4795,7 +4824,11 @@ describe('useQuery', () => { return (
-
data: {state.data ?? 'null'}
@@ -5218,7 +5251,11 @@ describe('useQuery', () => {
failureReason: {state.failureReason ?? 'null'}
data: {state.data}
@@ -5276,7 +5313,11 @@ describe('useQuery', () => {
data: {state.data}
@@ -5322,7 +5363,11 @@ describe('useQuery', () => {
data: {state.data}
@@ -5367,7 +5412,11 @@ describe('useQuery', () => {
data: {state.data}
@@ -5413,7 +5462,11 @@ describe('useQuery', () => {
data: {state.data}
@@ -5630,7 +5683,9 @@ describe('useQuery', () => { return (
@@ -5694,7 +5749,11 @@ describe('useQuery', () => { {show && } @@ -6181,7 +6240,7 @@ describe('useQuery', () => { const [id, setId] = React.useState(1) const { data } = useQuery({ - select: selector, + [selectOption]: selector, queryKey: [key, 'user', id], queryFn: () => fetchNumber(id), }) @@ -6248,10 +6307,10 @@ describe('useQuery', () => { const [id, setId] = React.useState(1) const { data } = useQuery({ - select: selector, + [selectOption]: selector, queryKey: [key, 'user', id], queryFn: () => fetchNumber(id), - placeholderData: { numbers: { current: { id: 99 } } }, + [placeholderOption]: { numbers: { current: { id: 99 } } }, }) React.useEffect(() => { @@ -6337,7 +6396,7 @@ describe('useQuery', () => { staleTime: Infinity, queryKey: [key, steps[count]], queryFn: () => sleep(10).then(() => steps[count]), - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) states.push(state) @@ -7123,8 +7182,8 @@ describe('useQuery', () => { queryKey: [...key, id], queryFn: () => [id], enabled: id !== '', - placeholderData: keepPreviousData, - select: (items) => items.find((item) => item === id), + [placeholderOption]: keepPreviousData, + [selectOption]: (items) => items.find((item) => item === id), }) return ( @@ -7151,8 +7210,8 @@ describe('useQuery', () => { queryKey: [...key, id], queryFn: () => [id], enabled: id !== '', - placeholderData: keepPreviousData, - select: (items) => items.find((item) => item === id), + [placeholderOption]: keepPreviousData, + [selectOption]: (items) => items.find((item) => item === id), }) states.push(state) diff --git a/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test-d.tsx b/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test-d.tsx index 514151b4c40..91a4235f639 100644 --- a/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test-d.tsx @@ -1,5 +1,9 @@ import { keepPreviousData, skipToken } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { useSuspenseInfiniteQuery } from '../useSuspenseInfiniteQuery' import type { InfiniteData } from '@tanstack/query-core' @@ -26,7 +30,7 @@ describe('useSuspenseInfiniteQuery', () => { : ({ pageParam }) => pageParam.toFixed(), initialPageParam: 1, getNextPageParam: () => undefined, - select: (data) => data.pages, + [selectOption]: (data) => data.pages, }) expectTypeOf(result.data).toEqualTypeOf | undefined>() @@ -54,7 +58,7 @@ describe('useSuspenseInfiniteQuery', () => { queryFn: () => Promise.resolve(5), initialPageParam: 1, getNextPageParam: () => 1, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) expectTypeOf(query.data).toEqualTypeOf>() @@ -65,13 +69,13 @@ describe('useSuspenseInfiniteQuery', () => { queryFn: () => Promise.resolve(5), initialPageParam: 1, getNextPageParam: () => 1, - placeholderData: (previousData) => { + [placeholderOption]: (previousData) => { expectTypeOf(previousData).toEqualTypeOf< InfiniteData | undefined >() return previousData ?? { pages: [0], pageParams: [1] } }, - select: (data) => data.pages.length, + [selectOption]: (data) => data.pages.length, }) expectTypeOf(selected.data).toEqualTypeOf() @@ -84,7 +88,7 @@ describe('useSuspenseInfiniteQuery', () => { queryFn: () => Promise.resolve(5), initialPageParam: 1, getNextPageParam: () => 1, - placeholderData: { pages: [5], pageParams: [1] }, + [placeholderOption]: { pages: [5], pageParams: [1] }, // @ts-expect-error TS2345 enabled: true, }), diff --git a/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test.tsx b/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test.tsx index 09f5d8aeaeb..3f417bc491f 100644 --- a/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test.tsx +++ b/packages/react-query/src/__tests__/useSuspenseInfiniteQuery.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { placeholderOption } from '@tanstack/query-test-utils/projection' import { act, fireEvent } from '@testing-library/react' import * as React from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -131,7 +132,7 @@ describe('useSuspenseInfiniteQuery', () => { queryFn, initialPageParam: 1, getNextPageParam: () => undefined, - placeholderData: { pages: [0], pageParams: [1] }, + [placeholderOption]: { pages: [0], pageParams: [1] }, }) states.push(state) @@ -157,7 +158,7 @@ describe('useSuspenseInfiniteQuery', () => { const queryClientWithPlaceholder = new QueryClient({ defaultOptions: { queries: { - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }, }, }) @@ -230,7 +231,7 @@ describe('useSuspenseInfiniteQuery', () => { queryFn: () => queryFn(count), initialPageParam: 1, getNextPageParam: () => undefined, - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }) return ( diff --git a/packages/react-query/src/__tests__/useSuspenseQueries.test-d.tsx b/packages/react-query/src/__tests__/useSuspenseQueries.test-d.tsx index a18946b0fc0..05fba69fa2b 100644 --- a/packages/react-query/src/__tests__/useSuspenseQueries.test-d.tsx +++ b/packages/react-query/src/__tests__/useSuspenseQueries.test-d.tsx @@ -1,4 +1,8 @@ import { createKey } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { skipToken, useSuspenseQueries } from '..' import { queryOptions } from '../queryOptions' @@ -39,7 +43,7 @@ describe('UseSuspenseQueries config object overload', () => { { queryKey: createKey(), queryFn: () => Promise.resolve(5), - placeholderData: (previousData, previousQuery) => { + [placeholderOption]: (previousData, previousQuery) => { expectTypeOf(previousData).toEqualTypeOf() expectTypeOf(previousQuery).toEqualTypeOf() return 0 @@ -54,8 +58,8 @@ describe('UseSuspenseQueries config object overload', () => { const selectedOptions = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(5), - placeholderData: 0, - select: (data) => data.toString(), + [placeholderOption]: 0, + [selectOption]: (data) => data.toString(), }) const [selectedQuery] = useSuspenseQueries({ queries: [selectedOptions], @@ -84,13 +88,13 @@ describe('UseSuspenseQueries config object overload', () => { const query1 = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data > 1, + [selectOption]: (data) => data > 1, }) const query2 = { queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data: number) => data > 1, + [selectOption]: (data: number) => data > 1, } const queryResults = useSuspenseQueries({ queries: [query1, query2] }) @@ -213,7 +217,7 @@ describe('UseSuspenseQueries config object overload', () => { ...queries1List, { ...Queries2.get(), - select(data: boolean) { + [selectOption](data: boolean) { return data }, }, @@ -277,7 +281,7 @@ describe('UseSuspenseQueries config object overload', () => { queryKey: createKey(), queryFn: () => 'Query Data', }), - select(data: string) { + [selectOption](data: string) { return data }, }, @@ -301,7 +305,7 @@ describe('UseSuspenseQueries config object overload', () => { { queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toBeUnknown() // @ts-expect-error `data` is `unknown`, not the expected `number` return data.toFixed() @@ -317,7 +321,7 @@ describe('UseSuspenseQueries config object overload', () => { { queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data: number) => data.toFixed(), + [selectOption]: (data: number) => data.toFixed(), }, ], }) @@ -339,7 +343,7 @@ describe('UseSuspenseQueries config object overload', () => { const options = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf() return data.toFixed() }, @@ -357,7 +361,7 @@ describe('UseSuspenseQueries config object overload', () => { queries: [ queryOptions({ ...baseOptions, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf() return data.toFixed() }, @@ -373,13 +377,13 @@ describe('UseSuspenseQueries config object overload', () => { const baseOptions = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data + 1, + [selectOption]: (data) => data + 1, }) const queryResults = useSuspenseQueries({ queries: [ queryOptions({ ...baseOptions, - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toEqualTypeOf() return data.toFixed() }, @@ -401,7 +405,7 @@ describe('UseSuspenseQueries config object overload', () => { { ...options, // @ts-expect-error Without an annotation the inline `select` parameter `data` implicitly has type `any` - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toBeAny() return data }, @@ -416,7 +420,9 @@ describe('UseSuspenseQueries config object overload', () => { queryFn: () => Promise.resolve(1), }) const queryResults = useSuspenseQueries({ - queries: [{ ...options, select: (data: number) => data.toFixed() }], + queries: [ + { ...options, [selectOption]: (data: number) => data.toFixed() }, + ], }) expectTypeOf(queryResults[0].data).toEqualTypeOf() }) @@ -425,14 +431,14 @@ describe('UseSuspenseQueries config object overload', () => { const options = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data + 1, + [selectOption]: (data) => data + 1, }) useSuspenseQueries({ queries: [ { ...options, // @ts-expect-error Without an annotation the inline `select` parameter `data` implicitly has type `any` - select: (data) => { + [selectOption]: (data) => { expectTypeOf(data).toBeAny() return data }, @@ -445,10 +451,12 @@ describe('UseSuspenseQueries config object overload', () => { const options = queryOptions({ queryKey: createKey(), queryFn: () => Promise.resolve(1), - select: (data) => data + 1, + [selectOption]: (data) => data + 1, }) const queryResults = useSuspenseQueries({ - queries: [{ ...options, select: (data: number) => data.toFixed() }], + queries: [ + { ...options, [selectOption]: (data: number) => data.toFixed() }, + ], }) expectTypeOf(queryResults[0].data).toEqualTypeOf() }) diff --git a/packages/react-query/src/__tests__/useSuspenseQueries.test.tsx b/packages/react-query/src/__tests__/useSuspenseQueries.test.tsx index f2841390c03..3fae8343b00 100644 --- a/packages/react-query/src/__tests__/useSuspenseQueries.test.tsx +++ b/packages/react-query/src/__tests__/useSuspenseQueries.test.tsx @@ -1,4 +1,9 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { act, fireEvent, render } from '@testing-library/react' import * as React from 'react' import { ErrorBoundary } from 'react-error-boundary' @@ -333,7 +338,9 @@ describe('useSuspenseQueries', () => { return (
@@ -384,14 +391,14 @@ describe('useSuspenseQueries', () => { function getName() { return { ...getUserData(), - select: (data: any) => data.name, + [selectOption]: (data: any) => data.name, } } function getAge() { return { ...getUserData(), - select: (data: any) => data.age, + [selectOption]: (data: any) => data.age, } } @@ -686,7 +693,7 @@ describe('useSuspenseQueries', () => { queryKey: key, queryFn: () => Promise.resolve('First'), staleTime: Infinity, - select: (data: string) => + [selectOption]: (data: string) => expanded ? data.toUpperCase() : data.toLowerCase(), }, ...(expanded @@ -838,7 +845,7 @@ describe('useSuspenseQueries', () => { const queryClientWithPlaceholder = new QueryClient({ defaultOptions: { queries: { - placeholderData: 'placeholder', + [placeholderOption]: 'placeholder', }, }, }) @@ -930,7 +937,7 @@ describe('useSuspenseQueries', () => { { queryKey: [...key, 1], queryFn: placeholderQueryFn, - placeholderData: 'placeholder', + [placeholderOption]: 'placeholder', }, { queryKey: [...key, 2], queryFn: pendingQueryFn }, ], @@ -975,7 +982,7 @@ describe('useSuspenseQueries', () => { { queryKey: [...key, deferredCount], queryFn: () => queryFn(deferredCount), - placeholderData: 'placeholder', + [placeholderOption]: 'placeholder', }, ], }) diff --git a/packages/react-query/src/__tests__/useSuspenseQuery.test-d.tsx b/packages/react-query/src/__tests__/useSuspenseQuery.test-d.tsx index d2935226a44..d68b299861e 100644 --- a/packages/react-query/src/__tests__/useSuspenseQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/useSuspenseQuery.test-d.tsx @@ -1,5 +1,9 @@ import { keepPreviousData, skipToken } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { useSuspenseQuery } from '../useSuspenseQuery' @@ -32,7 +36,7 @@ describe('useSuspenseQuery', () => { const result = useSuspenseQuery({ queryKey: createKey(), queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5), - select: (data) => data.toString(), + [selectOption]: (data) => data.toString(), }) expectTypeOf(result.data).toEqualTypeOf() @@ -48,7 +52,7 @@ describe('useSuspenseQuery', () => { const query = useSuspenseQuery({ queryKey: createKey(), queryFn: () => Promise.resolve(5), - placeholderData: (previousData, previousQuery) => { + [placeholderOption]: (previousData, previousQuery) => { expectTypeOf(previousData).toEqualTypeOf() expectTypeOf(previousQuery).not.toBeAny() return previousData ?? 0 @@ -62,15 +66,15 @@ describe('useSuspenseQuery', () => { useSuspenseQuery({ queryKey: createKey(), queryFn: () => Promise.resolve(5), - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }), ) const selected = useSuspenseQuery({ queryKey: createKey(), queryFn: () => Promise.resolve(5), - placeholderData: 0, - select: (data) => data.toString(), + [placeholderOption]: 0, + [selectOption]: (data) => data.toString(), }) expectTypeOf(selected.data).toEqualTypeOf() @@ -86,7 +90,7 @@ describe('useSuspenseQuery', () => { useSuspenseQuery({ queryKey: createKey(), queryFn: () => Promise.resolve(5), - placeholderData: 5, + [placeholderOption]: 5, // @ts-expect-error TS2345 enabled: true, }), diff --git a/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx b/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx index 7714d4fd4d7..29a3a622853 100644 --- a/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx +++ b/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx @@ -1,5 +1,10 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { refetchInterval } from '@tanstack/query-test-utils/polling' +import { + placeholderOption, + selectOption, +} from '@tanstack/query-test-utils/projection' import { act, fireEvent } from '@testing-library/react' import * as React from 'react' import { ErrorBoundary } from 'react-error-boundary' @@ -630,7 +635,7 @@ describe('useSuspenseQuery', () => { useSuspenseQuery({ queryKey: key, queryFn: () => sleep(10).then(() => ({ a: { b: 'c' } })), - select: () => { + [selectOption]: () => { throw new Error('foo') }, }) @@ -683,7 +688,10 @@ describe('useSuspenseQuery', () => { return (
rendered {result.data} -
@@ -912,7 +920,7 @@ describe('useSuspenseQuery', () => { const state = useSuspenseQuery({ queryKey: [...key, 'detail', 1], queryFn, - placeholderData: () => + [placeholderOption]: () => queryClient .getQueryData>([...key, 'list']) ?.find((item) => item.id === 1), @@ -949,7 +957,7 @@ describe('useSuspenseQuery', () => { const queryClientWithPlaceholder = new QueryClient({ defaultOptions: { queries: { - placeholderData: keepPreviousData, + [placeholderOption]: keepPreviousData, }, }, }) @@ -1017,7 +1025,7 @@ describe('useSuspenseQuery', () => { const state = useSuspenseQuery({ queryKey: key, queryFn: () => sleep(10).then(() => 'data'), - placeholderData: () => undefined, + [placeholderOption]: () => undefined, }) return
data: {state.data}
@@ -1040,7 +1048,7 @@ describe('useSuspenseQuery', () => { const state = useSuspenseQuery({ queryKey: key, queryFn, - placeholderData: showPlaceholder ? 'placeholder' : undefined, + [placeholderOption]: showPlaceholder ? 'placeholder' : undefined, }) return
data: {state.data}
@@ -1090,7 +1098,7 @@ describe('useSuspenseQuery', () => { const state = useSuspenseQuery({ queryKey: key, queryFn, - placeholderData: 'placeholder', + [placeholderOption]: 'placeholder', retry: false, }) diff --git a/scripts/port-query-projection-tests.mjs b/scripts/port-query-projection-tests.mjs new file mode 100644 index 00000000000..089d703beaf --- /dev/null +++ b/scripts/port-query-projection-tests.mjs @@ -0,0 +1,83 @@ +// Port explicitly marked query options in the copy used by the pluggable adapter. +// A tuple literal keeps inline callbacks contextually typed by the actual query hook. +import { readdirSync, readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' +import ts from 'typescript' + +export function portProjectionOptions(directory) { + for (const file of readdirSync(directory, { withFileTypes: true })) { + const path = join(directory, file.name) + if (file.isDirectory()) { + portProjectionOptions(path) + continue + } + if (!/\.tsx?$/.test(file.name)) continue + const text = readFileSync(path, 'utf8') + if (!text.includes('@tanstack/query-test-utils/projection')) continue + + const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true) + const edits = [] + const imports = new Set() + function visit(node) { + if ( + (ts.isMethodDeclaration(node) || ts.isPropertyAssignment(node)) && + ts.isObjectLiteralExpression(node.parent) && + ts.isComputedPropertyName(node.name) && + ts.isIdentifier(node.name.expression) + ) { + const marker = node.name.expression.text + if (marker === 'selectOption' || marker === 'placeholderOption') { + const isSelect = marker === 'selectOption' + const feature = isSelect ? 'select' : 'placeholderData' + const name = isSelect ? '__querySelect' : '__queryPlaceholder' + const wrapper = isSelect ? 'portSelect' : 'portPlaceholder' + if (ts.isMethodDeclaration(node)) { + imports.add(feature + ' as ' + name) + edits.push([ + node.name.end, + node.name.end, + ': [' + name + ', function', + ]) + edits.push([node.end, node.end, ']']) + } else { + const input = node.initializer + if ( + (ts.isArrowFunction(input) || ts.isFunctionExpression(input)) && + input.parameters.some((parameter) => !parameter.type) + ) { + imports.add(feature + ' as ' + name) + edits.push([ + input.getStart(source), + input.getStart(source), + '[' + name + ', ', + ]) + edits.push([input.end, input.end, ']']) + } else if (input.getText(source) !== 'undefined') { + imports.add(wrapper) + edits.push([ + input.getStart(source), + input.getStart(source), + wrapper + '(', + ]) + edits.push([input.end, input.end, ')']) + } + } + } + } + ts.forEachChild(node, visit) + } + visit(source) + if (!edits.length) continue + let result = text + for (const [start, end, replacement] of edits.sort((a, b) => b[0] - a[0])) { + result = result.slice(0, start) + replacement + result.slice(end) + } + writeFileSync( + path, + 'import { ' + + [...imports].join(', ') + + " } from '@tanstack/query-test-utils/projection'\n" + + result, + ) + } +} diff --git a/scripts/react-query-compat.config.ts b/scripts/react-query-compat.config.ts index dfaf8263193..e6442b05a6c 100644 --- a/scripts/react-query-compat.config.ts +++ b/scripts/react-query-compat.config.ts @@ -1,3 +1,4 @@ +import { readFileSync } from 'node:fs' import { basename, join, resolve } from 'node:path' import { defineConfig } from 'vitest/config' import core from '../packages/query-core/vite.config.ts' @@ -8,20 +9,17 @@ const suite = basename(resolve(process.cwd(), '../..')) const isReact = suite === 'react-query' const base = isReact ? react : core +const { paths } = JSON.parse(readFileSync('tsconfig.json', 'utf8')) + .compilerOptions as { paths: Record } export default defineConfig({ ...base, resolve: { ...base.resolve, - alias: { - '@tanstack/query-core': join(adapter, 'src/index.ts'), - ...(basename(adapter) === 'react-query-no-core-pluggable' && { - '@tanstack/query-test-utils/polling': join( - adapter, - 'tests/compat-polling.ts', - ), - }), - }, + // Use the same entry points for test execution and type checking. + alias: Object.fromEntries( + Object.entries(paths).map(([name, [file]]) => [name, file]), + ), }, test: { ...base.test, diff --git a/scripts/test-react-query-compat.mjs b/scripts/test-react-query-compat.mjs index c180baa2ea6..80ac313690a 100644 --- a/scripts/test-react-query-compat.mjs +++ b/scripts/test-react-query-compat.mjs @@ -11,6 +11,7 @@ import { } from 'node:fs' import { createRequire } from 'node:module' import { basename, join, relative, resolve, sep } from 'node:path' +import { portProjectionOptions } from './port-query-projection-tests.mjs' const adapter = process.cwd() const repository = resolve(import.meta.dirname, '..') @@ -38,6 +39,9 @@ for (const suite of ['query-core', 'react-query']) { filter: (path) => suite !== 'query-core' || basename(path) !== 'frameworkAdapters', }) + if (pluggable) { + portProjectionOptions(join(source, '__tests__')) + } for (const file of readdirSync(implementation, { withFileTypes: true })) { if (!file.isFile() || !/\.tsx?$/.test(file.name)) continue @@ -45,6 +49,11 @@ for (const suite of ['query-core', 'react-query']) { writeFileSync(join(source, file.name), `export * from '${target}'\n`) } if (suite === 'query-core') { + // The React runtimes expose the page fetcher directly. + writeFileSync( + join(source, '__tests__/infiniteFetch.ts'), + `export { prepareInfiniteFetch } from '../infiniteQueryBehavior'\n`, + ) // Upstream tests use ".." for the public package and "../foo" for internals. writeFileSync( join(source, 'index.ts'), @@ -63,11 +72,15 @@ for (const suite of ['query-core', 'react-query']) { noEmit: true, paths: { '@tanstack/query-core': [entry], - ...(pluggable && { - '@tanstack/query-test-utils/polling': [ - join(adapter, 'tests/compat-polling.ts'), - ], - }), + ...(pluggable && + Object.fromEntries( + ['polling', 'cacheOperations', 'projection', 'scope'].map( + (name) => [ + `@tanstack/query-test-utils/${name}`, + [join(adapter, `tests/compat-${name}.ts`)], + ], + ), + )), }, }, include: suite === 'react-query' ? ['src', setup] : ['src'], From 1c9c8d83c7d5a998b0c1d60e139ed65fa32541d0 Mon Sep 17 00:00:00 2001 From: Jonghyeon Ko Date: Fri, 27 Nov 2026 22:20:41 +0900 Subject: [PATCH 09/11] test(react-query): measure the retained Query runtime and publish bundle treemaps --- .github/workflows/react-query-bundle-size.yml | 14 +- integrations/react/bundle-size/README.md | 17 +- integrations/react/bundle-size/analyze.mjs | 19 ++ integrations/react/bundle-size/measure.mjs | 179 ++++++++++++++---- integrations/react/bundle-size/package.json | 1 + pnpm-lock.yaml | 3 + 6 files changed, 197 insertions(+), 36 deletions(-) create mode 100644 integrations/react/bundle-size/analyze.mjs diff --git a/.github/workflows/react-query-bundle-size.yml b/.github/workflows/react-query-bundle-size.yml index 176304febec..7da63fd5f73 100644 --- a/.github/workflows/react-query-bundle-size.yml +++ b/.github/workflows/react-query-bundle-size.yml @@ -28,6 +28,7 @@ jobs: contents: read outputs: report: ${{ steps.measure.outputs.report }} + analyzer_url: ${{ steps.analyzer.outputs.artifact-url }} steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 with: @@ -62,6 +63,14 @@ jobs: - 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 @@ -75,6 +84,7 @@ jobs: 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='' @@ -86,6 +96,6 @@ jobs: endpoint="repos/$REPO/issues/comments/$id" method=PATCH fi - jq -n --arg marker "$marker" --argjson report "$REPORT" \ - '{body: ($marker + "\n" + $report)}' | + 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/README.md b/integrations/react/bundle-size/README.md index 4f22b8b5d72..ecfa2c07b04 100644 --- a/integrations/react/bundle-size/README.md +++ b/integrations/react/bundle-size/README.md @@ -1,9 +1,22 @@ # 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. 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 all four regular and suspense query hooks. The options app keeps the previous page while fetching, selects the displayed titles, saves bookmarks in a serial scope, and invalidates the bookmark list. All builds include React and React DOM and use the default client. The original and standalone adapters accept a numeric interval. The pluggable adapter imports its interval scheduler through the `refetchInterval` option helper. The benchmark checks retained modules in each app and bundles individual public exports to check that selection, placeholder data and serial queues can be removed independently. The React hydration boundary only restores queries. The universal `hydrate` also restores serial queues from saved mutations. +This workspace builds four browser apps against each adapter’s public package entry point. The read-only app fetches a book list. 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 all four regular and suspense query hooks. 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 and standalone adapters accept 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 two alternatives, the app code, the bundler and both React packages come from the PR head. The report records both commit IDs. +## What the PR comment measures + +1. **Query runtime used by the app.** Vite builds the same HTML and React entry points with React, React DOM and their subpaths external. Rolldown groups the adapter’s retained modules into one ESM chunk, including `@tanstack/query-core` for the original adapter. The app and its workload-specific helpers stay in a separate entry chunk. The benchmark directly measures the minified Query chunk, including its ESM import and export bindings. Its gzip and Brotli sizes describe compressing this chunk on its own. Percentages use the original adapter’s isolated chunk for that workload and encoding. +2. **Whole production app.** Vite builds the deployable application with its ordinary chunk layout, including React, React DOM, the app and the adapter. Each percentage uses the original adapter’s full app for that workload and encoding. Compressing these complete chunks accounts for compression shared between the app and its dependencies. + +Both tables show the emitted JS byte length, gzip at level 9 and Brotli at quality 11. The benchmark compresses each emitted JS chunk independently and sums the lengths. HTML, source maps and analysis reports are excluded. + +For each app, the benchmark verifies that the isolated Query chunk contains the same retained Query module IDs and exports as the whole production app and imports only React peer entry points. The production app checks also cover feature-specific modules. Individual public export probes check that selection, placeholder data and serial queues can be removed independently. 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. + +## Run locally + For a comparison within the current checkout, run from the repository root after installing workspace dependencies: ```sh @@ -20,7 +33,7 @@ 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 ``` -The report at `integrations/react/bundle-size/dist/report.md` shows total emitted JavaScript bytes and the sum of individually compressed chunks for gzip and Brotli. Each percentage uses the original adapter’s application size for that workload as its denominator. Serve a directory under `dist//` to try the built app. +Read both tables in `integrations/react/bundle-size/dist/report.md`. Serve a directory under `dist//` to try the built app. Run the twelve production app scenarios in Chromium after measuring: diff --git a/integrations/react/bundle-size/analyze.mjs b/integrations/react/bundle-size/analyze.mjs new file mode 100644 index 00000000000..9b3984cbc85 --- /dev/null +++ b/integrations/react/bundle-size/analyze.mjs @@ -0,0 +1,19 @@ +import path from 'node:path' +import { visualizer } from 'rollup-plugin-visualizer' + +export function adapterTreemap(screen, packageName) { + const name = packageName.split('/')[1] + 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/measure.mjs b/integrations/react/bundle-size/measure.mjs index 6af9232eb94..d786f35cc21 100644 --- a/integrations/react/bundle-size/measure.mjs +++ b/integrations/react/bundle-size/measure.mjs @@ -1,10 +1,13 @@ +import assert from 'node:assert/strict' import { execFileSync } from 'node:child_process' -import { readFile, realpath, writeFile } from 'node:fs/promises' +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.mjs' 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 @@ -14,20 +17,15 @@ const baseline = '@tanstack/react-query' const pluggable = '@tanstack/react-query-no-core-pluggable' const packages = [baseline, '@tanstack/react-query-no-core', pluggable] const workloads = [ - { screen: 'query', title: 'Read-only list · useQuery' }, - { - screen: 'paginated', - title: - 'Paginated list with bookmarks · useQuery, useMutation, useInfiniteQuery', - }, + { screen: 'query', title: 'Read-only list' }, + { screen: 'paginated', title: 'Paginated bookmarks' }, { screen: 'options', - title: - 'Selected and placeholder data, serial bookmarks and cache invalidation', + title: 'Selection, serial bookmarks and invalidation', }, { screen: 'polling', - title: 'Polling with the four regular and suspense query hooks', + title: 'Polling', }, ] @@ -36,7 +34,7 @@ const excludedFromStandaloneApps = [ /\/node_modules\/(?:@angular|@lit|@vue|lit|lit-element|lit-html|preact|solid-js|svelte|vue)\//, ] -async function measure(packageName, screen) { +async function buildApp(packageName, screen, belongsToAdapter) { const outDir = path.join(root, 'dist', screen, packageName.split('/')[1]) const result = await build({ root, @@ -45,6 +43,7 @@ async function measure(packageName, screen) { mode: 'production', logLevel: 'warn', plugins: [ + ...(belongsToAdapter ? [adapterTreemap(screen, packageName)] : []), { name: 'resolve-benchmark-adapter', enforce: 'pre', @@ -79,21 +78,46 @@ async function measure(packageName, screen) { }, build: { outDir, - emptyOutDir: true, + write: !belongsToAdapter, + sourcemap: belongsToAdapter ? 'hidden' : false, reportCompressedSize: false, // All modules in these apps execute on the client. - rolldownOptions: { checks: { moduleLevelDirective: false } }, + rolldownOptions: { + checks: { moduleLevelDirective: false }, + ...(belongsToAdapter && { + external: reactPeer, + output: { + codeSplitting: { + groups: [ + { + name: 'query-runtime', + test: belongsToAdapter, + includeDependenciesRecursively: false, + }, + ], + }, + }, + }), + }, }, }) const chunks = result.output.filter((output) => output.type === 'chunk') if (!chunks.some((chunk) => chunk.isEntry)) { throw new Error(`Missing browser entry chunk for ${packageName}`) } - const modules = chunks.flatMap((chunk) => - Object.entries(chunk.modules) - .filter(([, module]) => module.renderedLength > 0) - .map(([id]) => id), + return chunks +} + +function renderedModules(chunks) { + return chunks.flatMap((chunk) => + Object.entries(chunk.modules).filter( + ([, module]) => module.renderedLength > 0, + ), ) +} + +function checkApp(chunks, packageName, screen) { + const modules = renderedModules(chunks).map(([id]) => id) if ( packageName === baseline && basePackage && @@ -151,10 +175,20 @@ async function measure(packageName, screen) { } } } +} +const reactPeer = /^react(?:-dom)?(?:\/|$)/ + +function retainedExports(modules) { + return new Map( + modules.map(([id, module]) => [id, new Set(module.renderedExports)]), + ) +} + +function sizesOf(chunks) { const sizes = { raw: 0, gzip: 0, brotli: 0 } for (const chunk of chunks) { - const js = await readFile(path.join(outDir, chunk.fileName)) + const js = Buffer.from(chunk.code) sizes.raw += js.length sizes.gzip += gzipSync(js, { level: 9 }).length sizes.brotli += brotliCompressSync(js, { @@ -164,6 +198,60 @@ async function measure(packageName, screen) { return sizes } +async function measure(packageName, 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 = ( + packageName === baseline + ? ['react-query', 'query-core'] + : [packageName.split('/')[1]] + ).map( + (name) => normalizePath(path.join(source, 'packages', name, 'build')) + '/', + ) + const belongsToAdapter = (id) => owners.some((dir) => id.startsWith(dir)) + const attributed = await buildApp(packageName, screen, belongsToAdapter) + const library = attributed.filter((chunk) => chunk.name === 'query-runtime') + assert.equal( + library.length, + 1, + `Expected one Query chunk in ${packageName} ${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 !== library[0])).some( + ([id]) => belongsToAdapter(id), + ) || + [...library[0].imports, ...library[0].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]) => id.slice(owners.find((dir) => id.startsWith(dir)).length)) + return { library: sizesOf(library), app: sizesOf(app), largestModules } +} + // A combined app cannot tell whether each projection pulls in its sibling, // or whether rendering a boundary pulls in paused-mutation restoration. async function checkStandaloneExports() { @@ -282,33 +370,60 @@ function revision(directory) { const head = revision(root) const base = baseCheckout ? revision(baseCheckout) : head const lines = [ - '## React Query app bundle size', + '## React Query bundle size', '', `Baseline adapter at \`${base}\` (${baseCheckout ? 'base checkout' : 'current checkout'}). Alternatives and fixture at \`${head}\`.`, '', - 'Each row includes the same React, React DOM and production Vite app. Changes are relative to the baseline for that workload. A negative change is a saving.', + 'Changes are relative to the original adapter for the same workload and measurement. A negative change is a saving.', ] +const results = [] for (const { screen, title } of workloads) { + const rows = [] + for (const name of packages) { + rows.push({ name, ...(await measure(name, screen)) }) + } + results.push({ screen, title, rows }) +} +function addTable(key, heading, description) { lines.push( '', - `### ${title}`, + `### ${heading}`, '', - '| Package | Minified JS | Gzip | Brotli |', - '| --- | ---: | ---: | ---: |', + description, + '', + '| Workload | Package | Minified JS | Gzip | Brotli |', + '| --- | --- | ---: | ---: | ---: |', ) - let baselineSizes - for (const name of packages) { - const sizes = await measure(name, screen) - baselineSizes ??= sizes - const cells = Object.entries(sizes).map(([key, value]) => - formatSize(value, baselineSizes[key], name === baseline), - ) - lines.push(`| \`${name}\` | ${cells.join(' | ')} |`) + for (const { title, rows } of results) { + const baselineSizes = rows[0][key] + for (const row of rows) { + const cells = Object.entries(row[key]).map(([metric, value]) => + formatSize(value, baselineSizes[metric], row.name === baseline), + ) + lines.push(`| ${title} | \`${row.name}\` | ${cells.join(' | ')} |`) + } } } +addTable( + 'library', + 'Query runtime used by the app', + 'The app entry drives tree-shaking. This build externalizes React and React DOM and groups retained Query modules into one ESM chunk. The baseline includes query-core. Each cell measures the isolated chunk directly.', +) +const readOnly = results + .find(({ screen }) => screen === 'query') + .rows.find(({ name }) => name === pluggable) +lines.push( + '', + `Largest modules in the read-only pluggable chunk, by rendered size before minification: ${readOnly.largestModules.map((name) => `\`${name}\``).join(', ')}.`, +) +addTable( + 'app', + 'Whole production app', + 'Each build includes the app, React, React DOM and Query. This measures the JavaScript delivered to the browser.', +) lines.push( '', - 'Gzip level 9 and Brotli quality 11 are applied to each JavaScript chunk before summing. All workloads use the default client. The polling workload imports the interval scheduler. The options workload imports selection, placeholder data, serial scopes and invalidation.', + 'All sizes are bytes. Each JavaScript chunk is compressed separately with gzip level 9 and Brotli quality 11, then summed.', '', ) const report = lines.join('\n') diff --git a/integrations/react/bundle-size/package.json b/integrations/react/bundle-size/package.json index 59a0a873b69..33d7569f8f0 100644 --- a/integrations/react/bundle-size/package.json +++ b/integrations/react/bundle-size/package.json @@ -19,6 +19,7 @@ "@vitest/browser-playwright": "5.0.5", "@vitest/ui": "5.0.5", "playwright": "1.65.1", + "rollup-plugin-visualizer": "7.1.1", "vite": "^8.3.8", "vitest": "^5.0.5" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2d22aca9c32..155552b6f5a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7285,6 +7285,9 @@ importers: playwright: specifier: 1.65.1 version: 1.65.1 + rollup-plugin-visualizer: + specifier: 7.1.1 + version: 7.1.1(rolldown@1.3.1)(rollup@4.65.1) vite: specifier: ^8.3.8 version: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1) From e2fb1311b3ea11b843c51349c9379563d5078fff Mon Sep 17 00:00:00 2001 From: Jonghyeon Ko Date: Fri, 27 Nov 2026 22:33:59 +0900 Subject: [PATCH 10/11] feat(react-query): acquire the pluggable mutation cache on demand --- .changeset/react-query-standalone-adapters.md | 2 + integrations/react/bundle-size/README.md | 6 +- integrations/react/bundle-size/measure.mjs | 73 ++++++++++++++----- .../query-core/src/__tests__/cacheGc.test.tsx | 5 +- .../src/__tests__/mutation.test.tsx | 31 ++++---- .../src/__tests__/mutationCache.test-d.tsx | 3 +- .../src/__tests__/mutationCache.test.tsx | 19 ++--- .../src/__tests__/mutationObserver.test.tsx | 29 ++++---- .../src/__tests__/queryClient.test-d.tsx | 9 ++- .../src/__tests__/queryClient.test.tsx | 21 +++--- .../query-core/src/__tests__/utils.test.tsx | 3 +- .../query-test-utils/src/cacheOperations.ts | 11 +++ .../react-query-no-core-pluggable/README.md | 4 + .../src/__tests__/getMutationCache.test.ts | 64 ++++++++++++++++ .../src/index.ts | 2 +- .../src/runtime/hydration.ts | 13 ++-- .../src/runtime/mutation.ts | 5 +- .../src/runtime/mutationCache.ts | 34 ++++++--- .../src/runtime/mutationObserver.ts | 8 +- .../src/runtime/queryClient.ts | 49 ++++++------- .../src/runtime/utils.ts | 2 +- .../src/useMutationState.ts | 3 +- .../tests/compat-cacheOperations.ts | 2 + .../src/__tests__/useMutation.test.tsx | 29 ++++---- .../src/__tests__/useMutationState.test.tsx | 11 +-- scripts/test-react-query-compat.mjs | 11 +++ 26 files changed, 305 insertions(+), 144 deletions(-) create mode 100644 packages/react-query-no-core-pluggable/src/__tests__/getMutationCache.test.ts diff --git a/.changeset/react-query-standalone-adapters.md b/.changeset/react-query-standalone-adapters.md index 42d62738506..b9d8ba194f4 100644 --- a/.changeset/react-query-standalone-adapters.md +++ b/.changeset/react-query-standalone-adapters.md @@ -6,3 +6,5 @@ --- Add experimental ESM React Query adapters with an integrated query runtime. The pluggable adapter lets apps import polling, selection, placeholder data, and scoped mutation queues at the point of use. It also exports imperative infinite queries and bulk cache operations as standalone functions. Both adapters and `@tanstack/query-core` share TypeScript definitions through `@tanstack/query-types`. + +In the pluggable adapter, mutation hooks acquire the cache on demand so query-only apps can omit its implementation. For direct cache access, use the named export `getMutationCache(client)`. Clients created with a custom mutation cache keep using that instance. diff --git a/integrations/react/bundle-size/README.md b/integrations/react/bundle-size/README.md index ecfa2c07b04..8814861df96 100644 --- a/integrations/react/bundle-size/README.md +++ b/integrations/react/bundle-size/README.md @@ -6,12 +6,14 @@ CI builds the original adapter and its dependencies from the PR's base commit. T ## What the PR comment measures +The opening table compares the gzipped Query runtime for each workload. It shows the v6 baseline in bytes and the signed change in bytes and percent for each alternative. Expand either detail table to see absolute sizes and changes for all three packages. + 1. **Query runtime used by the app.** Vite builds the same HTML and React entry points with React, React DOM and their subpaths external. Rolldown groups the adapter’s retained modules into one ESM chunk, including `@tanstack/query-core` for the original adapter. The app and its workload-specific helpers stay in a separate entry chunk. The benchmark directly measures the minified Query chunk, including its ESM import and export bindings. Its gzip and Brotli sizes describe compressing this chunk on its own. Percentages use the original adapter’s isolated chunk for that workload and encoding. 2. **Whole production app.** Vite builds the deployable application with its ordinary chunk layout, including React, React DOM, the app and the adapter. Each percentage uses the original adapter’s full app for that workload and encoding. Compressing these complete chunks accounts for compression shared between the app and its dependencies. Both tables show the emitted JS byte length, gzip at level 9 and Brotli at quality 11. The benchmark compresses each emitted JS chunk independently and sums the lengths. HTML, source maps and analysis reports are excluded. -For each app, the benchmark verifies that the isolated Query chunk contains the same retained Query module IDs and exports as the whole production app and imports only React peer entry points. The production app checks also cover feature-specific modules. Individual public export probes check that selection, placeholder data and serial queues can be removed independently. The React hydration boundary only restores queries. The universal `hydrate` also restores serial queues from saved mutations. +For each app, the benchmark verifies that the isolated Query chunk contains the same retained Query module IDs and exports as the whole production app and imports only React peer entry points. 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. Additional checks cover polling, infinite queries, selection, placeholder data, serial queues and bulk cache operations. Individual public export probes check that selection, placeholder data and serial queues can be removed independently. 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. @@ -33,7 +35,7 @@ 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 both tables in `integrations/react/bundle-size/dist/report.md`. Serve a directory under `dist//` to try the built app. +Read the summary and detailed tables in `integrations/react/bundle-size/dist/report.md`. Serve a directory under `dist//` to try the built app. Run the twelve production app scenarios in Chromium after measuring: diff --git a/integrations/react/bundle-size/measure.mjs b/integrations/react/bundle-size/measure.mjs index d786f35cc21..655b83515d4 100644 --- a/integrations/react/bundle-size/measure.mjs +++ b/integrations/react/bundle-size/measure.mjs @@ -156,7 +156,15 @@ function checkApp(chunks, packageName, screen) { } } if (packageName === pluggable) { + const usesMutations = screen === 'paginated' || screen === 'options' const features = { + queryClient: true, + queryCache: true, + query: true, + queryObserver: true, + mutationCache: usesMutations, + mutation: usesMutations, + mutationObserver: usesMutations, refetchInterval: screen === 'polling', infiniteQueryBehavior: screen === 'paginated' || screen === 'polling', select: screen === 'options', @@ -256,12 +264,20 @@ async function measure(packageName, screen) { // or whether rendering a boundary pulls in paused-mutation restoration. async function checkStandaloneExports() { const expected = { + QueryClient: [], + getMutationCache: ['mutationCache'], select: ['select', 'projectResult'], placeholderData: ['placeholderData', 'projectResult'], serialScope: ['serialScope'], invalidateQueries: ['cacheOperations'], HydrationBoundary: ['infiniteQueryBehavior'], - hydrate: ['infiniteQueryBehavior', 'mutation', 'serialScope'], + dehydrate: [], + hydrate: [ + 'infiniteQueryBehavior', + 'mutation', + 'mutationCache', + 'serialScope', + ], } const features = new Set(Object.values(expected).flat()) const entry = path.join(root, 'public-export-probe.js') @@ -324,13 +340,17 @@ async function checkStandaloneExports() { await checkStandaloneExports() const integer = new Intl.NumberFormat('en-US') -function formatSize(bytes, baselineBytes, isBaseline) { - const size = `${integer.format(bytes)} B` - if (isBaseline) return size +function formatChange(bytes, baselineBytes) { const difference = bytes - baselineBytes const sign = difference > 0 ? '+' : '' const percent = ((100 * difference) / baselineBytes).toFixed(2) - return `${size} (${sign}${integer.format(difference)} B, ${sign}${percent}%)` + return `${sign}${integer.format(difference)} B (${sign}${percent}%)` +} + +function formatSize(bytes, baselineBytes, isBaseline) { + const size = `${integer.format(bytes)} B` + if (isBaseline) return size + return `${size}
${formatChange(bytes, baselineBytes)}` } // Inspect the published ESM entry points as a consumer would. @@ -372,9 +392,12 @@ const base = baseCheckout ? revision(baseCheckout) : head const lines = [ '## React Query bundle size', '', - `Baseline adapter at \`${base}\` (${baseCheckout ? 'base checkout' : 'current checkout'}). Alternatives and fixture at \`${head}\`.`, + '### 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.', '', - 'Changes are relative to the original adapter for the same workload and measurement. A negative change is a saving.', + '| Workload | v6 | no-core change | no-core-pluggable change |', + '| --- | ---: | ---: | ---: |', ] const results = [] for (const { screen, title } of workloads) { @@ -383,11 +406,24 @@ for (const { screen, title } of workloads) { rows.push({ name, ...(await measure(name, screen)) }) } results.push({ screen, title, rows }) + const [v6Gzip, standaloneGzip, pluggableGzip] = rows.map( + (row) => row.library.gzip, + ) + lines.push( + `| ${title} | ${integer.format(v6Gzip)} B | ${formatChange(standaloneGzip, v6Gzip)} | ${formatChange(pluggableGzip, v6Gzip)} |`, + ) } +lines.push( + '', + 'The pluggable read-only list retains the query client, cache, query and observer. Its production build drops the mutation cache and observer, polling scheduler, infinite-query behavior, selection, placeholder data, serial scopes and bulk cache operations. Both bookmark apps retain the mutation cache and observer.', + '', + `Baseline adapter at \`${base}\` (${baseCheckout ? 'base checkout' : 'current checkout'}). Alternatives and fixture at \`${head}\`.`, +) function addTable(key, heading, description) { lines.push( '', - `### ${heading}`, + '
', + `${heading}`, '', description, '', @@ -403,22 +439,25 @@ function addTable(key, heading, description) { lines.push(`| ${title} | \`${row.name}\` | ${cells.join(' | ')} |`) } } + if (key === 'library') { + const readOnly = results + .find(({ screen }) => screen === 'query') + .rows.find(({ name }) => name === pluggable) + lines.push( + '', + `Largest modules in the read-only pluggable chunk, by rendered size before minification: ${readOnly.largestModules.map((name) => `\`${name}\``).join(', ')}.`, + ) + } + lines.push('', '
') } addTable( 'library', - 'Query runtime used by the app', + 'Query runtime sizes · minified JS, gzip and Brotli', 'The app entry drives tree-shaking. This build externalizes React and React DOM and groups retained Query modules into one ESM chunk. The baseline includes query-core. Each cell measures the isolated chunk directly.', ) -const readOnly = results - .find(({ screen }) => screen === 'query') - .rows.find(({ name }) => name === pluggable) -lines.push( - '', - `Largest modules in the read-only pluggable chunk, by rendered size before minification: ${readOnly.largestModules.map((name) => `\`${name}\``).join(', ')}.`, -) addTable( 'app', - 'Whole production app', + 'Whole production app sizes · minified JS, gzip and Brotli', 'Each build includes the app, React, React DOM and Query. This measures the JavaScript delivered to the browser.', ) lines.push( diff --git a/packages/query-core/src/__tests__/cacheGc.test.tsx b/packages/query-core/src/__tests__/cacheGc.test.tsx index 67bc7a458e8..a31f7a5e6d9 100644 --- a/packages/query-core/src/__tests__/cacheGc.test.tsx +++ b/packages/query-core/src/__tests__/cacheGc.test.tsx @@ -1,3 +1,4 @@ +import { getMutationCache } from '@tanstack/query-test-utils/cacheOperations' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MutationObserver, QueryClient, QueryObserver } from '..' import { Mutation } from '../mutation' @@ -21,7 +22,7 @@ describe('garbage collection after cache removal', () => { }) it('clears an existing mutation timer on clear', () => { - const cache = client.getMutationCache() + const cache = getMutationCache(client) Mutation.build(client, {}) expect(vi.getTimerCount()).toBe(1) @@ -32,7 +33,7 @@ describe('garbage collection after cache removal', () => { }) it('clears an existing mutation timer on remove', () => { - const cache = client.getMutationCache() + const cache = getMutationCache(client) const mutation = Mutation.build(client, {}) expect(vi.getTimerCount()).toBe(1) diff --git a/packages/query-core/src/__tests__/mutation.test.tsx b/packages/query-core/src/__tests__/mutation.test.tsx index aab835a7da0..54e249ccb75 100644 --- a/packages/query-core/src/__tests__/mutation.test.tsx +++ b/packages/query-core/src/__tests__/mutation.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { getMutationCache } from '@tanstack/query-test-utils/cacheOperations' import { serialScope } from '@tanstack/query-test-utils/scope' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MutationCache, QueryClient, focusManager, onlineManager } from '..' @@ -347,7 +348,7 @@ describe('mutation', () => { }) it('should not add an existing observer with addObserver', () => { - const mutationCache = queryClient.getMutationCache() + const mutationCache = getMutationCache(queryClient) const observer = new MutationObserver(queryClient, {}) const currentMutation = Mutation.build(queryClient, {}) @@ -498,7 +499,7 @@ describe('mutation', () => { await vi.advanceTimersByTimeAsync(10) expect(count).toBe(1) expect( - queryClient.getMutationCache().find({ mutationKey: key })?.state + getMutationCache(queryClient).find({ mutationKey: key })?.state .isPaused, ).toBe(true) @@ -536,7 +537,7 @@ describe('mutation', () => { 'vars1', ) expect( - queryClient.getMutationCache().find({ mutationKey: key1 })?.state, + getMutationCache(queryClient).find({ mutationKey: key1 })?.state, ).toMatchObject({ status: 'pending', isPaused: false, @@ -557,7 +558,7 @@ describe('mutation', () => { 'vars2', ) expect( - queryClient.getMutationCache().find({ mutationKey: key2 })?.state, + getMutationCache(queryClient).find({ mutationKey: key2 })?.state, ).toMatchObject({ status: 'pending', isPaused: true, @@ -620,7 +621,7 @@ describe('mutation', () => { 'finish-B', ]) expect( - queryClient.getMutationCache().find({ mutationKey: key2 })?.state, + getMutationCache(queryClient).find({ mutationKey: key2 })?.state, ).toMatchObject({ status: 'success', isPaused: false, @@ -675,7 +676,7 @@ describe('mutation', () => { await vi.advanceTimersByTimeAsync(10) expect(results).toStrictEqual(['start-A', 'finish-A']) expect( - queryClient.getMutationCache().find({ mutationKey: key2 })?.state, + getMutationCache(queryClient).find({ mutationKey: key2 })?.state, ).toMatchObject({ status: 'pending', isPaused: true, @@ -734,7 +735,7 @@ describe('mutation', () => { await vi.advanceTimersByTimeAsync(0) expect(results).toStrictEqual(['start-A']) expect( - queryClient.getMutationCache().find({ mutationKey: key2 })?.state + getMutationCache(queryClient).find({ mutationKey: key2 })?.state .isPaused, ).toBe(true) @@ -754,7 +755,7 @@ describe('mutation', () => { it('should keep a queued mutation paused when its onMutate resolves before its turn', async () => { const isPaused: Array = [] - const unsubscribe = queryClient.getMutationCache().subscribe((event) => { + const unsubscribe = getMutationCache(queryClient).subscribe((event) => { if ( event.type === 'updated' && event.mutation.state.variables === 'vars2' @@ -806,7 +807,7 @@ describe('mutation', () => { }, 'vars', ) - const mutation = queryClient.getMutationCache().find({ mutationKey: key })! + const mutation = getMutationCache(queryClient).find({ mutationKey: key })! expect(mutation.state).toMatchObject({ status: 'pending', isPaused: true, @@ -1497,9 +1498,9 @@ describe('mutation', () => { observer1.mutate() await vi.advanceTimersByTimeAsync(10) - expect(queryClient.getMutationCache().getAll()).toHaveLength(1) + expect(getMutationCache(queryClient).getAll()).toHaveLength(1) - const mutation = queryClient.getMutationCache().getAll()[0]! + const mutation = getMutationCache(queryClient).getAll()[0]! const observer2 = new MutationObserver(queryClient, { gcTime: 10, mutationFn: () => sleep(10).then(() => 'data'), @@ -1508,7 +1509,7 @@ describe('mutation', () => { unsubscribe1() await vi.advanceTimersByTimeAsync(10) - expect(queryClient.getMutationCache().getAll()).toHaveLength(1) + expect(getMutationCache(queryClient).getAll()).toHaveLength(1) }) it('should release the retryer once a mutation settles', async () => { @@ -1519,7 +1520,7 @@ describe('mutation', () => { observer.mutate('data') await vi.advanceTimersByTimeAsync(10) - const mutation = queryClient.getMutationCache().getAll()[0]! + const mutation = getMutationCache(queryClient).getAll()[0]! expect(mutation.state.status).toBe('success') // continue() is the only reader of the retryer outside execute(): while a @@ -1536,7 +1537,7 @@ describe('mutation', () => { observer.mutate(undefined).catch(() => undefined) await vi.advanceTimersByTimeAsync(10) - const mutation = queryClient.getMutationCache().getAll()[0]! + const mutation = getMutationCache(queryClient).getAll()[0]! expect(mutation.state.status).toBe('error') // a retained retryer would hand back its rejected promise here @@ -1552,7 +1553,7 @@ describe('mutation', () => { observer.mutate() await vi.advanceTimersByTimeAsync(10) - const mutation = queryClient.getMutationCache().getAll()[0]! + const mutation = getMutationCache(queryClient).getAll()[0]! expect(mutation.state.status).toBe('success') expect(mutationFn).toHaveBeenCalledTimes(1) diff --git a/packages/query-core/src/__tests__/mutationCache.test-d.tsx b/packages/query-core/src/__tests__/mutationCache.test-d.tsx index 9be20684105..df77f70c071 100644 --- a/packages/query-core/src/__tests__/mutationCache.test-d.tsx +++ b/packages/query-core/src/__tests__/mutationCache.test-d.tsx @@ -1,3 +1,4 @@ +import { getMutationCache } from '@tanstack/query-test-utils/cacheOperations' import { afterEach, beforeEach, describe, expectTypeOf, it } from 'vitest' import { MutationCache, QueryClient } from '..' import { Mutation } from '../mutation' @@ -22,7 +23,7 @@ describe('mutationCache', () => { beforeEach(() => { queryClient = new QueryClient() queryClient.mount() - mutationCache = queryClient.getMutationCache() + mutationCache = getMutationCache(queryClient) }) afterEach(() => { diff --git a/packages/query-core/src/__tests__/mutationCache.test.tsx b/packages/query-core/src/__tests__/mutationCache.test.tsx index 3e422fa3e61..52761dae305 100644 --- a/packages/query-core/src/__tests__/mutationCache.test.tsx +++ b/packages/query-core/src/__tests__/mutationCache.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { getMutationCache } from '@tanstack/query-test-utils/cacheOperations' import { serialScope } from '@tanstack/query-test-utils/scope' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MutationCache, MutationObserver, QueryClient } from '..' @@ -497,17 +498,17 @@ describe('mutationCache', () => { mutationFn: (input: number) => sleep(10).then(() => input), }) const unsubscribe = observer.subscribe(() => undefined) - expect(queryClient.getMutationCache().getAll()).toHaveLength(0) + expect(getMutationCache(queryClient).getAll()).toHaveLength(0) observer.mutate(1) - expect(queryClient.getMutationCache().getAll()).toHaveLength(1) + expect(getMutationCache(queryClient).getAll()).toHaveLength(1) await vi.advanceTimersByTimeAsync(10) - expect(queryClient.getMutationCache().getAll()).toHaveLength(1) + expect(getMutationCache(queryClient).getAll()).toHaveLength(1) unsubscribe() - expect(queryClient.getMutationCache().getAll()).toHaveLength(1) + expect(getMutationCache(queryClient).getAll()).toHaveLength(1) await vi.advanceTimersByTimeAsync(10) - expect(queryClient.getMutationCache().getAll()).toHaveLength(0) + expect(getMutationCache(queryClient).getAll()).toHaveLength(0) }) it('should be garbage collected later when unsubscribed and mutation is pending', async () => { @@ -531,13 +532,13 @@ describe('mutationCache', () => { observer.mutate(1) unsubscribe() - expect(queryClient.getMutationCache().getAll()).toHaveLength(1) + expect(getMutationCache(queryClient).getAll()).toHaveLength(1) await vi.advanceTimersByTimeAsync(10) // unsubscribe should not remove even though gcTime has elapsed b/c mutation is still pending - expect(queryClient.getMutationCache().getAll()).toHaveLength(1) + expect(getMutationCache(queryClient).getAll()).toHaveLength(1) await vi.advanceTimersByTimeAsync(10) // should be removed after an additional gcTime wait - expect(queryClient.getMutationCache().getAll()).toHaveLength(0) + expect(getMutationCache(queryClient).getAll()).toHaveLength(0) expect(onSuccess).toHaveBeenCalledTimes(1) }) @@ -563,7 +564,7 @@ describe('mutationCache', () => { unsubscribe() await vi.advanceTimersByTimeAsync(10) - expect(queryClient.getMutationCache().getAll()).toHaveLength(0) + expect(getMutationCache(queryClient).getAll()).toHaveLength(0) expect(onSuccess).toHaveBeenCalledTimes(1) }) }) diff --git a/packages/query-core/src/__tests__/mutationObserver.test.tsx b/packages/query-core/src/__tests__/mutationObserver.test.tsx index 86037973441..48f327bba42 100644 --- a/packages/query-core/src/__tests__/mutationObserver.test.tsx +++ b/packages/query-core/src/__tests__/mutationObserver.test.tsx @@ -1,4 +1,5 @@ import { createKey, sleep } from '@tanstack/query-test-utils' +import { getMutationCache } from '@tanstack/query-test-utils/cacheOperations' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MutationObserver, QueryClient } from '..' import type { MutationFunctionContext, MutationObserverResult } from '..' @@ -61,11 +62,11 @@ describe('mutationObserver', () => { mutation.mutate('input') await vi.advanceTimersByTimeAsync(5) - expect(queryClient.getMutationCache().findAll()).toHaveLength(1) + expect(getMutationCache(queryClient).findAll()).toHaveLength(1) unsubscribe() await vi.advanceTimersByTimeAsync(10) - expect(queryClient.getMutationCache().findAll()).toHaveLength(0) + expect(getMutationCache(queryClient).findAll()).toHaveLength(0) }) it('should reattach the observer to the in-flight mutation when resubscribing', async () => { @@ -125,11 +126,11 @@ describe('mutationObserver', () => { mutation.mutate('input') await vi.advanceTimersByTimeAsync(5) - expect(queryClient.getMutationCache().findAll()).toHaveLength(1) + expect(getMutationCache(queryClient).findAll()).toHaveLength(1) mutation.reset() await vi.advanceTimersByTimeAsync(10) - expect(queryClient.getMutationCache().findAll()).toHaveLength(0) + expect(getMutationCache(queryClient).findAll()).toHaveLength(0) unsubscribe() }) @@ -182,7 +183,7 @@ describe('mutationObserver', () => { mutationObserver.mutate('input') await vi.advanceTimersByTimeAsync(5) expect( - queryClient.getMutationCache().find({ mutationKey: [...key, '1'] }), + getMutationCache(queryClient).find({ mutationKey: [...key, '1'] }), ).toMatchObject({ options: { mutationKey: [...key, '1'] }, state: { @@ -195,7 +196,7 @@ describe('mutationObserver', () => { mutationKey: [...key, '2'], }) expect( - queryClient.getMutationCache().find({ mutationKey: [...key, '1'] }), + getMutationCache(queryClient).find({ mutationKey: [...key, '1'] }), ).toMatchObject({ options: { mutationKey: [...key, '1'] }, state: { @@ -222,7 +223,7 @@ describe('mutationObserver', () => { mutationObserver.mutate('input') await vi.advanceTimersByTimeAsync(5) - expect(queryClient.getMutationCache().find({})).toMatchObject({ + expect(getMutationCache(queryClient).find({})).toMatchObject({ options: { meta: { a: 1 } }, state: { status: 'success', @@ -233,7 +234,7 @@ describe('mutationObserver', () => { mutationObserver.setOptions({ meta: { a: 2 }, }) - expect(queryClient.getMutationCache().find({})).toMatchObject({ + expect(getMutationCache(queryClient).find({})).toMatchObject({ options: { meta: { a: 1 } }, state: { status: 'success', @@ -269,7 +270,7 @@ describe('mutationObserver', () => { mutationObserver.mutate('input') await vi.advanceTimersByTimeAsync(5) - const mutations = queryClient.getMutationCache().findAll() + const mutations = getMutationCache(queryClient).findAll() expect(mutations[0]).toMatchObject({ options: { meta: { a: 1 } }, state: { @@ -304,7 +305,7 @@ describe('mutationObserver', () => { mutationObserver.mutate('input').catch(() => undefined) await vi.advanceTimersByTimeAsync(5) - expect(queryClient.getMutationCache().find({})).toMatchObject({ + expect(getMutationCache(queryClient).find({})).toMatchObject({ options: { meta: { a: 1 } }, state: { status: 'error', @@ -314,7 +315,7 @@ describe('mutationObserver', () => { mutationObserver.setOptions({ meta: { a: 2 }, }) - expect(queryClient.getMutationCache().find({})).toMatchObject({ + expect(getMutationCache(queryClient).find({})).toMatchObject({ options: { meta: { a: 1 } }, state: { status: 'error', @@ -339,7 +340,7 @@ describe('mutationObserver', () => { mutationObserver.mutate('input') await vi.advanceTimersByTimeAsync(5) - expect(queryClient.getMutationCache().find({})).toMatchObject({ + expect(getMutationCache(queryClient).find({})).toMatchObject({ options: { meta: { a: 1 } }, state: { status: 'pending', @@ -349,7 +350,7 @@ describe('mutationObserver', () => { mutationObserver.setOptions({ meta: { a: 2 }, }) - expect(queryClient.getMutationCache().find({})).toMatchObject({ + expect(getMutationCache(queryClient).find({})).toMatchObject({ options: { meta: { a: 2 } }, state: { status: 'pending', @@ -598,7 +599,7 @@ describe('mutationObserver', () => { mutationFn: (text: string) => Promise.resolve(text), }) - const notifySpy = vi.spyOn(queryClient.getMutationCache(), 'notify') + const notifySpy = vi.spyOn(getMutationCache(queryClient), 'notify') const unsubscribe = mutationObserver.subscribe(() => undefined) diff --git a/packages/query-core/src/__tests__/queryClient.test-d.tsx b/packages/query-core/src/__tests__/queryClient.test-d.tsx index 83aec78b0c6..83160484381 100644 --- a/packages/query-core/src/__tests__/queryClient.test-d.tsx +++ b/packages/query-core/src/__tests__/queryClient.test-d.tsx @@ -1,4 +1,7 @@ -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' +import { + cacheOperations, + getMutationCache, +} from '@tanstack/query-test-utils/cacheOperations' import { selectOption } from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { QueryClient } from '../queryClient' @@ -911,9 +914,7 @@ describe('queryClient', () => { it('should return the MutationCache', () => { const queryClient = new QueryClient() - expectTypeOf( - queryClient.getMutationCache(), - ).toEqualTypeOf() + expectTypeOf(getMutationCache(queryClient)).toEqualTypeOf() }) }) diff --git a/packages/query-core/src/__tests__/queryClient.test.tsx b/packages/query-core/src/__tests__/queryClient.test.tsx index a95b2a356a1..b39ebaa9ffb 100644 --- a/packages/query-core/src/__tests__/queryClient.test.tsx +++ b/packages/query-core/src/__tests__/queryClient.test.tsx @@ -1,5 +1,8 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' +import { + cacheOperations, + getMutationCache, +} from '@tanstack/query-test-utils/cacheOperations' import { selectOption } from '@tanstack/query-test-utils/projection' import { serialScope } from '@tanstack/query-test-utils/scope' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -2393,7 +2396,7 @@ describe('queryClient', () => { 'onOnline', ) const mutationCacheResumePausedMutationsSpy = vi.spyOn( - testClient.getMutationCache(), + getMutationCache(testClient), 'resumePausedMutations', ) @@ -2422,7 +2425,7 @@ describe('queryClient', () => { 'onOnline', ) const mutationCacheResumePausedMutationsSpy = vi.spyOn( - testClient.getMutationCache(), + getMutationCache(testClient), 'resumePausedMutations', ) @@ -2586,15 +2589,15 @@ describe('queryClient', () => { hydrate(newQueryClient, state) // still paused because we are still offline - expect( - newQueryClient.getMutationCache().getAll()[0]?.state.isPaused, - ).toBe(true) + expect(getMutationCache(newQueryClient).getAll()[0]?.state.isPaused).toBe( + true, + ) await newQueryClient.resumePausedMutations() onlineManager.setOnline(true) await vi.advanceTimersByTimeAsync(0) - expect(newQueryClient.getMutationCache().getAll()[0]?.state.status).toBe( + expect(getMutationCache(newQueryClient).getAll()[0]?.state.status).toBe( 'success', ) @@ -2695,7 +2698,7 @@ describe('queryClient', () => { 'onOnline', ) const mutationCacheResumePausedMutationsSpy = vi.spyOn( - testClient.getMutationCache(), + getMutationCache(testClient), 'resumePausedMutations', ) @@ -2730,7 +2733,7 @@ describe('queryClient', () => { 'onOnline', ) const mutationCacheResumePausedMutationsSpy = vi.spyOn( - testClient.getMutationCache(), + getMutationCache(testClient), 'resumePausedMutations', ) diff --git a/packages/query-core/src/__tests__/utils.test.tsx b/packages/query-core/src/__tests__/utils.test.tsx index 1fa46835e7d..b3169c0be13 100644 --- a/packages/query-core/src/__tests__/utils.test.tsx +++ b/packages/query-core/src/__tests__/utils.test.tsx @@ -1,4 +1,5 @@ import { createKey } from '@tanstack/query-test-utils' +import { getMutationCache } from '@tanstack/query-test-utils/cacheOperations' import { describe, expect, it, vi } from 'vitest' import { QueryClient } from '..' import { Mutation } from '../mutation' @@ -559,7 +560,7 @@ describe('core/utils', () => { const mutation = new Mutation({ client: queryClient, mutationId: 1, - mutationCache: queryClient.getMutationCache(), + mutationCache: getMutationCache(queryClient), options: {}, }) diff --git a/packages/query-test-utils/src/cacheOperations.ts b/packages/query-test-utils/src/cacheOperations.ts index 1c040648ca2..aab73fe28d9 100644 --- a/packages/query-test-utils/src/cacheOperations.ts +++ b/packages/query-test-utils/src/cacheOperations.ts @@ -7,3 +7,14 @@ export function cacheOperations(client: TClient): TClient { return client } + +/** + * Reads the cache from clients with the standard instance method. + * @param client - Query client under test. + * @returns The client's configured mutation cache. + */ +export function getMutationCache(client: { + getMutationCache: () => TCache +}): TCache { + return client.getMutationCache() +} diff --git a/packages/react-query-no-core-pluggable/README.md b/packages/react-query-no-core-pluggable/README.md index 464ecf53e82..133cfdd24e2 100644 --- a/packages/react-query-no-core-pluggable/README.md +++ b/packages/react-query-no-core-pluggable/README.md @@ -67,6 +67,10 @@ function usePostTitle(id: number) { ## Mutations and cache operations +`useMutation`, `useMutationState`, and `useIsMutating` acquire the client's mutation cache automatically. To inspect or subscribe to it directly, replace `client.getMutationCache()` with the named export `getMutationCache(client)`. The first call creates a default cache for that client. If you supplied `new QueryClient({ mutationCache })`, the helper returns that same cache. An app that uses only `useQuery` can omit the mutation cache implementation from its bundle. + +Integrations that subscribe to both caches need the same migration. For example, a persistence integration for this adapter can subscribe to `client.getQueryCache()` and `getMutationCache(client)`. The stock `@tanstack/query-persist-client-core` subscription expects the v6 client instance method. + Pass `scope: serialScope('orders')` to `useMutation` to run mutations with that ID one at a time within a cache. Multiple calls to `serialScope('orders')` share the queue. The scope ID survives dehydration and hydration. Imperative infinite queries and bulk cache operations are named exports. Pass the client as the first argument. diff --git a/packages/react-query-no-core-pluggable/src/__tests__/getMutationCache.test.ts b/packages/react-query-no-core-pluggable/src/__tests__/getMutationCache.test.ts new file mode 100644 index 00000000000..3286b5a33aa --- /dev/null +++ b/packages/react-query-no-core-pluggable/src/__tests__/getMutationCache.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it, vi } from 'vitest' +import { + MutationCache, + MutationObserver, + QueryClient, + dehydrate, + getMutationCache, + hydrate, +} from '..' +import { mutationCacheKey } from '../runtime/queryClient' + +describe('getMutationCache', () => { + it('keeps query-only hydration, resume and clear free of mutation caches', async () => { + const server = new QueryClient() + const client = new QueryClient() + server.setQueryData(['books'], ['Dune']) + hydrate(client, dehydrate(server)) + + expect(client.getQueryData(['books'])).toStrictEqual(['Dune']) + expect(client.isMutating()).toBe(0) + await expect(client.resumePausedMutations()).resolves.toStrictEqual([]) + client.clear() + expect(client.getQueryData(['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([]) + first.clear() + 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') + client.clear() + expect(cache.getAll()).toStrictEqual([]) + }) +}) diff --git a/packages/react-query-no-core-pluggable/src/index.ts b/packages/react-query-no-core-pluggable/src/index.ts index a5dddd66238..af4348b29f1 100644 --- a/packages/react-query-no-core-pluggable/src/index.ts +++ b/packages/react-query-no-core-pluggable/src/index.ts @@ -13,7 +13,7 @@ export { } from './runtime/hydration' export { infiniteQuery } from './runtime/infiniteQuery' export { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' -export { MutationCache } from './runtime/mutationCache' +export { MutationCache, getMutationCache } from './runtime/mutationCache' export type { MutationCacheNotifyEvent, MutationCacheConfig, diff --git a/packages/react-query-no-core-pluggable/src/runtime/hydration.ts b/packages/react-query-no-core-pluggable/src/runtime/hydration.ts index bfa78711e61..d3905a7bb1b 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/hydration.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/hydration.ts @@ -1,5 +1,6 @@ import { prepareInfiniteFetch } from './infiniteQueryBehavior' import { Mutation } from './mutation' +import { mutationCacheKey } from './queryClient' import { serialScope } from './serialScope' import { noop } from './utils' import type * as Shared from '@tanstack/query-types/bindings' @@ -186,12 +187,12 @@ export function dehydrate( client.getDefaultOptions().dehydrate?.shouldDehydrateMutation ?? defaultShouldDehydrateMutation - const mutations = client - .getMutationCache() - .getAll() - .flatMap((mutation) => - filterMutation(mutation) ? [dehydrateMutation(mutation)] : [], - ) + const mutations = + client[mutationCacheKey] + ?.getAll() + .flatMap((mutation) => + filterMutation(mutation) ? [dehydrateMutation(mutation)] : [], + ) ?? [] const filterQuery = options.shouldDehydrateQuery ?? diff --git a/packages/react-query-no-core-pluggable/src/runtime/mutation.ts b/packages/react-query-no-core-pluggable/src/runtime/mutation.ts index 2a8bfe30d88..5257b436f22 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/mutation.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/mutation.ts @@ -1,3 +1,4 @@ +import { getMutationCache } from './mutationCache' import { notifyManager } from './notifyManager' import { Removable } from './removable' import { createRetryer } from './retryer' @@ -40,7 +41,7 @@ type MutationConfig = * is possible via `mutationCache.find()`/`getAll()` for inspecting cache state. * @example * ```ts - * const mutationCache = queryClient.getMutationCache() + * const mutationCache = getMutationCache(queryClient) * * const mutation = mutationCache.find({ mutationKey: ['addPost'] }) * ``` @@ -74,7 +75,7 @@ export class Mutation< options: MutationOptions, state?: MutationState, ): Mutation { - const cache = client.getMutationCache() + const cache = getMutationCache(client) return cache.register( (mutationId) => new Mutation({ diff --git a/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts b/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts index e3e341b42f0..d85c33af47e 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts @@ -1,8 +1,10 @@ import { notifyManager } from './notifyManager' +import { mutationCacheKey } from './queryClient' import { Subscribable } from './subscribable' import { matchMutation, noop } from './utils' import type * as Shared from '@tanstack/query-types/bindings' import type { Mutation } from './mutation' +import type { QueryClient } from './queryClient' import type { QueryRuntime } from './runtimeBinding' import type { DefaultError } from './types' import type { MutationFilters } from './utils' @@ -16,14 +18,26 @@ export type MutationCacheNotifyEvent = type MutationCacheListener = Shared.MutationCacheListener -// CLASS - /** - * The `MutationCache` is the storage for mutations. + * 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/react-query-no-core-pluggable' * - * Normally, you will not interact with the `MutationCache` directly and instead use a - * `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of - * safe/known updates to the cache, such as mutations being added, removed, or updated. + * 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) => { @@ -119,7 +133,7 @@ export class MutationCache extends Subscribable { * Mutations that are already running continue to execute. * @example * ```ts - * const mutationCache = queryClient.getMutationCache() + * const mutationCache = getMutationCache(queryClient) * * mutationCache.clear() * ``` @@ -146,7 +160,7 @@ export class MutationCache extends Subscribable { * @returns Every mutation in the cache. * @example * ```ts - * const mutationCache = queryClient.getMutationCache() + * const mutationCache = getMutationCache(queryClient) * * const mutations = mutationCache.getAll() * ``` @@ -166,7 +180,7 @@ export class MutationCache extends Subscribable { * @see {@link MutationCache#findAll} * @example * ```ts - * const mutationCache = queryClient.getMutationCache() + * const mutationCache = getMutationCache(queryClient) * * const mutation = mutationCache.find({ mutationKey: ['addPost'] }) * ``` @@ -197,7 +211,7 @@ export class MutationCache extends Subscribable { * @see {@link MutationCache#find} * @example * ```ts - * const mutationCache = queryClient.getMutationCache() + * const mutationCache = getMutationCache(queryClient) * * const mutations = mutationCache.findAll({ mutationKey: ['addPost'] }) * ``` diff --git a/packages/react-query-no-core-pluggable/src/runtime/mutationObserver.ts b/packages/react-query-no-core-pluggable/src/runtime/mutationObserver.ts index 2feb3590d83..f140cc0839d 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/mutationObserver.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/mutationObserver.ts @@ -1,4 +1,5 @@ import { Mutation, getDefaultState } from './mutation' +import { getMutationCache } from './mutationCache' import { notifyManager } from './notifyManager' import { Subscribable } from './subscribable' import { hashKeyByOptions, shallowEqualObjects } from './utils' @@ -114,8 +115,9 @@ export class MutationObserver< | MutationObserverOptions | undefined this.options = this.#client.defaultMutationOptions(options) + const mutationCache = getMutationCache(this.#client) if (!shallowEqualObjects(this.options, prevOptions)) { - this.#client.getMutationCache().notify({ + mutationCache.notify({ type: 'observerOptionsUpdated', mutation: this.#currentMutation, observer: this, @@ -127,11 +129,11 @@ export class MutationObserver< this.options.mutationKey && hashKeyByOptions( prevOptions.mutationKey, - this.#client.getMutationCache().config.mutationKey, + mutationCache.config.mutationKey, ) !== hashKeyByOptions( this.options.mutationKey, - this.#client.getMutationCache().config.mutationKey, + mutationCache.config.mutationKey, ) ) { this.reset() diff --git a/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts b/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts index e0fc33effe0..a5f8ac6f7ce 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts @@ -1,5 +1,4 @@ import { focusManager } from './focusManager' -import { MutationCache } from './mutationCache' import { onlineManager } from './onlineManager' import { QueryCache } from './queryCache' import { @@ -11,6 +10,7 @@ import { skipToken, } from './utils' import type { WithoutSkipToken } from '@tanstack/query-types/bindings' +import type { MutationCache } from './mutationCache' import type { QueryState } from './query' import type { CacheKeyConfig, @@ -56,12 +56,15 @@ class KeyDefaults< } } -// CLASS +/** @internal */ +export const mutationCacheKey = Symbol.for( + '@tanstack/react-query-no-core-pluggable/mutationCache', +) /** - * `QueryClient` is used to interact with a cache of queries and mutations. It owns a - * `QueryCache` and a `MutationCache` (creating default ones if none are passed in) and holds - * the default options that are applied to queries and mutations created through it. + * Stores the query cache and default options for this client's queries and mutations. + * Pass a custom mutation cache in the constructor or let mutation hooks and + * `getMutationCache(client)` create one on first use. * @example * ```ts * const queryClient = new QueryClient({ @@ -76,8 +79,9 @@ class KeyDefaults< * ``` */ export class QueryClient { + /** @internal */ + [mutationCacheKey]?: MutationCache #queryCache: QueryCache - #mutationCache: MutationCache #defaultOptions: DefaultOptions #queryDefaults = new KeyDefaults() #mutationDefaults = new KeyDefaults() @@ -87,7 +91,7 @@ export class QueryClient { constructor(config: QueryClientConfig = {}) { this.#queryCache = config.queryCache || new QueryCache() - this.#mutationCache = config.mutationCache || new MutationCache() + this[mutationCacheKey] = config.mutationCache this.#defaultOptions = config.defaultOptions || {} this.#mountCount = 0 } @@ -170,7 +174,10 @@ export class QueryClient { any >, >(filters?: NoInfer>): number { - return this.#mutationCache.findAll({ ...filters, status: 'pending' }).length + return ( + this[mutationCacheKey]?.findAll({ ...filters, status: 'pending' }) + .length ?? 0 + ) } /** @@ -417,7 +424,9 @@ export class QueryClient { */ resumePausedMutations(): Promise { if (onlineManager.isOnline()) { - return this.#mutationCache.resumePausedMutations() + return ( + this[mutationCacheKey]?.resumePausedMutations() ?? Promise.resolve([]) + ) } return Promise.resolve() } @@ -438,22 +447,6 @@ export class QueryClient { return this.#queryCache } - /** - * Returns the mutation cache this client is connected to. - * @returns The {@link MutationCache} instance. - * @example - * ```ts - * import { QueryClient } from '@tanstack/react-query-no-core-pluggable' - * - * const queryClient = new QueryClient() - * const mutationCache = queryClient.getMutationCache() - * const mutations = mutationCache.findAll({ status: 'pending' }) - * ``` - */ - getMutationCache(): MutationCache { - return this.#mutationCache - } - /** * Returns the default options that were set when creating the client, or via * {@link QueryClient#setDefaultOptions}. @@ -569,7 +562,7 @@ export class QueryClient { this.#mutationDefaults.set( mutationKey, options, - this.#mutationCache.config.mutationKey, + this[mutationCacheKey]?.config.mutationKey, ) } @@ -590,7 +583,7 @@ export class QueryClient { ): OmitKeyof, 'mutationKey'> { return this.#mutationDefaults.get( mutationKey, - this.#mutationCache.config.mutationKey, + this[mutationCacheKey]?.config.mutationKey, ) } @@ -724,6 +717,6 @@ export class QueryClient { */ clear(): void { this.#queryCache.clear() - this.#mutationCache.clear() + this[mutationCacheKey]?.clear() } } diff --git a/packages/react-query-no-core-pluggable/src/runtime/utils.ts b/packages/react-query-no-core-pluggable/src/runtime/utils.ts index 7a666f2aa50..9d3c33c7bbf 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/utils.ts +++ b/packages/react-query-no-core-pluggable/src/runtime/utils.ts @@ -188,7 +188,7 @@ export function matchQuery( * @returns `true` if the mutation matches every specified filter. * @example * ```ts - * const mutationCache = queryClient.getMutationCache() + * const mutationCache = getMutationCache(queryClient) * * const matchingMutations = mutationCache * .getAll() diff --git a/packages/react-query-no-core-pluggable/src/useMutationState.ts b/packages/react-query-no-core-pluggable/src/useMutationState.ts index 28e15d17301..fa732480865 100644 --- a/packages/react-query-no-core-pluggable/src/useMutationState.ts +++ b/packages/react-query-no-core-pluggable/src/useMutationState.ts @@ -1,6 +1,7 @@ 'use client' import * as React from 'react' import { useQueryClient } from './QueryClientProvider' +import { getMutationCache } from './runtime/mutationCache' import { notifyManager } from './runtime/notifyManager' import { replaceEqualDeep } from './runtime/utils' import type { MutationState } from '@tanstack/query-types/bindings' @@ -186,7 +187,7 @@ export function useMutationState< options: MutationStateOptions = {}, queryClient?: QueryClient, ): Array { - const mutationCache = useQueryClient(queryClient).getMutationCache() + const mutationCache = getMutationCache(useQueryClient(queryClient)) const [createSnapshot] = React.useState(() => createSnapshotFactory(), ) diff --git a/packages/react-query-no-core-pluggable/tests/compat-cacheOperations.ts b/packages/react-query-no-core-pluggable/tests/compat-cacheOperations.ts index bba5a0616b9..4981592c4f1 100644 --- a/packages/react-query-no-core-pluggable/tests/compat-cacheOperations.ts +++ b/packages/react-query-no-core-pluggable/tests/compat-cacheOperations.ts @@ -28,3 +28,5 @@ export function cacheOperations(client: TClient) { refetchQueries: bind(refetchQueries), } } + +export { getMutationCache } from '../src' diff --git a/packages/react-query/src/__tests__/useMutation.test.tsx b/packages/react-query/src/__tests__/useMutation.test.tsx index 011c12a1e12..9171fe68eb7 100644 --- a/packages/react-query/src/__tests__/useMutation.test.tsx +++ b/packages/react-query/src/__tests__/useMutation.test.tsx @@ -1,5 +1,8 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' +import { + cacheOperations, + getMutationCache, +} from '@tanstack/query-test-utils/cacheOperations' import { act, fireEvent, render } from '@testing-library/react' import * as React from 'react' import { ErrorBoundary } from 'react-error-boundary' @@ -1085,7 +1088,7 @@ describe('useMutation', () => { expect(count).toBe(0) onlineMock.mockReturnValue(true) - queryClient.getMutationCache().resumePausedMutations() + getMutationCache(queryClient).resumePausedMutations() await vi.advanceTimersByTimeAsync(6) expect( @@ -1142,7 +1145,7 @@ describe('useMutation', () => { }) onlineMock.mockReturnValue(true) - queryClient.getMutationCache().resumePausedMutations() + getMutationCache(queryClient).resumePausedMutations() await vi.advanceTimersByTimeAsync(11) expect( @@ -1197,7 +1200,7 @@ describe('useMutation', () => { expect(states[1]).toBe('pending, true') onlineMock.mockReturnValue(true) - queryClient.getMutationCache().resumePausedMutations() + getMutationCache(queryClient).resumePausedMutations() await vi.advanceTimersByTimeAsync(11) expect( @@ -1245,10 +1248,10 @@ describe('useMutation', () => { expect(rendered.getByText('isPaused: true')).toBeInTheDocument() expect( - queryClient.getMutationCache().findAll({ mutationKey: key }), + getMutationCache(queryClient).findAll({ mutationKey: key }), ).toHaveLength(1) expect( - queryClient.getMutationCache().findAll({ mutationKey: key })[0]?.state, + getMutationCache(queryClient).findAll({ mutationKey: key })[0]?.state, ).toMatchObject({ status: 'pending', isPaused: true, @@ -1257,13 +1260,13 @@ describe('useMutation', () => { }) onlineMock.mockReturnValue(true) - queryClient.getMutationCache().resumePausedMutations() + getMutationCache(queryClient).resumePausedMutations() await vi.advanceTimersByTimeAsync(11) expect(rendered.getByText('data: data2')).toBeInTheDocument() expect( - queryClient.getMutationCache().findAll({ mutationKey: key })[0]?.state, + getMutationCache(queryClient).findAll({ mutationKey: key })[0]?.state, ).toMatchObject({ status: 'success', isPaused: false, @@ -1296,12 +1299,12 @@ describe('useMutation', () => { expect(states).toStrictEqual(['idle', 'pending']) fireEvent.click(getByText('unmount')) - expect(queryClient.getMutationCache().getAll()[0]?.state.status).toBe( + expect(getMutationCache(queryClient).getAll()[0]?.state.status).toBe( 'pending', ) await vi.advanceTimersByTimeAsync(11) - expect(queryClient.getMutationCache().getAll()[0]?.state.status).toBe( + expect(getMutationCache(queryClient).getAll()[0]?.state.status).toBe( 'success', ) expect(states).toStrictEqual(['idle', 'pending']) @@ -1641,9 +1644,9 @@ describe('useMutation', () => { fireEvent.click(rendered.getByRole('button', { name: /mutate/i })) fireEvent.click(rendered.getByRole('button', { name: /hide/i })) await vi.advanceTimersByTimeAsync(10) - expect( - queryClient.getMutationCache().findAll({ mutationKey }), - ).toHaveLength(0) + expect(getMutationCache(queryClient).findAll({ mutationKey })).toHaveLength( + 0, + ) expect(count).toBe(1) diff --git a/packages/react-query/src/__tests__/useMutationState.test.tsx b/packages/react-query/src/__tests__/useMutationState.test.tsx index a22294f5e80..1003e793651 100644 --- a/packages/react-query/src/__tests__/useMutationState.test.tsx +++ b/packages/react-query/src/__tests__/useMutationState.test.tsx @@ -1,5 +1,6 @@ import { Mutation } from '@tanstack/query-core' import { createKey, sleep } from '@tanstack/query-test-utils' +import { getMutationCache } from '@tanstack/query-test-utils/cacheOperations' import { fireEvent, render } from '@testing-library/react' import * as React from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -251,7 +252,7 @@ describe('useMutationState', () => { const queryClient = new QueryClient() const key1 = createKey() const key2 = createKey() - const cache = queryClient.getMutationCache() + const cache = getMutationCache(queryClient) Mutation.build(queryClient, { mutationKey: key1 }) Mutation.build(queryClient, { mutationKey: key2 }) const onCacheChange = vi.fn<(event: MutationCacheNotifyEvent) => void>() @@ -308,7 +309,7 @@ describe('useMutationState', () => { (resultType) => { const queryClient = new QueryClient() const key = createKey() - const cache = queryClient.getMutationCache() + const cache = getMutationCache(queryClient) const existingMutation = Mutation.build(queryClient, { mutationKey: key, meta: { time: 0 }, @@ -512,8 +513,8 @@ describe('useMutationState', () => { expect( rendered.getByText(`keys: ${JSON.stringify([key2])}`), ).toBeInTheDocument() - expect(client1.getMutationCache().hasListeners()).toBe(false) - expect(client2.getMutationCache().hasListeners()).toBe(true) + expect(getMutationCache(client1).hasListeners()).toBe(false) + expect(getMutationCache(client2).hasListeners()).toBe(true) }) it('should remove successful mutations when the query client is cleared', async () => { @@ -544,7 +545,7 @@ describe('useMutationState', () => { fireEvent.click(rendered.getByRole('button', { name: 'clear' })) await vi.advanceTimersByTimeAsync(1) - expect(queryClient.getMutationCache().getAll()).toStrictEqual([]) + expect(getMutationCache(queryClient).getAll()).toStrictEqual([]) expect(rendered.getByText('data: []')).toBeInTheDocument() }) diff --git a/scripts/test-react-query-compat.mjs b/scripts/test-react-query-compat.mjs index 80ac313690a..f47df32654b 100644 --- a/scripts/test-react-query-compat.mjs +++ b/scripts/test-react-query-compat.mjs @@ -72,6 +72,17 @@ for (const suite of ['query-core', 'react-query']) { noEmit: true, paths: { '@tanstack/query-core': [entry], + // The React suite uses per-query persistence. The separate whole-client + // persister subscribes through the original client's mutation-cache method. + ...(pluggable && + suite === 'react-query' && { + '@tanstack/query-persist-client-core': [ + join( + repository, + 'packages/query-persist-client-core/src/createPersister.ts', + ), + ], + }), ...(pluggable && Object.fromEntries( ['polling', 'cacheOperations', 'projection', 'scope'].map( From 8a21fac770b3d63a8fada1f272cd33df9eda89ff Mon Sep 17 00:00:00 2001 From: Jonghyeon Ko Date: Fri, 27 Nov 2026 23:00:46 +0900 Subject: [PATCH 11/11] feat(react-query): compose query modes and import client operations from a shared-core adapter --- .changeset/react-query-pluggable.md | 8 + .changeset/react-query-standalone-adapters.md | 10 - .github/workflows/react-query-bundle-size.yml | 3 +- integrations/react/bundle-size/README.md | 14 +- .../react/bundle-size/browser/apps.test.js | 38 +- integrations/react/bundle-size/measure.mjs | 218 +- integrations/react/bundle-size/package.json | 3 +- .../react/bundle-size/src/paginated.jsx | 4 +- .../react/bundle-size/src/pluggable-query.js | 17 + .../react/bundle-size/src/polling.jsx | 83 +- integrations/react/bundle-size/src/query.jsx | 4 +- .../react/bundle-size/src/v6-query.js | 6 + .../bundle-size/vitest.browser.config.js | 33 + integrations/react/nodenext/README.md | 2 +- integrations/react/nodenext/package.json | 4 +- .../react/nodenext/src/sharedTypes.ts | 23 +- knip.config.ts | 23 +- nx.json | 1 + packages/query-core/package.json | 8 +- .../query-core/src/__tests__/cacheGc.test.tsx | 5 +- .../src/__tests__/hydration.test.tsx | 21 +- .../__tests__/infiniteQueryBehavior.test.tsx | 5 +- .../__tests__/infiniteQueryObserver.test.tsx | 3 +- .../src/__tests__/mutation.test.tsx | 31 +- .../src/__tests__/mutationCache.test-d.tsx | 3 +- .../src/__tests__/mutationCache.test.tsx | 19 +- .../src/__tests__/mutationObserver.test.tsx | 29 +- .../src/__tests__/queriesObserver.test.tsx | 11 +- .../query-core/src/__tests__/query.test.tsx | 20 +- .../src/__tests__/queryCache.test.tsx | 3 +- .../src/__tests__/queryClient.test-d.tsx | 115 +- .../src/__tests__/queryClient.test.tsx | 157 +- .../src/__tests__/queryObserver.test.tsx | 17 +- .../__tests__/queryObserverProjection.test.ts | 5 +- .../src/__tests__/streamedQuery.test.tsx | 7 +- .../query-core/src/__tests__/utils.test-d.tsx | 12 +- .../query-core/src/__tests__/utils.test.tsx | 3 +- packages/query-core/src/environmentManager.ts | 7 +- packages/query-core/src/focusManager.ts | 10 +- packages/query-core/src/hydration.ts | 96 +- packages/query-core/src/index.ts | 1 - .../query-core/src/infiniteQueryObserver.ts | 39 +- packages/query-core/src/mutation.ts | 123 +- packages/query-core/src/mutationCache.ts | 113 +- packages/query-core/src/mutationObserver.ts | 15 +- packages/query-core/src/notifyManager.ts | 16 +- packages/query-core/src/onlineManager.ts | 7 +- packages/query-core/src/primitives.ts | 57 + packages/query-core/src/queriesObserver.ts | 68 +- packages/query-core/src/query.ts | 337 ++- packages/query-core/src/queryCache.ts | 120 +- packages/query-core/src/queryClient.ts | 20 +- packages/query-core/src/queryObserver.ts | 125 +- packages/query-core/src/queryState.ts | 84 + packages/query-core/src/retryer.ts | 86 +- packages/query-core/src/runtimeBinding.ts | 42 - packages/query-core/src/streamedQuery.ts | 49 +- packages/query-core/src/timeoutManager.ts | 61 +- packages/query-core/src/types.ts | 2528 ++++++++++++++-- packages/query-core/src/utils.ts | 154 +- packages/query-core/tsconfig.json | 7 +- packages/query-core/tsconfig.legacy.json | 7 +- packages/query-test-utils/package.json | 1 - .../query-test-utils/src/cacheOperations.ts | 20 - packages/query-test-utils/src/polling.ts | 2 +- packages/query-types/README.md | 27 - packages/query-types/oxlint.config.ts | 7 - packages/query-types/package.json | 57 - packages/query-types/src/binding.ts | 127 - packages/query-types/src/bindings.ts | 235 -- packages/query-types/src/contracts.ts | 692 ----- .../query-types/src/environmentManager.ts | 4 - packages/query-types/src/focusManager.ts | 7 - packages/query-types/src/hydration.ts | 91 - packages/query-types/src/index.ts | 612 ---- .../query-types/src/infiniteQueryObserver.ts | 47 - packages/query-types/src/mutation.ts | 120 - packages/query-types/src/mutationCache.ts | 130 - packages/query-types/src/mutationObserver.ts | 20 - packages/query-types/src/notifyManager.ts | 17 - packages/query-types/src/onlineManager.ts | 7 - packages/query-types/src/queriesObserver.ts | 57 - packages/query-types/src/query.ts | 258 -- packages/query-types/src/queryCache.ts | 147 - packages/query-types/src/queryClient.ts | 25 - packages/query-types/src/queryObserver.ts | 122 - packages/query-types/src/retryer.ts | 76 - packages/query-types/src/streamedQuery.ts | 62 - packages/query-types/src/symbols.ts | 26 - packages/query-types/src/timeoutManager.ts | 51 - packages/query-types/src/types.ts | 2585 ----------------- packages/query-types/src/utils.ts | 120 - packages/query-types/tsconfig.json | 8 - packages/query-types/tsconfig.legacy.json | 8 - packages/query-types/tsdown.config.ts | 6 - .../react-query-no-core-pluggable/README.md | 88 - .../root.oxlint.config.ts | 1 - .../root.tsdown.config.js | 1 - .../src/QueryErrorResetBoundary.tsx | 169 -- .../src/infiniteQueryOptions.ts | 304 -- .../src/mutationOptions.ts | 89 - .../src/queryOptions.ts | 249 -- .../src/runtime/environmentManager.ts | 41 - .../src/runtime/focusManager.ts | 142 - .../src/runtime/notifyManager.ts | 126 - .../src/runtime/onlineManager.ts | 120 - .../src/runtime/queryCache.ts | 301 -- .../src/runtime/queryClient.ts | 722 ----- .../src/runtime/removable.ts | 65 - .../src/runtime/retryer.ts | 241 -- .../src/runtime/runtimeBinding.ts | 63 - .../src/runtime/streamedQuery.ts | 112 - .../src/runtime/subscribable.ts | 65 - .../src/runtime/timeoutManager.ts | 211 -- .../src/runtime/types.ts | 450 --- .../src/runtime/utils.ts | 746 ----- .../src/suspense.ts | 214 -- .../src/useInfiniteQuery.ts | 364 --- .../src/useIsFetching.ts | 57 - .../src/useMutation.ts | 239 -- .../src/usePrefetchQuery.tsx | 60 - .../src/useSuspenseInfiniteQuery.ts | 185 -- .../src/useSuspenseQuery.ts | 151 - .../tests/compat-cacheOperations.ts | 32 - .../tests/compat-infiniteQuery.ts | 76 - .../tsconfig.prod.json | 10 - packages/react-query-no-core/README.md | 35 - packages/react-query-no-core/oxlint.config.ts | 51 - packages/react-query-no-core/package.json | 80 - .../react-query-no-core/root.oxlint.config.ts | 1 - .../react-query-no-core/root.tsdown.config.js | 1 - .../src/HydrationBoundary.tsx | 137 - .../src/IsRestoringProvider.ts | 18 - .../src/QueryClientProvider.tsx | 84 - .../src/errorBoundaryUtils.ts | 105 - packages/react-query-no-core/src/index.ts | 240 -- .../src/runtime/environmentManager.ts | 41 - .../src/runtime/focusManager.ts | 142 - .../src/runtime/hydration.ts | 370 --- .../src/runtime/identity.ts | 9 - .../src/runtime/infiniteQueryBehavior.ts | 184 -- .../src/runtime/infiniteQueryObserver.ts | 277 -- .../src/runtime/mutation.ts | 503 ---- .../src/runtime/mutationCache.ts | 272 -- .../src/runtime/mutationObserver.ts | 331 --- .../src/runtime/onlineManager.ts | 120 - .../src/runtime/queriesObserver.ts | 459 --- .../react-query-no-core/src/runtime/query.ts | 877 ------ .../src/runtime/queryClient.ts | 1077 ------- .../src/runtime/queryObserver.ts | 1036 ------- .../src/runtime/removable.ts | 65 - .../src/runtime/retryer.ts | 241 -- .../src/runtime/runtimeBinding.ts | 47 - .../src/runtime/subscribable.ts | 65 - .../src/runtime/timeoutManager.ts | 211 -- .../react-query-no-core/src/runtime/types.ts | 450 --- .../react-query-no-core/src/runtime/utils.ts | 746 ----- packages/react-query-no-core/src/types.ts | 473 --- .../react-query-no-core/src/useBaseQuery.ts | 146 - .../src/useMutationState.ts | 204 -- .../src/useObserverSnapshot.ts | 43 - .../src/usePrefetchInfiniteQuery.tsx | 72 - .../react-query-no-core/src/useQueries.ts | 482 --- packages/react-query-no-core/src/useQuery.ts | 298 -- .../src/useSuspenseQueries.ts | 547 ---- packages/react-query-no-core/tsconfig.json | 15 - .../react-query-no-core/tsconfig.legacy.json | 9 - .../react-query-no-core/tsconfig.prod.json | 10 - packages/react-query-no-core/tsdown.config.ts | 8 - packages/react-query-pluggable/README.md | 168 ++ .../oxlint.config.ts | 0 .../package.json | 9 +- .../root.oxlint.config.ts | 0 .../root.tsdown.config.js | 0 .../src/HydrationBoundary.tsx | 12 +- .../src/IsRestoringProvider.ts | 0 .../src/QueryClientProvider.tsx | 9 +- .../src/QueryErrorResetBoundary.tsx | 4 +- .../src/__tests__/cacheOperations.test.ts | 15 +- .../src/__tests__/fetchInfiniteQuery.test.ts} | 19 +- .../src/__tests__/getMutationCache.test.ts | 25 +- .../src/__tests__/projection.test-d.ts | 0 .../src/__tests__/projection.test.ts | 11 +- .../src/__tests__/queryBuilders.test.ts | 14 + .../src/__tests__/queryModes.test-d.ts | 63 + .../src/__tests__/queryModes.test.tsx | 90 + .../src/__tests__/refetchInterval.test-d.ts | 0 .../src/__tests__/refetchInterval.test.ts | 4 +- .../src/__tests__/serialScope.test.ts | 9 +- .../src/__tests__/sharedCore.test.ts | 44 + .../src/errorBoundaryUtils.ts | 8 +- .../src/index.ts | 227 +- .../src/infiniteQuery.ts | 85 + .../src/infiniteQueryOptions.ts | 23 +- .../src/mutationOptions.ts | 6 +- .../src/queryOptions.ts | 26 +- .../src/runtime/cacheOperations.ts | 42 +- .../src/runtime/fetchInfiniteQuery.ts} | 16 +- .../src/runtime/hydration.ts | 89 +- .../src/runtime/identity.ts | 0 .../src/runtime/infiniteQueryBehavior.ts | 6 +- .../src/runtime/infiniteQueryObserver.ts | 41 +- .../src/runtime/mutation.ts | 35 +- .../src/runtime/mutationCache.ts | 115 +- .../src/runtime/mutationObserver.ts | 25 +- .../src/runtime/notifyManager.ts | 15 +- .../src/runtime/placeholderData.ts | 11 +- .../src/runtime/projectResult.ts | 0 .../src/runtime/projectionTypes.ts | 0 .../src/runtime/queriesObserver.ts | 47 +- .../src/runtime/query.ts | 194 +- .../src/runtime/queryCache.ts | 142 +- .../src/runtime/queryClient.ts | 783 +++++ .../src/runtime/queryObserver.ts | 160 +- .../src/runtime/refetchInterval.ts | 13 +- .../src/runtime/select.ts | 5 +- .../src/runtime/serialScope.ts | 0 .../src/runtime/streamedQuery.ts | 72 +- .../src/runtime/types.ts | 788 +++++ .../src/runtime/utils.ts | 300 ++ .../src/suspense.ts | 7 +- .../src/suspenseQuery.ts | 87 + .../src/types.ts | 10 +- .../src/useBaseQuery.ts | 41 +- .../src/useInfiniteQuery.ts | 36 +- .../src/useIsFetching.ts | 11 +- .../src/useMutation.ts | 33 +- .../src/useMutationState.ts | 13 +- .../src/useObserverSnapshot.ts | 2 +- .../src/usePrefetchInfiniteQuery.tsx | 21 +- .../src/usePrefetchQuery.tsx | 15 +- .../src/useQueries.ts | 15 +- .../src/useQuery.ts | 128 +- .../src/useSuspenseInfiniteQuery.ts | 45 +- .../src/useSuspenseQueries.ts | 15 +- .../src/useSuspenseQuery.ts | 31 +- .../tests/compat-polling.ts | 0 .../tests/compat-projection.ts | 0 .../tests/compat-scope.ts | 0 .../tsconfig.json | 0 .../tsconfig.legacy.json | 0 .../tsconfig.prod.json | 0 .../tsdown.config.ts | 0 .../__tests__/infiniteQueryOptions.test-d.tsx | 9 +- .../react-query/src/__tests__/ssr.test.tsx | 3 +- .../src/__tests__/useInfiniteQuery.test-d.tsx | 3 +- .../src/__tests__/useInfiniteQuery.test.tsx | 3 +- .../src/__tests__/useMutation.test.tsx | 34 +- .../src/__tests__/useMutationState.test.tsx | 11 +- .../usePrefetchInfiniteQuery.test.tsx | 5 +- .../src/__tests__/useQueries.test.tsx | 5 +- .../src/__tests__/useQuery.test.tsx | 67 +- .../src/__tests__/useSuspenseQueries.test.tsx | 5 +- .../src/__tests__/useSuspenseQuery.test.tsx | 6 +- pnpm-lock.yaml | 84 +- scripts/port-query-client-tests.mjs | 180 ++ scripts/react-query-compat.config.ts | 4 +- scripts/test-react-query-compat.mjs | 97 +- 258 files changed, 7891 insertions(+), 24095 deletions(-) create mode 100644 .changeset/react-query-pluggable.md delete mode 100644 .changeset/react-query-standalone-adapters.md create mode 100644 integrations/react/bundle-size/src/pluggable-query.js create mode 100644 integrations/react/bundle-size/src/v6-query.js create mode 100644 packages/query-core/src/primitives.ts create mode 100644 packages/query-core/src/queryState.ts delete mode 100644 packages/query-core/src/runtimeBinding.ts delete mode 100644 packages/query-test-utils/src/cacheOperations.ts delete mode 100644 packages/query-types/README.md delete mode 100644 packages/query-types/oxlint.config.ts delete mode 100644 packages/query-types/package.json delete mode 100644 packages/query-types/src/binding.ts delete mode 100644 packages/query-types/src/bindings.ts delete mode 100644 packages/query-types/src/contracts.ts delete mode 100644 packages/query-types/src/environmentManager.ts delete mode 100644 packages/query-types/src/focusManager.ts delete mode 100644 packages/query-types/src/hydration.ts delete mode 100644 packages/query-types/src/index.ts delete mode 100644 packages/query-types/src/infiniteQueryObserver.ts delete mode 100644 packages/query-types/src/mutation.ts delete mode 100644 packages/query-types/src/mutationCache.ts delete mode 100644 packages/query-types/src/mutationObserver.ts delete mode 100644 packages/query-types/src/notifyManager.ts delete mode 100644 packages/query-types/src/onlineManager.ts delete mode 100644 packages/query-types/src/queriesObserver.ts delete mode 100644 packages/query-types/src/query.ts delete mode 100644 packages/query-types/src/queryCache.ts delete mode 100644 packages/query-types/src/queryClient.ts delete mode 100644 packages/query-types/src/queryObserver.ts delete mode 100644 packages/query-types/src/retryer.ts delete mode 100644 packages/query-types/src/streamedQuery.ts delete mode 100644 packages/query-types/src/symbols.ts delete mode 100644 packages/query-types/src/timeoutManager.ts delete mode 100644 packages/query-types/src/types.ts delete mode 100644 packages/query-types/src/utils.ts delete mode 100644 packages/query-types/tsconfig.json delete mode 100644 packages/query-types/tsconfig.legacy.json delete mode 100644 packages/query-types/tsdown.config.ts delete mode 100644 packages/react-query-no-core-pluggable/README.md delete mode 120000 packages/react-query-no-core-pluggable/root.oxlint.config.ts delete mode 120000 packages/react-query-no-core-pluggable/root.tsdown.config.js delete mode 100644 packages/react-query-no-core-pluggable/src/QueryErrorResetBoundary.tsx delete mode 100644 packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts delete mode 100644 packages/react-query-no-core-pluggable/src/mutationOptions.ts delete mode 100644 packages/react-query-no-core-pluggable/src/queryOptions.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/environmentManager.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/focusManager.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/notifyManager.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/onlineManager.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/queryCache.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/queryClient.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/removable.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/retryer.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/streamedQuery.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/subscribable.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/types.ts delete mode 100644 packages/react-query-no-core-pluggable/src/runtime/utils.ts delete mode 100644 packages/react-query-no-core-pluggable/src/suspense.ts delete mode 100644 packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts delete mode 100644 packages/react-query-no-core-pluggable/src/useIsFetching.ts delete mode 100644 packages/react-query-no-core-pluggable/src/useMutation.ts delete mode 100644 packages/react-query-no-core-pluggable/src/usePrefetchQuery.tsx delete mode 100644 packages/react-query-no-core-pluggable/src/useSuspenseInfiniteQuery.ts delete mode 100644 packages/react-query-no-core-pluggable/src/useSuspenseQuery.ts delete mode 100644 packages/react-query-no-core-pluggable/tests/compat-cacheOperations.ts delete mode 100644 packages/react-query-no-core-pluggable/tests/compat-infiniteQuery.ts delete mode 100644 packages/react-query-no-core-pluggable/tsconfig.prod.json delete mode 100644 packages/react-query-no-core/README.md delete mode 100644 packages/react-query-no-core/oxlint.config.ts delete mode 100644 packages/react-query-no-core/package.json delete mode 120000 packages/react-query-no-core/root.oxlint.config.ts delete mode 120000 packages/react-query-no-core/root.tsdown.config.js delete mode 100644 packages/react-query-no-core/src/HydrationBoundary.tsx delete mode 100644 packages/react-query-no-core/src/IsRestoringProvider.ts delete mode 100644 packages/react-query-no-core/src/QueryClientProvider.tsx delete mode 100644 packages/react-query-no-core/src/errorBoundaryUtils.ts delete mode 100644 packages/react-query-no-core/src/index.ts delete mode 100644 packages/react-query-no-core/src/runtime/environmentManager.ts delete mode 100644 packages/react-query-no-core/src/runtime/focusManager.ts delete mode 100644 packages/react-query-no-core/src/runtime/hydration.ts delete mode 100644 packages/react-query-no-core/src/runtime/identity.ts delete mode 100644 packages/react-query-no-core/src/runtime/infiniteQueryBehavior.ts delete mode 100644 packages/react-query-no-core/src/runtime/infiniteQueryObserver.ts delete mode 100644 packages/react-query-no-core/src/runtime/mutation.ts delete mode 100644 packages/react-query-no-core/src/runtime/mutationCache.ts delete mode 100644 packages/react-query-no-core/src/runtime/mutationObserver.ts delete mode 100644 packages/react-query-no-core/src/runtime/onlineManager.ts delete mode 100644 packages/react-query-no-core/src/runtime/queriesObserver.ts delete mode 100644 packages/react-query-no-core/src/runtime/query.ts delete mode 100644 packages/react-query-no-core/src/runtime/queryClient.ts delete mode 100644 packages/react-query-no-core/src/runtime/queryObserver.ts delete mode 100644 packages/react-query-no-core/src/runtime/removable.ts delete mode 100644 packages/react-query-no-core/src/runtime/retryer.ts delete mode 100644 packages/react-query-no-core/src/runtime/runtimeBinding.ts delete mode 100644 packages/react-query-no-core/src/runtime/subscribable.ts delete mode 100644 packages/react-query-no-core/src/runtime/timeoutManager.ts delete mode 100644 packages/react-query-no-core/src/runtime/types.ts delete mode 100644 packages/react-query-no-core/src/runtime/utils.ts delete mode 100644 packages/react-query-no-core/src/types.ts delete mode 100644 packages/react-query-no-core/src/useBaseQuery.ts delete mode 100644 packages/react-query-no-core/src/useMutationState.ts delete mode 100644 packages/react-query-no-core/src/useObserverSnapshot.ts delete mode 100644 packages/react-query-no-core/src/usePrefetchInfiniteQuery.tsx delete mode 100644 packages/react-query-no-core/src/useQueries.ts delete mode 100644 packages/react-query-no-core/src/useQuery.ts delete mode 100644 packages/react-query-no-core/src/useSuspenseQueries.ts delete mode 100644 packages/react-query-no-core/tsconfig.json delete mode 100644 packages/react-query-no-core/tsconfig.legacy.json delete mode 100644 packages/react-query-no-core/tsconfig.prod.json delete mode 100644 packages/react-query-no-core/tsdown.config.ts create mode 100644 packages/react-query-pluggable/README.md rename packages/{react-query-no-core-pluggable => react-query-pluggable}/oxlint.config.ts (100%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/package.json (92%) rename packages/{query-types => react-query-pluggable}/root.oxlint.config.ts (100%) rename packages/{query-types => react-query-pluggable}/root.tsdown.config.js (100%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/HydrationBoundary.tsx (93%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/IsRestoringProvider.ts (100%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/QueryClientProvider.tsx (88%) rename packages/{react-query-no-core => react-query-pluggable}/src/QueryErrorResetBoundary.tsx (99%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/__tests__/cacheOperations.test.ts (68%) rename packages/{react-query-no-core-pluggable/src/__tests__/infiniteQuery.test.ts => react-query-pluggable/src/__tests__/fetchInfiniteQuery.test.ts} (75%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/__tests__/getMutationCache.test.ts (77%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/__tests__/projection.test-d.ts (100%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/__tests__/projection.test.ts (87%) create mode 100644 packages/react-query-pluggable/src/__tests__/queryBuilders.test.ts create mode 100644 packages/react-query-pluggable/src/__tests__/queryModes.test-d.ts create mode 100644 packages/react-query-pluggable/src/__tests__/queryModes.test.tsx rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/__tests__/refetchInterval.test-d.ts (100%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/__tests__/refetchInterval.test.ts (98%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/__tests__/serialScope.test.ts (88%) create mode 100644 packages/react-query-pluggable/src/__tests__/sharedCore.test.ts rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/errorBoundaryUtils.ts (95%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/index.ts (85%) create mode 100644 packages/react-query-pluggable/src/infiniteQuery.ts rename packages/{react-query-no-core => react-query-pluggable}/src/infiniteQueryOptions.ts (96%) rename packages/{react-query-no-core => react-query-pluggable}/src/mutationOptions.ts (98%) rename packages/{react-query-no-core => react-query-pluggable}/src/queryOptions.ts (93%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/cacheOperations.ts (92%) rename packages/{react-query-no-core-pluggable/src/runtime/infiniteQuery.ts => react-query-pluggable/src/runtime/fetchInfiniteQuery.ts} (87%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/hydration.ts (82%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/identity.ts (100%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/infiniteQueryBehavior.ts (97%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/infiniteQueryObserver.ts (92%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/mutation.ts (95%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/mutationCache.ts (66%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/mutationObserver.ts (95%) rename packages/{react-query-no-core => react-query-pluggable}/src/runtime/notifyManager.ts (92%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/placeholderData.ts (93%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/projectResult.ts (100%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/projectionTypes.ts (100%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/queriesObserver.ts (93%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/query.ts (87%) rename packages/{react-query-no-core => react-query-pluggable}/src/runtime/queryCache.ts (65%) create mode 100644 packages/react-query-pluggable/src/runtime/queryClient.ts rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/queryObserver.ts (88%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/refetchInterval.ts (91%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/select.ts (97%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/runtime/serialScope.ts (100%) rename packages/{react-query-no-core => react-query-pluggable}/src/runtime/streamedQuery.ts (58%) create mode 100644 packages/react-query-pluggable/src/runtime/types.ts create mode 100644 packages/react-query-pluggable/src/runtime/utils.ts rename packages/{react-query-no-core => react-query-pluggable}/src/suspense.ts (96%) create mode 100644 packages/react-query-pluggable/src/suspenseQuery.ts rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/types.ts (98%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/useBaseQuery.ts (84%) rename packages/{react-query-no-core => react-query-pluggable}/src/useInfiniteQuery.ts (92%) rename packages/{react-query-no-core => react-query-pluggable}/src/useIsFetching.ts (84%) rename packages/{react-query-no-core => react-query-pluggable}/src/useMutation.ts (82%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/useMutationState.ts (94%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/useObserverSnapshot.ts (95%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/usePrefetchInfiniteQuery.tsx (82%) rename packages/{react-query-no-core => react-query-pluggable}/src/usePrefetchQuery.tsx (77%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/useQueries.ts (97%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/useQuery.ts (71%) rename packages/{react-query-no-core => react-query-pluggable}/src/useSuspenseInfiniteQuery.ts (82%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/src/useSuspenseQueries.ts (98%) rename packages/{react-query-no-core => react-query-pluggable}/src/useSuspenseQuery.ts (86%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/tests/compat-polling.ts (100%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/tests/compat-projection.ts (100%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/tests/compat-scope.ts (100%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/tsconfig.json (100%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/tsconfig.legacy.json (100%) rename packages/{query-types => react-query-pluggable}/tsconfig.prod.json (100%) rename packages/{react-query-no-core-pluggable => react-query-pluggable}/tsdown.config.ts (100%) create mode 100644 scripts/port-query-client-tests.mjs diff --git a/.changeset/react-query-pluggable.md b/.changeset/react-query-pluggable.md new file mode 100644 index 00000000000..7d2e8ea0f4c --- /dev/null +++ b/.changeset/react-query-pluggable.md @@ -0,0 +1,8 @@ +--- +'@tanstack/query-core': minor +'@tanstack/react-query-pluggable': minor +--- + +Add an experimental ESM-only React Query adapter backed by `@tanstack/query-core`. Apps can import polling, selection, placeholder data, and serial mutation queues where they use them. Use `useQuery(query(options))` for a regular read and `useQuery(suspenseQuery(options))` to suspend on the same cache. Compose `infiniteQuery(options)` with the same hook and Suspense policy to read pages. For imperative fetching, import `fetchInfiniteQuery(client, options)`. Client operations are named functions with the client as their first argument, including `getQueryData(client, key)` and `invalidateQueries(client, filters)`. + +Mutation hooks acquire a cache on first use. For direct access, import `getMutationCache` and call `getMutationCache(client)`. Clients configured with a custom cache return that instance. diff --git a/.changeset/react-query-standalone-adapters.md b/.changeset/react-query-standalone-adapters.md deleted file mode 100644 index b9d8ba194f4..00000000000 --- a/.changeset/react-query-standalone-adapters.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -'@tanstack/query-types': minor -'@tanstack/query-core': patch -'@tanstack/react-query-no-core': minor -'@tanstack/react-query-no-core-pluggable': minor ---- - -Add experimental ESM React Query adapters with an integrated query runtime. The pluggable adapter lets apps import polling, selection, placeholder data, and scoped mutation queues at the point of use. It also exports imperative infinite queries and bulk cache operations as standalone functions. Both adapters and `@tanstack/query-core` share TypeScript definitions through `@tanstack/query-types`. - -In the pluggable adapter, mutation hooks acquire the cache on demand so query-only apps can omit its implementation. For direct cache access, use the named export `getMutationCache(client)`. Clients created with a custom mutation cache keep using that instance. diff --git a/.github/workflows/react-query-bundle-size.yml b/.github/workflows/react-query-bundle-size.yml index 7da63fd5f73..f0d3c8a43f8 100644 --- a/.github/workflows/react-query-bundle-size.yml +++ b/.github/workflows/react-query-bundle-size.yml @@ -6,9 +6,8 @@ on: - '.github/workflows/react-query-bundle-size.yml' - 'integrations/react/bundle-size/**' - 'packages/query-core/**' - - 'packages/query-types/**' - 'packages/react-query/**' - - 'packages/react-query-no-core*/**' + - 'packages/react-query-pluggable/**' - 'scripts/getTsdownConfig.js' - '.nvmrc' - 'package.json' diff --git a/integrations/react/bundle-size/README.md b/integrations/react/bundle-size/README.md index 8814861df96..3f70a12fa98 100644 --- a/integrations/react/bundle-size/README.md +++ b/integrations/react/bundle-size/README.md @@ -1,19 +1,21 @@ # 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. 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 all four regular and suspense query hooks. 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 and standalone adapters accept a numeric interval. The pluggable adapter imports its interval scheduler through the `refetchInterval` option helper. +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(query(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 `query(options)`, `infiniteQuery(options)`, `suspenseQuery(options)` or `suspenseQuery(infiniteQuery(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 two alternatives, the app code, the bundler and both React packages come from the PR head. The report records both commit IDs. +CI builds the original adapter and its dependencies from the PR's base commit. The experimental `@tanstack/react-query-pluggable` adapter, its `@tanstack/query-core` dependency, the app code, the bundler and both React packages 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 v6 baseline in bytes and the signed change in bytes and percent for each alternative. Expand either detail table to see absolute sizes and changes for all three packages. +The opening table compares the gzipped Query runtime for each workload. It shows both package sizes in bytes and the signed change in bytes and percent relative to v6. Expand either detail table to see the absolute minified, gzip and Brotli sizes. -1. **Query runtime used by the app.** Vite builds the same HTML and React entry points with React, React DOM and their subpaths external. Rolldown groups the adapter’s retained modules into one ESM chunk, including `@tanstack/query-core` for the original adapter. The app and its workload-specific helpers stay in a separate entry chunk. The benchmark directly measures the minified Query chunk, including its ESM import and export bindings. Its gzip and Brotli sizes describe compressing this chunk on its own. Percentages use the original adapter’s isolated chunk for that workload and encoding. +1. **Query runtime used by the app.** Vite builds the same HTML and React entry points with React, React DOM and their subpaths external. Rolldown groups the adapter’s retained modules into one ESM chunk, including all retained `@tanstack/query-core` modules from the same checkout as that adapter. The app and its workload-specific helpers stay in a separate entry chunk. The benchmark directly measures the minified Query chunk, including its ESM import and export bindings. Its gzip and Brotli sizes describe compressing this chunk on its own. Percentages use the original adapter’s isolated chunk for that workload and encoding. 2. **Whole production app.** Vite builds the deployable application with its ordinary chunk layout, including React, React DOM, the app and the adapter. Each percentage uses the original adapter’s full app for that workload and encoding. Compressing these complete chunks accounts for compression shared between the app and its dependencies. Both tables show the emitted JS byte length, gzip at level 9 and Brotli at quality 11. The benchmark compresses each emitted JS chunk independently and sums the lengths. HTML, source maps and analysis reports are excluded. -For each app, the benchmark verifies that the isolated Query chunk contains the same retained Query module IDs and exports as the whole production app and imports only React peer entry points. 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. Additional checks cover polling, infinite queries, selection, placeholder data, serial queues and bulk cache operations. Individual public export probes check that selection, placeholder data and serial queues can be removed independently. The React hydration boundary only restores queries. The universal `hydrate` also restores serial queues from saved mutations. +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 `fetchQuery`, `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 whole production app and imports only React peer entry points. Feature checks cover modules in both the pluggable adapter and its shared core. 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 read-only app excludes the Suspense builder and policy. The polling app retains both. Pagination and polling retain the infinite query builder and observer. All four hook-driven apps exclude the imperative `fetchInfiniteQuery` implementation. Additional checks cover polling, infinite queries, selection, placeholder data, serial queues and bulk cache operations. Individual public export probes check that selection, placeholder data and serial queues can be removed independently. 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. @@ -37,7 +39,7 @@ QUERY_BASE_CHECKOUT="$PWD/../query-bundle-base" pnpm --filter @tanstack/query-in Read the summary and detailed tables in `integrations/react/bundle-size/dist/report.md`. Serve a directory under `dist//` to try the built app. -Run the twelve production app scenarios in Chromium after measuring: +Run the eight production app scenarios in Chromium after measuring: ```sh cd integrations/react/bundle-size diff --git a/integrations/react/bundle-size/browser/apps.test.js b/integrations/react/bundle-size/browser/apps.test.js index f17aa83f987..996a869c909 100644 --- a/integrations/react/bundle-size/browser/apps.test.js +++ b/integrations/react/bundle-size/browser/apps.test.js @@ -1,16 +1,18 @@ import { afterEach, describe, expect, it } from 'vitest' +import { commands } from 'vitest/browser' -const adapters = [ - 'react-query', - 'react-query-no-core', - 'react-query-no-core-pluggable', -] +const adapters = ['react-query', 'react-query-pluggable'] -async function openApp(scenario, adapter) { +function mountApp(scenario, 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, adapter) { + const frame = mountApp(scenario, adapter) await expect .poll(() => frame.contentDocument?.querySelector('li')?.textContent) .toContain('Middlemarch') @@ -88,7 +90,29 @@ describe.each(adapters)('@tanstack/%s', (adapter) => { }) it('periodically refetches regular, infinite and suspense queries', async () => { - const app = await openApp('polling', adapter) + 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 + 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) diff --git a/integrations/react/bundle-size/measure.mjs b/integrations/react/bundle-size/measure.mjs index 655b83515d4..e4197cc79e3 100644 --- a/integrations/react/bundle-size/measure.mjs +++ b/integrations/react/bundle-size/measure.mjs @@ -14,8 +14,8 @@ const baseCheckout = process.env.QUERY_BASE_CHECKOUT const basePackage = baseCheckout && path.join(baseCheckout, 'packages/react-query') const baseline = '@tanstack/react-query' -const pluggable = '@tanstack/react-query-no-core-pluggable' -const packages = [baseline, '@tanstack/react-query-no-core', pluggable] +const pluggable = '@tanstack/react-query-pluggable' +const packages = [baseline, pluggable] const workloads = [ { screen: 'query', title: 'Read-only list' }, { screen: 'paginated', title: 'Paginated bookmarks' }, @@ -29,11 +29,26 @@ const workloads = [ }, ] -const excludedFromStandaloneApps = [ - /\/(?:packages|node_modules\/@tanstack)\/(?:query-core|(?:angular|lit|preact|solid|svelte|vue)-query[^/]*)\//, +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 runtimeOwners(directory, packageName) { + return [packageName.split('/')[1], 'query-core'].map( + (name) => + normalizePath(path.join(directory, 'packages', name, 'build')) + '/', + ) +} + +const pluggableOwners = runtimeOwners(checkout, pluggable) +function rendersFeature(id, feature) { + return ( + id.endsWith(`/${feature}.js`) && + pluggableOwners.some((dir) => id.startsWith(dir)) + ) +} + async function buildApp(packageName, screen, belongsToAdapter) { const outDir = path.join(root, 'dist', screen, packageName.split('/')[1]) const result = await build({ @@ -61,6 +76,11 @@ async function buildApp(packageName, screen, belongsToAdapter) { resolve: { dedupe: ['react', 'react-dom'], alias: { + '#query-hooks': path.join( + root, + 'src', + packageName === pluggable ? 'pluggable-query.js' : 'v6-query.js', + ), '#polling-option': path.join( root, 'src', @@ -116,6 +136,40 @@ function renderedModules(chunks) { ) } +// Each bulk operation may retain the other public operations it calls. +const bulkOperations = { + getQueriesData: [], + setQueriesData: ['setQueryData'], + removeQueries: [], + resetQueries: ['refetchQueries'], + cancelQueries: [], + invalidateQueries: ['refetchQueries'], + refetchQueries: [], +} + +function checkClientOperations(modules, workload, required) { + const operations = new Set( + modules.flatMap(([id, module]) => { + if (rendersFeature(id, 'cacheOperations')) return module.renderedExports + if (rendersFeature(id, 'queryClient')) { + return module.renderedExports.filter( + (name) => name === 'fetchQuery' || name === 'setQueryData', + ) + } + return [] + }), + ) + const allowed = [required, ...(bulkOperations[required] ?? [])] + 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}`) +} + function checkApp(chunks, packageName, screen) { const modules = renderedModules(chunks).map(([id]) => id) if ( @@ -127,18 +181,9 @@ function checkApp(chunks, packageName, screen) { `Missing built @tanstack/react-query from base checkout ${basePackage}`, ) } - if ( - modules.some((id) => - /\/(?:packages|node_modules\/@tanstack)\/query-types\//.test(id), - ) - ) { - throw new Error( - `${packageName} shipped runtime code from @tanstack/query-types`, - ) - } - if (packageName !== baseline) { + if (packageName === pluggable) { const foreignRuntime = modules.find((id) => - excludedFromStandaloneApps.some((pattern) => pattern.test(id)), + otherFrameworks.some((pattern) => pattern.test(id)), ) if (foreignRuntime) { throw new Error( @@ -154,8 +199,6 @@ function checkApp(chunks, packageName, screen) { `${packageName} included an internal runtime barrel in the app`, ) } - } - if (packageName === pluggable) { const usesMutations = screen === 'paginated' || screen === 'options' const features = { queryClient: true, @@ -165,7 +208,12 @@ function checkApp(chunks, packageName, screen) { mutationCache: usesMutations, mutation: usesMutations, mutationObserver: usesMutations, + suspenseQuery: screen === 'polling', + suspense: screen === 'polling', refetchInterval: screen === 'polling', + fetchInfiniteQuery: false, + infiniteQuery: screen === 'paginated' || screen === 'polling', + infiniteQueryObserver: screen === 'paginated' || screen === 'polling', infiniteQueryBehavior: screen === 'paginated' || screen === 'polling', select: screen === 'options', placeholderData: screen === 'options', @@ -173,15 +221,18 @@ function checkApp(chunks, packageName, screen) { cacheOperations: screen === 'options', } for (const [feature, expected] of Object.entries(features)) { - const included = modules.some((id) => - id.endsWith(`/runtime/${feature}.js`), - ) + const included = modules.some((id) => rendersFeature(id, feature)) if (included !== expected) { throw new Error( `Unexpected ${feature} implementation in ${screen}: included=${included}`, ) } } + checkClientOperations( + renderedModules(chunks), + screen, + screen === 'options' ? 'invalidateQueries' : undefined, + ) } } @@ -214,13 +265,7 @@ async function measure(packageName, screen) { // Query chunk. Keep the original app entrypoint so it drives tree-shaking. const source = packageName === baseline && baseCheckout ? baseCheckout : checkout - const owners = ( - packageName === baseline - ? ['react-query', 'query-core'] - : [packageName.split('/')[1]] - ).map( - (name) => normalizePath(path.join(source, 'packages', name, 'build')) + '/', - ) + const owners = runtimeOwners(source, packageName) const belongsToAdapter = (id) => owners.some((dir) => id.startsWith(dir)) const attributed = await buildApp(packageName, screen, belongsToAdapter) const library = attributed.filter((chunk) => chunk.name === 'query-runtime') @@ -256,20 +301,67 @@ async function measure(packageName, screen) { const largestModules = actual .sort(([, a], [, b]) => b.renderedLength - a.renderedLength) .slice(0, 5) - .map(([id]) => id.slice(owners.find((dir) => id.startsWith(dir)).length)) + .map(([id]) => + normalizePath(path.relative(path.join(source, 'packages'), id)), + ) return { library: sizesOf(library), app: sizesOf(app), largestModules } } // A combined app cannot tell whether each projection pulls in its sibling, // or whether rendering a boundary pulls in paused-mutation restoration. -async function checkStandaloneExports() { +async function checkPluggableExports() { + const { + QueryClient, + query, + queryOptions, + mutationOptions, + infiniteQueryOptions, + QueriesObserver, + notifyManager, + } = await import(pluggable) + 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`, + ) + } + if ( + typeof queryOptions !== 'function' || + queryOptions !== query || + queryOptions !== mutationOptions || + queryOptions !== infiniteQueryOptions + ) { + throw new Error( + `${pluggable} must use the same identity function for query and the three option factories`, + ) + } + const expected = { + query: [], + suspenseQuery: ['suspenseQuery', 'suspense'], + infiniteQuery: [ + 'infiniteQuery', + 'infiniteQueryObserver', + 'infiniteQueryBehavior', + ], + fetchInfiniteQuery: ['fetchInfiniteQuery', 'infiniteQueryBehavior'], QueryClient: [], + fetchQuery: [], + setQueryData: [], getMutationCache: ['mutationCache'], select: ['select', 'projectResult'], placeholderData: ['placeholderData', 'projectResult'], serialScope: ['serialScope'], - invalidateQueries: ['cacheOperations'], + ...Object.fromEntries( + Object.keys(bulkOperations).map((name) => [name, ['cacheOperations']]), + ), HydrationBoundary: ['infiniteQueryBehavior'], dehydrate: [], hydrate: [ @@ -314,30 +406,26 @@ async function checkStandaloneExports() { ) .filter(([, module]) => module.renderedLength > 0) for (const feature of features) { - const included = modules.some(([id]) => - id.endsWith(`/runtime/${feature}.js`), - ) + const included = modules.some(([id]) => rendersFeature(id, feature)) if (included !== required.includes(feature)) { throw new Error( `Importing ${name} unexpectedly ${included ? 'included' : 'excluded'} ${feature}`, ) } } - if (name === 'invalidateQueries') { - const [, operations] = modules.find(([id]) => - id.endsWith('/runtime/cacheOperations.js'), + if ( + ['QueryClient', 'fetchQuery', 'setQueryData'].includes(name) || + Object.hasOwn(bulkOperations, name) + ) { + checkClientOperations( + modules, + name, + name === 'QueryClient' ? undefined : name, ) - if ( - operations.renderedExports.some( - (item) => !['invalidateQueries', 'refetchQueries'].includes(item), - ) - ) { - throw new Error('Invalidation included unrelated bulk cache operations') - } } } } -await checkStandaloneExports() +await checkPluggableExports() const integer = new Intl.NumberFormat('en-US') function formatChange(bytes, baselineBytes) { @@ -353,34 +441,6 @@ function formatSize(bytes, baselineBytes, isBaseline) { return `${size}
${formatChange(bytes, baselineBytes)}` } -// Inspect the published ESM entry points as a consumer would. -for (const name of packages.filter((name) => name !== baseline)) { - const { - queryOptions, - mutationOptions, - infiniteQueryOptions, - QueriesObserver, - notifyManager, - } = await import(name) - if ( - 'getQueries' in QueriesObserver.prototype || - 'setBatchNotifyFunction' in notifyManager - ) { - throw new Error( - `${name} exposed another adapter's observer or batch notification API`, - ) - } - if ( - typeof queryOptions !== 'function' || - queryOptions !== mutationOptions || - queryOptions !== infiniteQueryOptions - ) { - throw new Error( - `${name} must export one runtime function for all three option factories`, - ) - } -} - function revision(directory) { return execFileSync('git', ['-C', directory, 'rev-parse', 'HEAD'], { encoding: 'utf8', @@ -396,7 +456,7 @@ const lines = [ '', '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 | v6 | no-core change | no-core-pluggable change |', + '| Workload | React Query v6 | React Query Pluggable | Change vs v6 |', '| --- | ---: | ---: | ---: |', ] const results = [] @@ -406,18 +466,16 @@ for (const { screen, title } of workloads) { rows.push({ name, ...(await measure(name, screen)) }) } results.push({ screen, title, rows }) - const [v6Gzip, standaloneGzip, pluggableGzip] = rows.map( - (row) => row.library.gzip, - ) + const [v6Gzip, pluggableGzip] = rows.map((row) => row.library.gzip) lines.push( - `| ${title} | ${integer.format(v6Gzip)} B | ${formatChange(standaloneGzip, v6Gzip)} | ${formatChange(pluggableGzip, v6Gzip)} |`, + `| ${title} | ${integer.format(v6Gzip)} B | ${integer.format(pluggableGzip)} B | ${formatChange(pluggableGzip, v6Gzip)} |`, ) } lines.push( '', - 'The pluggable read-only list retains the query client, cache, query and observer. Its production build drops the mutation cache and observer, polling scheduler, infinite-query behavior, selection, placeholder data, serial scopes and bulk cache operations. Both bookmark apps retain the mutation cache and observer.', + 'The pluggable read-only list retains the query client, cache, query and observer. Its production build drops the Suspense builder and policy, mutation cache and observer, polling scheduler, infinite-query behavior, selection, placeholder data, serial scopes and bulk cache operations. Both bookmark apps retain the mutation cache and observer.', '', - `Baseline adapter at \`${base}\` (${baseCheckout ? 'base checkout' : 'current checkout'}). Alternatives and fixture at \`${head}\`.`, + `Baseline adapter and core at \`${base}\` (${baseCheckout ? 'base checkout' : 'current checkout'}). Pluggable adapter, core and fixture at \`${head}\`.`, ) function addTable(key, heading, description) { lines.push( @@ -453,7 +511,7 @@ function addTable(key, heading, description) { addTable( 'library', 'Query runtime sizes · minified JS, gzip and Brotli', - 'The app entry drives tree-shaking. This build externalizes React and React DOM and groups retained Query modules into one ESM chunk. The baseline includes query-core. Each cell measures the isolated chunk directly.', + 'The app entry drives tree-shaking. This build externalizes React and React DOM and groups the adapter and its retained query-core modules into one ESM chunk for each package. Each cell measures the isolated chunk directly.', ) addTable( 'app', diff --git a/integrations/react/bundle-size/package.json b/integrations/react/bundle-size/package.json index 33d7569f8f0..f1fa4a16bac 100644 --- a/integrations/react/bundle-size/package.json +++ b/integrations/react/bundle-size/package.json @@ -10,8 +10,7 @@ }, "dependencies": { "@tanstack/react-query": "workspace:*", - "@tanstack/react-query-no-core": "workspace:*", - "@tanstack/react-query-no-core-pluggable": "workspace:*", + "@tanstack/react-query-pluggable": "workspace:*", "react": "catalog:", "react-dom": "catalog:" }, diff --git a/integrations/react/bundle-size/src/paginated.jsx b/integrations/react/bundle-size/src/paginated.jsx index 599a6569e6d..d545d72eee3 100644 --- a/integrations/react/bundle-size/src/paginated.jsx +++ b/integrations/react/bundle-size/src/paginated.jsx @@ -3,14 +3,14 @@ import { queryOptions, infiniteQueryOptions, mutationOptions, - useInfiniteQuery, useMutation, useQuery, } from '#adapter' +import { useBookPages } from '#query-hooks' import { fetchBooks } from './books.js' export function ReadingList() { - const books = useInfiniteQuery( + const books = useBookPages( infiniteQueryOptions({ queryKey: ['books'], queryFn: ({ pageParam, signal }) => fetchBooks(pageParam, signal), diff --git a/integrations/react/bundle-size/src/pluggable-query.js b/integrations/react/bundle-size/src/pluggable-query.js new file mode 100644 index 00000000000..ab789642baa --- /dev/null +++ b/integrations/react/bundle-size/src/pluggable-query.js @@ -0,0 +1,17 @@ +import { infiniteQuery, query, suspenseQuery, useQuery } from '#adapter' + +export function useBookQuery(options) { + return useQuery(query(options)) +} + +export function useSuspenseBookQuery(options) { + return useQuery(suspenseQuery(options)) +} + +export function useBookPages(options) { + return useQuery(infiniteQuery(options)) +} + +export function useSuspenseBookPages(options) { + return useQuery(suspenseQuery(infiniteQuery(options))) +} diff --git a/integrations/react/bundle-size/src/polling.jsx b/integrations/react/bundle-size/src/polling.jsx index 1ad84dd63dd..05fdae7e6bf 100644 --- a/integrations/react/bundle-size/src/polling.jsx +++ b/integrations/react/bundle-size/src/polling.jsx @@ -1,11 +1,11 @@ import * as React from 'react' -import { - useQuery, - useInfiniteQuery, - useSuspenseQuery, - useSuspenseInfiniteQuery, -} from '#adapter' import { interval } from '#polling-option' +import { + useBookPages, + useBookQuery, + useSuspenseBookPages, + useSuspenseBookQuery, +} from '#query-hooks' import { fetchBooks } from './books.js' function options(name) { @@ -22,44 +22,55 @@ const pagination = { getNextPageParam: (page) => page.next, } -function Updates() { - const query = useQuery(options('query')) - const infinite = useInfiniteQuery({ ...options('infinite'), ...pagination }) - const suspense = useSuspenseQuery(options('suspense')) - const suspenseInfinite = useSuspenseInfiniteQuery({ +function BookRow({ label, result, page }) { + 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, }) - const rows = [ - ['Query', query, query.data], - ['Infinite query', infinite, infinite.data?.pages[0]], - ['Suspense query', suspense, suspense.data], - [ - 'Suspense infinite query', - suspenseInfinite, - suspenseInfinite.data.pages[0], - ], - ] return ( -
      - {rows.map(([name, result, page]) => ( -
    • - {name}: {page?.titles.join(', ')}{' '} - {result.dataUpdatedAt > 0 && ( - - )} -
    • - ))} -
    + ) } export function ReadingList() { + const query = useBookQuery(options('query')) + const infinite = useBookPages({ ...options('infinite'), ...pagination }) return ( - Loading books…

    }> - -
    +
      + + + Loading suspense query…}> + + + Loading suspense pages…}> + + +
    ) } diff --git a/integrations/react/bundle-size/src/query.jsx b/integrations/react/bundle-size/src/query.jsx index 18f4324e063..51ae3ccbe3e 100644 --- a/integrations/react/bundle-size/src/query.jsx +++ b/integrations/react/bundle-size/src/query.jsx @@ -1,9 +1,9 @@ import * as React from 'react' -import { useQuery } from '#adapter' +import { useBookQuery } from '#query-hooks' import { fetchBooks } from './books.js' export function ReadingList() { - const books = useQuery({ + const books = useBookQuery({ queryKey: ['books', 1], queryFn: ({ signal }) => fetchBooks(1, signal), }) diff --git a/integrations/react/bundle-size/src/v6-query.js b/integrations/react/bundle-size/src/v6-query.js new file mode 100644 index 00000000000..17ebd6494d6 --- /dev/null +++ b/integrations/react/bundle-size/src/v6-query.js @@ -0,0 +1,6 @@ +export { + useInfiniteQuery as useBookPages, + useQuery as useBookQuery, + useSuspenseInfiniteQuery as useSuspenseBookPages, + useSuspenseQuery as useSuspenseBookQuery, +} from '#adapter' diff --git a/integrations/react/bundle-size/vitest.browser.config.js b/integrations/react/bundle-size/vitest.browser.config.js index 51dd9c93e83..07f125f521f 100644 --- a/integrations/react/bundle-size/vitest.browser.config.js +++ b/integrations/react/bundle-size/vitest.browser.config.js @@ -1,10 +1,27 @@ import { playwright } from '@vitest/browser-playwright' import { defineConfig } from 'vitest/config' +const pendingBooks = new Map() +const booksUrl = (adapter) => `/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 = pendingBooks.get(request.url) + if (gate) { + gate.requested.resolve() + gate.response.promise.then(() => next(), next) + } else next() + }) + }, + }, + ], test: { include: ['browser/*.test.js'], browser: { @@ -12,6 +29,22 @@ export default defineConfig({ headless: true, provider: playwright(), instances: [{ browser: 'chromium' }], + commands: { + holdPollingBooks(_, adapter) { + pendingBooks.set(booksUrl(adapter), { + requested: Promise.withResolvers(), + response: Promise.withResolvers(), + }) + }, + waitForPollingRequest(_, adapter) { + return pendingBooks.get(booksUrl(adapter)).requested.promise + }, + releasePollingBooks(_, adapter) { + const url = booksUrl(adapter) + pendingBooks.get(url).response.resolve() + pendingBooks.delete(url) + }, + }, }, }, }) diff --git a/integrations/react/nodenext/README.md b/integrations/react/nodenext/README.md index e3fc41c8384..8cc19458b58 100644 --- a/integrations/react/nodenext/README.md +++ b/integrations/react/nodenext/README.md @@ -6,7 +6,7 @@ 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 the shared `Register` and passes an adapter-tagged query key to all three clients to check inference across the published ESM entry points. +- `src/sharedTypes.ts` augments `@tanstack/query-core`’s `Register` and passes a pluggable-tagged query key to the core and pluggable clients to check inference across the published ESM entry points. - 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/package.json b/integrations/react/nodenext/package.json index f1c00328c42..2b1b1eea17a 100644 --- a/integrations/react/nodenext/package.json +++ b/integrations/react/nodenext/package.json @@ -10,10 +10,8 @@ }, "dependencies": { "@tanstack/query-core": "workspace:*", - "@tanstack/query-types": "workspace:*", "@tanstack/react-query": "workspace:*", - "@tanstack/react-query-no-core": "workspace:*", - "@tanstack/react-query-no-core-pluggable": "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 index c26755fec1d..6794c49c352 100644 --- a/integrations/react/nodenext/src/sharedTypes.ts +++ b/integrations/react/nodenext/src/sharedTypes.ts @@ -1,14 +1,15 @@ import { QueryClient as CoreClient } from '@tanstack/query-core' -import { QueryClient, queryOptions } from '@tanstack/react-query-no-core' -import { QueryClient as PluggableClient } from '@tanstack/react-query-no-core-pluggable' +import { + QueryClient, + getQueryData, + queryOptions, +} from '@tanstack/react-query-pluggable' import type { QueryMeta as CoreMeta } from '@tanstack/query-core' -import type { QueryMeta } from '@tanstack/query-types' -import type { QueryMeta as DirectMeta } from '@tanstack/react-query-no-core' -import type { QueryMeta as PluggableMeta } from '@tanstack/react-query-no-core-pluggable' +import type { QueryMeta as PluggableMeta } from '@tanstack/react-query-pluggable' type BookMeta = { shelf: string } -declare module '@tanstack/query-types' { +declare module '@tanstack/query-core' { interface Register { queryMeta: BookMeta } @@ -17,22 +18,18 @@ declare module '@tanstack/query-types' { type Assert = Matches type Same = [A, B] extends [B, A] ? true : false -// Consumers can augment the shared Register once for each runtime. export type SharedMetadata = [ - Assert>, Assert>, - Assert>, Assert>, ] const book = queryOptions({ queryKey: ['book'], queryFn: () => 'Dune' }) -// The unique symbols on a tagged key carry its data type across packages. +// Both clients infer the data type from the adapter's tagged key. export const fromCore: string | undefined = new CoreClient().getQueryData( book.queryKey, ) -export const fromDirect: string | undefined = new QueryClient().getQueryData( +export const fromPluggable: string | undefined = getQueryData( + new QueryClient(), book.queryKey, ) -export const fromPluggable: string | undefined = - new PluggableClient().getQueryData(book.queryKey) diff --git a/knip.config.ts b/knip.config.ts index 5271e7e9cbe..26a6fada2d3 100644 --- a/knip.config.ts +++ b/knip.config.ts @@ -1,8 +1,7 @@ import reactQueryDevtools from './packages/react-query-devtools/package.json' import reactQueryNextExperimental from './packages/react-query-next-experimental/package.json' -import reactQueryPluggable from './packages/react-query-no-core-pluggable/package.json' -import reactQueryNoCore from './packages/react-query-no-core/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' @@ -16,13 +15,6 @@ const optionalPeerDependencies = (pkg: { .filter((dependency) => dependency in pkg.peerDependencies) .map((dependency) => `${dependency}!`) -// The compatibility runner creates test entry points for the adapter and runtime -// modules imported by the upstream suites. -const compatibilityEntries = [ - 'src/suspense.ts', - 'src/runtime/{query,notifyManager,retryer,timeoutManager,utils}.ts', -] - export default { ignore: [ 'scripts/*.{j,t}s', @@ -50,12 +42,13 @@ export default { 'packages/react-query': { ignoreDependencies: optionalPeerDependencies(reactQuery), }, - 'packages/react-query-no-core': { - entry: compatibilityEntries, - ignoreDependencies: optionalPeerDependencies(reactQueryNoCore), - }, - 'packages/react-query-no-core-pluggable': { - entry: [...compatibilityEntries, 'tests/compat-*.ts'], + 'packages/react-query-pluggable': { + // These internal imports are exercised by the upstream compatibility suites. + entry: [ + 'src/suspense.ts', + 'src/runtime/{query,notifyManager,utils}.ts', + 'tests/compat-*.ts', + ], ignoreDependencies: optionalPeerDependencies(reactQueryPluggable), }, 'packages/react-query-devtools': { diff --git a/nx.json b/nx.json index 0db40918265..2733e7562d5 100644 --- a/nx.json +++ b/nx.json @@ -27,6 +27,7 @@ ], "reactQueryCompatibility": [ "{workspaceRoot}/scripts/test-react-query-compat.mjs", + "{workspaceRoot}/scripts/port-query-client-tests.mjs", "{workspaceRoot}/scripts/port-query-projection-tests.mjs", "{workspaceRoot}/scripts/react-query-compat.config.ts", "{workspaceRoot}/packages/query-core/src/__tests__/**/*", diff --git a/packages/query-core/package.json b/packages/query-core/package.json index 8868c00ab15..8ca2510d094 100644 --- a/packages/query-core/package.json +++ b/packages/query-core/package.json @@ -40,6 +40,11 @@ "types": "./build/index.d.ts", "default": "./build/index.js" }, + "./primitives": { + "@tanstack/custom-condition": "./src/primitives.ts", + "types": "./build/primitives.d.ts", + "default": "./build/primitives.js" + }, "./package.json": "./package.json" }, "sideEffects": false, @@ -48,9 +53,6 @@ "src", "!src/__tests__" ], - "dependencies": { - "@tanstack/query-types": "workspace:*" - }, "devDependencies": { "@tanstack/query-test-utils": "workspace:*", "typescript": "catalog:" diff --git a/packages/query-core/src/__tests__/cacheGc.test.tsx b/packages/query-core/src/__tests__/cacheGc.test.tsx index a31f7a5e6d9..67bc7a458e8 100644 --- a/packages/query-core/src/__tests__/cacheGc.test.tsx +++ b/packages/query-core/src/__tests__/cacheGc.test.tsx @@ -1,4 +1,3 @@ -import { getMutationCache } from '@tanstack/query-test-utils/cacheOperations' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MutationObserver, QueryClient, QueryObserver } from '..' import { Mutation } from '../mutation' @@ -22,7 +21,7 @@ describe('garbage collection after cache removal', () => { }) it('clears an existing mutation timer on clear', () => { - const cache = getMutationCache(client) + const cache = client.getMutationCache() Mutation.build(client, {}) expect(vi.getTimerCount()).toBe(1) @@ -33,7 +32,7 @@ describe('garbage collection after cache removal', () => { }) it('clears an existing mutation timer on remove', () => { - const cache = getMutationCache(client) + const cache = client.getMutationCache() const mutation = Mutation.build(client, {}) expect(vi.getTimerCount()).toBe(1) diff --git a/packages/query-core/src/__tests__/hydration.test.tsx b/packages/query-core/src/__tests__/hydration.test.tsx index 8c54bfee381..c60ce08910f 100644 --- a/packages/query-core/src/__tests__/hydration.test.tsx +++ b/packages/query-core/src/__tests__/hydration.test.tsx @@ -1,5 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { serialScope } from '@tanstack/query-test-utils/scope' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { dehydrate, hydrate } from '../hydration' @@ -790,7 +789,7 @@ describe('dehydration and rehydration', () => { }) .catch(noop) - cacheOperations(queryClient).refetchQueries({ queryKey: key }) + queryClient.refetchQueries({ queryKey: key }) const dehydrated = dehydrate(queryClient) resolvePromise('string') @@ -1535,7 +1534,7 @@ describe('dehydration and rehydration', () => { const queryCache = new QueryCache() const queryClient = new QueryClient({ queryCache }) - const prefetchPromise = cacheOperations(queryClient) + const prefetchPromise = queryClient .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => @@ -1576,7 +1575,7 @@ describe('dehydration and rehydration', () => { const queryCache = new QueryCache() const queryClient = new QueryClient({ queryCache }) - const prefetchPromise = cacheOperations(queryClient) + const prefetchPromise = queryClient .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => @@ -1598,7 +1597,7 @@ describe('dehydration and rehydration', () => { const hydrationClient = new QueryClient({ queryCache: hydrationCache }) hydrate(hydrationClient, dehydrated) - const resultPromise = cacheOperations(hydrationClient).infiniteQuery({ + const resultPromise = hydrationClient.infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => sleep(10).then(() => ({ @@ -1620,7 +1619,7 @@ describe('dehydration and rehydration', () => { const key = createKey() const serverClient = new QueryClient({ queryCache: new QueryCache() }) - const prefetchPromise = cacheOperations(serverClient) + const prefetchPromise = serverClient .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => @@ -1657,7 +1656,7 @@ describe('dehydration and rehydration', () => { const key = createKey() const serverClient = new QueryClient({ queryCache: new QueryCache() }) - const prefetchPromise = cacheOperations(serverClient) + const prefetchPromise = serverClient .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => @@ -1686,7 +1685,7 @@ describe('dehydration and rehydration', () => { expect(beforeRefetch?.pages).toHaveLength(1) expect(beforeRefetch?.pageParams).toHaveLength(1) - const resultPromise = cacheOperations(clientClient).infiniteQuery({ + const resultPromise = clientClient.infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => sleep(10).then(() => ({ @@ -1710,7 +1709,7 @@ describe('dehydration and rehydration', () => { const key = createKey() const serverClient = new QueryClient({ queryCache: new QueryCache() }) - const prefetchPromise = cacheOperations(serverClient) + const prefetchPromise = serverClient .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => @@ -1743,7 +1742,7 @@ describe('dehydration and rehydration', () => { const key = createKey() const serverClient = new QueryClient({ queryCache: new QueryCache() }) - const prefetchPromise = cacheOperations(serverClient) + const prefetchPromise = serverClient .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => @@ -1772,7 +1771,7 @@ describe('dehydration and rehydration', () => { }>(key) expect(beforeRefetch?.pages).toHaveLength(2) - const resultPromise = cacheOperations(clientClient) + const resultPromise = clientClient .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => diff --git a/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx b/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx index 55252d7eecc..d00e81ae014 100644 --- a/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx +++ b/packages/query-core/src/__tests__/infiniteQueryBehavior.test.tsx @@ -1,5 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { CancelledError, @@ -489,13 +488,13 @@ describe('InfiniteQueryBehavior', () => { return String(pageParam) } - await cacheOperations(queryClient).infiniteQuery({ + await queryClient.infiniteQuery({ queryKey: key, queryFn, initialPageParam: null, getNextPageParam: () => undefined, }) - await cacheOperations(queryClient).infiniteQuery({ + await queryClient.infiniteQuery({ queryKey: key, queryFn, initialPageParam: 'replacement', diff --git a/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx b/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx index 4d80341e594..2b1def6188b 100644 --- a/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx +++ b/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx @@ -1,5 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { selectOption } from '@tanstack/query-test-utils/projection' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { InfiniteQueryObserver, QueryClient } from '..' @@ -262,7 +261,7 @@ describe('InfiniteQueryObserver', () => { const unsubscribe = observer.subscribe(() => {}) await vi.advanceTimersByTimeAsync(10) - cacheOperations(queryClient).removeQueries({ queryKey: key }) + queryClient.removeQueries({ queryKey: key }) queryClient.getQueryCache().build(queryClient, { queryKey: key, queryFn: () => sleep(10).then(() => 'recreated-page'), diff --git a/packages/query-core/src/__tests__/mutation.test.tsx b/packages/query-core/src/__tests__/mutation.test.tsx index 54e249ccb75..aab835a7da0 100644 --- a/packages/query-core/src/__tests__/mutation.test.tsx +++ b/packages/query-core/src/__tests__/mutation.test.tsx @@ -1,5 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { getMutationCache } from '@tanstack/query-test-utils/cacheOperations' import { serialScope } from '@tanstack/query-test-utils/scope' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MutationCache, QueryClient, focusManager, onlineManager } from '..' @@ -348,7 +347,7 @@ describe('mutation', () => { }) it('should not add an existing observer with addObserver', () => { - const mutationCache = getMutationCache(queryClient) + const mutationCache = queryClient.getMutationCache() const observer = new MutationObserver(queryClient, {}) const currentMutation = Mutation.build(queryClient, {}) @@ -499,7 +498,7 @@ describe('mutation', () => { await vi.advanceTimersByTimeAsync(10) expect(count).toBe(1) expect( - getMutationCache(queryClient).find({ mutationKey: key })?.state + queryClient.getMutationCache().find({ mutationKey: key })?.state .isPaused, ).toBe(true) @@ -537,7 +536,7 @@ describe('mutation', () => { 'vars1', ) expect( - getMutationCache(queryClient).find({ mutationKey: key1 })?.state, + queryClient.getMutationCache().find({ mutationKey: key1 })?.state, ).toMatchObject({ status: 'pending', isPaused: false, @@ -558,7 +557,7 @@ describe('mutation', () => { 'vars2', ) expect( - getMutationCache(queryClient).find({ mutationKey: key2 })?.state, + queryClient.getMutationCache().find({ mutationKey: key2 })?.state, ).toMatchObject({ status: 'pending', isPaused: true, @@ -621,7 +620,7 @@ describe('mutation', () => { 'finish-B', ]) expect( - getMutationCache(queryClient).find({ mutationKey: key2 })?.state, + queryClient.getMutationCache().find({ mutationKey: key2 })?.state, ).toMatchObject({ status: 'success', isPaused: false, @@ -676,7 +675,7 @@ describe('mutation', () => { await vi.advanceTimersByTimeAsync(10) expect(results).toStrictEqual(['start-A', 'finish-A']) expect( - getMutationCache(queryClient).find({ mutationKey: key2 })?.state, + queryClient.getMutationCache().find({ mutationKey: key2 })?.state, ).toMatchObject({ status: 'pending', isPaused: true, @@ -735,7 +734,7 @@ describe('mutation', () => { await vi.advanceTimersByTimeAsync(0) expect(results).toStrictEqual(['start-A']) expect( - getMutationCache(queryClient).find({ mutationKey: key2 })?.state + queryClient.getMutationCache().find({ mutationKey: key2 })?.state .isPaused, ).toBe(true) @@ -755,7 +754,7 @@ describe('mutation', () => { it('should keep a queued mutation paused when its onMutate resolves before its turn', async () => { const isPaused: Array = [] - const unsubscribe = getMutationCache(queryClient).subscribe((event) => { + const unsubscribe = queryClient.getMutationCache().subscribe((event) => { if ( event.type === 'updated' && event.mutation.state.variables === 'vars2' @@ -807,7 +806,7 @@ describe('mutation', () => { }, 'vars', ) - const mutation = getMutationCache(queryClient).find({ mutationKey: key })! + const mutation = queryClient.getMutationCache().find({ mutationKey: key })! expect(mutation.state).toMatchObject({ status: 'pending', isPaused: true, @@ -1498,9 +1497,9 @@ describe('mutation', () => { observer1.mutate() await vi.advanceTimersByTimeAsync(10) - expect(getMutationCache(queryClient).getAll()).toHaveLength(1) + expect(queryClient.getMutationCache().getAll()).toHaveLength(1) - const mutation = getMutationCache(queryClient).getAll()[0]! + const mutation = queryClient.getMutationCache().getAll()[0]! const observer2 = new MutationObserver(queryClient, { gcTime: 10, mutationFn: () => sleep(10).then(() => 'data'), @@ -1509,7 +1508,7 @@ describe('mutation', () => { unsubscribe1() await vi.advanceTimersByTimeAsync(10) - expect(getMutationCache(queryClient).getAll()).toHaveLength(1) + expect(queryClient.getMutationCache().getAll()).toHaveLength(1) }) it('should release the retryer once a mutation settles', async () => { @@ -1520,7 +1519,7 @@ describe('mutation', () => { observer.mutate('data') await vi.advanceTimersByTimeAsync(10) - const mutation = getMutationCache(queryClient).getAll()[0]! + const mutation = queryClient.getMutationCache().getAll()[0]! expect(mutation.state.status).toBe('success') // continue() is the only reader of the retryer outside execute(): while a @@ -1537,7 +1536,7 @@ describe('mutation', () => { observer.mutate(undefined).catch(() => undefined) await vi.advanceTimersByTimeAsync(10) - const mutation = getMutationCache(queryClient).getAll()[0]! + const mutation = queryClient.getMutationCache().getAll()[0]! expect(mutation.state.status).toBe('error') // a retained retryer would hand back its rejected promise here @@ -1553,7 +1552,7 @@ describe('mutation', () => { observer.mutate() await vi.advanceTimersByTimeAsync(10) - const mutation = getMutationCache(queryClient).getAll()[0]! + const mutation = queryClient.getMutationCache().getAll()[0]! expect(mutation.state.status).toBe('success') expect(mutationFn).toHaveBeenCalledTimes(1) diff --git a/packages/query-core/src/__tests__/mutationCache.test-d.tsx b/packages/query-core/src/__tests__/mutationCache.test-d.tsx index df77f70c071..9be20684105 100644 --- a/packages/query-core/src/__tests__/mutationCache.test-d.tsx +++ b/packages/query-core/src/__tests__/mutationCache.test-d.tsx @@ -1,4 +1,3 @@ -import { getMutationCache } from '@tanstack/query-test-utils/cacheOperations' import { afterEach, beforeEach, describe, expectTypeOf, it } from 'vitest' import { MutationCache, QueryClient } from '..' import { Mutation } from '../mutation' @@ -23,7 +22,7 @@ describe('mutationCache', () => { beforeEach(() => { queryClient = new QueryClient() queryClient.mount() - mutationCache = getMutationCache(queryClient) + mutationCache = queryClient.getMutationCache() }) afterEach(() => { diff --git a/packages/query-core/src/__tests__/mutationCache.test.tsx b/packages/query-core/src/__tests__/mutationCache.test.tsx index 52761dae305..3e422fa3e61 100644 --- a/packages/query-core/src/__tests__/mutationCache.test.tsx +++ b/packages/query-core/src/__tests__/mutationCache.test.tsx @@ -1,5 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { getMutationCache } from '@tanstack/query-test-utils/cacheOperations' import { serialScope } from '@tanstack/query-test-utils/scope' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MutationCache, MutationObserver, QueryClient } from '..' @@ -498,17 +497,17 @@ describe('mutationCache', () => { mutationFn: (input: number) => sleep(10).then(() => input), }) const unsubscribe = observer.subscribe(() => undefined) - expect(getMutationCache(queryClient).getAll()).toHaveLength(0) + expect(queryClient.getMutationCache().getAll()).toHaveLength(0) observer.mutate(1) - expect(getMutationCache(queryClient).getAll()).toHaveLength(1) + expect(queryClient.getMutationCache().getAll()).toHaveLength(1) await vi.advanceTimersByTimeAsync(10) - expect(getMutationCache(queryClient).getAll()).toHaveLength(1) + expect(queryClient.getMutationCache().getAll()).toHaveLength(1) unsubscribe() - expect(getMutationCache(queryClient).getAll()).toHaveLength(1) + expect(queryClient.getMutationCache().getAll()).toHaveLength(1) await vi.advanceTimersByTimeAsync(10) - expect(getMutationCache(queryClient).getAll()).toHaveLength(0) + expect(queryClient.getMutationCache().getAll()).toHaveLength(0) }) it('should be garbage collected later when unsubscribed and mutation is pending', async () => { @@ -532,13 +531,13 @@ describe('mutationCache', () => { observer.mutate(1) unsubscribe() - expect(getMutationCache(queryClient).getAll()).toHaveLength(1) + expect(queryClient.getMutationCache().getAll()).toHaveLength(1) await vi.advanceTimersByTimeAsync(10) // unsubscribe should not remove even though gcTime has elapsed b/c mutation is still pending - expect(getMutationCache(queryClient).getAll()).toHaveLength(1) + expect(queryClient.getMutationCache().getAll()).toHaveLength(1) await vi.advanceTimersByTimeAsync(10) // should be removed after an additional gcTime wait - expect(getMutationCache(queryClient).getAll()).toHaveLength(0) + expect(queryClient.getMutationCache().getAll()).toHaveLength(0) expect(onSuccess).toHaveBeenCalledTimes(1) }) @@ -564,7 +563,7 @@ describe('mutationCache', () => { unsubscribe() await vi.advanceTimersByTimeAsync(10) - expect(getMutationCache(queryClient).getAll()).toHaveLength(0) + expect(queryClient.getMutationCache().getAll()).toHaveLength(0) expect(onSuccess).toHaveBeenCalledTimes(1) }) }) diff --git a/packages/query-core/src/__tests__/mutationObserver.test.tsx b/packages/query-core/src/__tests__/mutationObserver.test.tsx index 48f327bba42..86037973441 100644 --- a/packages/query-core/src/__tests__/mutationObserver.test.tsx +++ b/packages/query-core/src/__tests__/mutationObserver.test.tsx @@ -1,5 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { getMutationCache } from '@tanstack/query-test-utils/cacheOperations' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { MutationObserver, QueryClient } from '..' import type { MutationFunctionContext, MutationObserverResult } from '..' @@ -62,11 +61,11 @@ describe('mutationObserver', () => { mutation.mutate('input') await vi.advanceTimersByTimeAsync(5) - expect(getMutationCache(queryClient).findAll()).toHaveLength(1) + expect(queryClient.getMutationCache().findAll()).toHaveLength(1) unsubscribe() await vi.advanceTimersByTimeAsync(10) - expect(getMutationCache(queryClient).findAll()).toHaveLength(0) + expect(queryClient.getMutationCache().findAll()).toHaveLength(0) }) it('should reattach the observer to the in-flight mutation when resubscribing', async () => { @@ -126,11 +125,11 @@ describe('mutationObserver', () => { mutation.mutate('input') await vi.advanceTimersByTimeAsync(5) - expect(getMutationCache(queryClient).findAll()).toHaveLength(1) + expect(queryClient.getMutationCache().findAll()).toHaveLength(1) mutation.reset() await vi.advanceTimersByTimeAsync(10) - expect(getMutationCache(queryClient).findAll()).toHaveLength(0) + expect(queryClient.getMutationCache().findAll()).toHaveLength(0) unsubscribe() }) @@ -183,7 +182,7 @@ describe('mutationObserver', () => { mutationObserver.mutate('input') await vi.advanceTimersByTimeAsync(5) expect( - getMutationCache(queryClient).find({ mutationKey: [...key, '1'] }), + queryClient.getMutationCache().find({ mutationKey: [...key, '1'] }), ).toMatchObject({ options: { mutationKey: [...key, '1'] }, state: { @@ -196,7 +195,7 @@ describe('mutationObserver', () => { mutationKey: [...key, '2'], }) expect( - getMutationCache(queryClient).find({ mutationKey: [...key, '1'] }), + queryClient.getMutationCache().find({ mutationKey: [...key, '1'] }), ).toMatchObject({ options: { mutationKey: [...key, '1'] }, state: { @@ -223,7 +222,7 @@ describe('mutationObserver', () => { mutationObserver.mutate('input') await vi.advanceTimersByTimeAsync(5) - expect(getMutationCache(queryClient).find({})).toMatchObject({ + expect(queryClient.getMutationCache().find({})).toMatchObject({ options: { meta: { a: 1 } }, state: { status: 'success', @@ -234,7 +233,7 @@ describe('mutationObserver', () => { mutationObserver.setOptions({ meta: { a: 2 }, }) - expect(getMutationCache(queryClient).find({})).toMatchObject({ + expect(queryClient.getMutationCache().find({})).toMatchObject({ options: { meta: { a: 1 } }, state: { status: 'success', @@ -270,7 +269,7 @@ describe('mutationObserver', () => { mutationObserver.mutate('input') await vi.advanceTimersByTimeAsync(5) - const mutations = getMutationCache(queryClient).findAll() + const mutations = queryClient.getMutationCache().findAll() expect(mutations[0]).toMatchObject({ options: { meta: { a: 1 } }, state: { @@ -305,7 +304,7 @@ describe('mutationObserver', () => { mutationObserver.mutate('input').catch(() => undefined) await vi.advanceTimersByTimeAsync(5) - expect(getMutationCache(queryClient).find({})).toMatchObject({ + expect(queryClient.getMutationCache().find({})).toMatchObject({ options: { meta: { a: 1 } }, state: { status: 'error', @@ -315,7 +314,7 @@ describe('mutationObserver', () => { mutationObserver.setOptions({ meta: { a: 2 }, }) - expect(getMutationCache(queryClient).find({})).toMatchObject({ + expect(queryClient.getMutationCache().find({})).toMatchObject({ options: { meta: { a: 1 } }, state: { status: 'error', @@ -340,7 +339,7 @@ describe('mutationObserver', () => { mutationObserver.mutate('input') await vi.advanceTimersByTimeAsync(5) - expect(getMutationCache(queryClient).find({})).toMatchObject({ + expect(queryClient.getMutationCache().find({})).toMatchObject({ options: { meta: { a: 1 } }, state: { status: 'pending', @@ -350,7 +349,7 @@ describe('mutationObserver', () => { mutationObserver.setOptions({ meta: { a: 2 }, }) - expect(getMutationCache(queryClient).find({})).toMatchObject({ + expect(queryClient.getMutationCache().find({})).toMatchObject({ options: { meta: { a: 2 } }, state: { status: 'pending', @@ -599,7 +598,7 @@ describe('mutationObserver', () => { mutationFn: (text: string) => Promise.resolve(text), }) - const notifySpy = vi.spyOn(getMutationCache(queryClient), 'notify') + const notifySpy = vi.spyOn(queryClient.getMutationCache(), 'notify') const unsubscribe = mutationObserver.subscribe(() => undefined) diff --git a/packages/query-core/src/__tests__/queriesObserver.test.tsx b/packages/query-core/src/__tests__/queriesObserver.test.tsx index 5d148cf5af4..93f047aaa55 100644 --- a/packages/query-core/src/__tests__/queriesObserver.test.tsx +++ b/packages/query-core/src/__tests__/queriesObserver.test.tsx @@ -1,7 +1,6 @@ import { setFlagsFromString } from 'node:v8' import { runInNewContext } from 'node:vm' import { createKey, sleep } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { placeholderOption, selectOption, @@ -756,7 +755,7 @@ describe('queriesObserver', () => { const unsubscribe = observer.subscribe(() => undefined) - void cacheOperations(queryClient).resetQueries({ queryKey: key }) + void queryClient.resetQueries({ queryKey: key }) expect(combine).toHaveBeenCalledTimes(1) unsubscribe() @@ -802,7 +801,7 @@ describe('queriesObserver', () => { { combine }, ) - void cacheOperations(queryClient).resetQueries({ queryKey: key }) + void queryClient.resetQueries({ queryKey: key }) expect(combine).toHaveBeenCalledTimes(1) unsubscribe() @@ -973,7 +972,7 @@ describe('queriesObserver', () => { expect.objectContaining({ status: 'success', data: 'data' }), ]) - void cacheOperations(queryClient).refetchQueries({ queryKey: key }) + void queryClient.refetchQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(10) expect(listener).toHaveBeenCalledTimes(2) expect(listener).toHaveBeenLastCalledWith([ @@ -984,7 +983,7 @@ describe('queriesObserver', () => { }), ]) - void cacheOperations(queryClient).refetchQueries({ queryKey: key }) + void queryClient.refetchQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(0) expect(observer.getCurrentResult()[0]).toMatchObject({ status: 'error', @@ -1345,7 +1344,7 @@ describe('queriesObserver', () => { ) observer.setQueries([{ queryKey: createKey(), queryFn: () => 2 }]) - cacheOperations(queryClient).removeQueries({ queryKey: oldKey }) + queryClient.removeQueries({ queryKey: oldKey }) // A WeakRef keeps its target alive until the current job ends. await vi.advanceTimersByTimeAsync(0) gc() diff --git a/packages/query-core/src/__tests__/query.test.tsx b/packages/query-core/src/__tests__/query.test.tsx index e2286a13c7a..c19d15da5d7 100644 --- a/packages/query-core/src/__tests__/query.test.tsx +++ b/packages/query-core/src/__tests__/query.test.tsx @@ -3,7 +3,6 @@ import { mockVisibilityState, sleep, } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { CancelledError, @@ -53,7 +52,7 @@ describe('query', () => { }) initial.catch(noop) await vi.advanceTimersByTimeAsync(0) - await cacheOperations(queryClient).cancelQueries({ queryKey: key }) + await queryClient.cancelQueries({ queryKey: key }) focusManager.setFocused(false) try { const replacement = queryClient.query({ @@ -81,7 +80,7 @@ describe('query', () => { }) initial.catch(noop) await vi.advanceTimersByTimeAsync(0) - await cacheOperations(queryClient).cancelQueries({ queryKey: key }) + await queryClient.cancelQueries({ queryKey: key }) focusManager.setFocused(false) try { await vi.advanceTimersByTimeAsync(250) @@ -1152,9 +1151,9 @@ describe('query', () => { mockedData = [1, 2] // update "server" state in the background - void cacheOperations(queryClient).invalidateQueries({ queryKey: key }) + void queryClient.invalidateQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(5) - void cacheOperations(queryClient).invalidateQueries({ queryKey: key }) + void queryClient.invalidateQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(5) unsubscribe() // unsubscribe to simulate unmount await vi.advanceTimersByTimeAsync(5) @@ -1197,10 +1196,7 @@ describe('query', () => { x = 1 // cancel ongoing re-fetches - void cacheOperations(queryClient).refetchQueries( - { queryKey: key }, - { cancelRefetch: true }, - ) + void queryClient.refetchQueries({ queryKey: key }, { cancelRefetch: true }) // The promise should not reject await vi.advanceTimersByTimeAsync(100) @@ -1231,7 +1227,7 @@ describe('query', () => { ]) await vi.advanceTimersByTimeAsync(10) - void cacheOperations(queryClient).invalidateQueries({ queryKey: key }) + void queryClient.invalidateQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(100) await expect(results).resolves.toStrictEqual([ @@ -1263,9 +1259,9 @@ describe('query', () => { ]) await vi.advanceTimersByTimeAsync(10) - void cacheOperations(queryClient).invalidateQueries({ queryKey: key }) + void queryClient.invalidateQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(10) - void cacheOperations(queryClient).invalidateQueries({ queryKey: key }) + void queryClient.invalidateQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(100) await expect(results).resolves.toStrictEqual([ diff --git a/packages/query-core/src/__tests__/queryCache.test.tsx b/packages/query-core/src/__tests__/queryCache.test.tsx index 440662e04a6..06a44f75d00 100644 --- a/packages/query-core/src/__tests__/queryCache.test.tsx +++ b/packages/query-core/src/__tests__/queryCache.test.tsx @@ -1,5 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueryCache, QueryClient, QueryObserver, hashKey, noop } from '..' import type { DefaultError, Query, QueryCacheNotifyEvent } from '..' @@ -249,7 +248,7 @@ describe('queryCache', () => { }) .catch(noop) await vi.advanceTimersByTimeAsync(100) - cacheOperations(queryClient).invalidateQueries({ queryKey: key2 }) + queryClient.invalidateQueries({ queryKey: key2 }) const query1 = queryCache.find({ queryKey: key1 })! const query2 = queryCache.find({ queryKey: key2 })! const query3 = queryCache.find({ queryKey: [{ a: 'a', b: 'b' }] })! diff --git a/packages/query-core/src/__tests__/queryClient.test-d.tsx b/packages/query-core/src/__tests__/queryClient.test-d.tsx index 83160484381..3b65b7d9f9c 100644 --- a/packages/query-core/src/__tests__/queryClient.test-d.tsx +++ b/packages/query-core/src/__tests__/queryClient.test-d.tsx @@ -1,7 +1,3 @@ -import { - cacheOperations, - getMutationCache, -} from '@tanstack/query-test-utils/cacheOperations' import { selectOption } from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { QueryClient } from '../queryClient' @@ -85,8 +81,6 @@ const untypedMutationKey = untypedMutationOptions.mutationKey! type SuccessCallback = () => unknown -type CacheOperations = ReturnType> - describe('queryClient', () => { describe('getQueryData', () => { it('should be typed if key is tagged', () => { @@ -291,13 +285,12 @@ describe('queryClient', () => { it('should resolve QueryKey and unknown for a tagged filter', () => { const queryClient = new QueryClient() // TODO: types here are wrong and coming up undefined - const operations = cacheOperations(queryClient) - const data = operations.setQueriesData(typedQueryFilters, { foo: '' }) + const data = queryClient.setQueriesData(typedQueryFilters, { foo: '' }) expectTypeOf(data).toEqualTypeOf>() expectTypeOf< Parameters< - typeof operations.setQueriesData + typeof queryClient.setQueriesData >[1] >().toEqualTypeOf>() }) @@ -305,13 +298,12 @@ describe('queryClient', () => { it('should resolve QueryKey and unknown for an untyped filter', () => { const queryClient = new QueryClient() // TODO: types here are wrong and coming up undefined - const operations = cacheOperations(queryClient) - const data = operations.setQueriesData(untypedQueryFilters, { foo: '' }) + const data = queryClient.setQueriesData(untypedQueryFilters, { foo: '' }) expectTypeOf(data).toEqualTypeOf>() expectTypeOf< Parameters< - typeof operations.setQueriesData + typeof queryClient.setQueriesData >[1] >().toEqualTypeOf>() }) @@ -413,7 +405,7 @@ describe('queryClient', () => { describe('infiniteQuery', () => { it('should allow passing select option', () => { - const result = cacheOperations(new QueryClient()).infiniteQuery({ + const result = new QueryClient().infiniteQuery({ queryKey: ['key'], queryFn: () => Promise.resolve({ count: 1 }), initialPageParam: 1, @@ -427,7 +419,7 @@ describe('queryClient', () => { }) it('should allow passing pages', async () => { - const result = await cacheOperations(new QueryClient()).infiniteQuery({ + const result = await new QueryClient().infiniteQuery({ queryKey: ['key'], queryFn: () => Promise.resolve({ count: 1 }), getNextPageParam: () => 1, @@ -453,11 +445,7 @@ describe('queryClient', () => { }) it('should allow passing getNextPageParam without pages', () => { - assertType< - Parameters< - ReturnType>['infiniteQuery'] - > - >([ + assertType>([ { queryKey: ['key'], queryFn: () => Promise.resolve({ count: 1 }), @@ -468,11 +456,7 @@ describe('queryClient', () => { }) it('should require getNextPageParam even without pages', () => { - assertType< - Parameters< - ReturnType>['infiniteQuery'] - > - >([ + assertType>([ // @ts-expect-error Property 'getNextPageParam' is missing { queryKey: ['key'], @@ -484,7 +468,7 @@ describe('queryClient', () => { it('should default its page param to unknown', () => { const queryClient = new QueryClient() - const result = cacheOperations(queryClient).infiniteQuery({ + const result = queryClient.infiniteQuery({ queryKey: ['key'], queryFn: () => Promise.resolve('string'), initialPageParam: 1, @@ -495,18 +479,15 @@ describe('queryClient', () => { Promise> >() - const { infiniteQuery } = cacheOperations(queryClient) type PageParam = Parameters< - typeof infiniteQuery + typeof queryClient.infiniteQuery >[0]['initialPageParam'] expectTypeOf().toEqualTypeOf() }) it('should resolve with InfiniteData of the data type', async () => { const queryClient = new QueryClient() - const data = await cacheOperations(queryClient).infiniteQuery( - typedInfiniteQueryOptions, - ) + const data = await queryClient.infiniteQuery(typedInfiniteQueryOptions) expectTypeOf(data).toEqualTypeOf< InfiniteData | undefined @@ -515,9 +496,7 @@ describe('queryClient', () => { it('should resolve with InfiniteData of unknown when untyped', async () => { const queryClient = new QueryClient() - const data = await cacheOperations(queryClient).infiniteQuery( - untypedInfiniteQueryOptions, - ) + const data = await queryClient.infiniteQuery(untypedInfiniteQueryOptions) expectTypeOf(data).toEqualTypeOf< InfiniteData | undefined @@ -527,18 +506,18 @@ describe('queryClient', () => { describe('invalidateQueries', () => { it('should reject a non-array queryKey', () => { - assertType>([]) - assertType>([ + assertType>([]) + assertType>([ { queryKey: ['1'] }, ]) - assertType>([ + assertType>([ // @ts-expect-error { queryKey: '1' }, ]) }) it('should reject an object queryKey (#8684)', () => { - assertType>([ + assertType>([ // @ts-expect-error key is not an array { queryKey: { foo: true } }, ]) @@ -547,7 +526,7 @@ describe('queryClient', () => { it('should type the predicate if the key is tagged', () => { const key = ['key'] as DataTag, number> const queryClient = new QueryClient() - cacheOperations(queryClient).invalidateQueries({ + queryClient.invalidateQueries({ queryKey: key, predicate: (query) => { expectTypeOf(query.state.data).toEqualTypeOf() @@ -560,14 +539,14 @@ describe('queryClient', () => { it('should return a promise of void', () => { const queryClient = new QueryClient() - expectTypeOf( - cacheOperations(queryClient).invalidateQueries(), - ).toEqualTypeOf>() + expectTypeOf(queryClient.invalidateQueries()).toEqualTypeOf< + Promise + >() }) it('should accept a refetchType that QueryFilters does not have', () => { type RefetchType = NonNullable< - Parameters[0] + Parameters[0] >['refetchType'] expectTypeOf().toEqualTypeOf< 'all' | 'active' | 'inactive' | 'none' | undefined @@ -576,7 +555,7 @@ describe('queryClient', () => { it('should accept the refetch options it inherits as its second argument', () => { expectTypeOf< - NonNullable[1]> + NonNullable[1]> >().toEqualTypeOf<{ throwOnError?: boolean cancelRefetch?: boolean @@ -588,7 +567,7 @@ describe('queryClient', () => { it('should type the predicate if the key is tagged', () => { const key = ['key'] as DataTag, number> const queryClient = new QueryClient() - cacheOperations(queryClient).cancelQueries({ + queryClient.cancelQueries({ queryKey: key, predicate: (query) => { expectTypeOf(query.state.data).toEqualTypeOf() @@ -599,15 +578,13 @@ describe('queryClient', () => { }) it('should accept being called without filters', () => { - assertType>([]) + assertType>([]) }) it('should return a promise of void', () => { const queryClient = new QueryClient() - expectTypeOf(cacheOperations(queryClient).cancelQueries()).toEqualTypeOf< - Promise - >() + expectTypeOf(queryClient.cancelQueries()).toEqualTypeOf>() }) }) @@ -615,7 +592,7 @@ describe('queryClient', () => { it('should type the predicate if the key is tagged', () => { const key = ['key'] as DataTag, number> const queryClient = new QueryClient() - cacheOperations(queryClient).removeQueries({ + queryClient.removeQueries({ queryKey: key, predicate: (query) => { expectTypeOf(query.state.data).toEqualTypeOf() @@ -626,15 +603,13 @@ describe('queryClient', () => { }) it('should accept being called without filters', () => { - assertType>([]) + assertType>([]) }) it('should return void', () => { const queryClient = new QueryClient() - expectTypeOf( - cacheOperations(queryClient).removeQueries(), - ).toEqualTypeOf() + expectTypeOf(queryClient.removeQueries()).toEqualTypeOf() }) }) @@ -642,7 +617,7 @@ describe('queryClient', () => { it('should type the predicate if the key is tagged', () => { const key = ['key'] as DataTag, number> const queryClient = new QueryClient() - cacheOperations(queryClient).refetchQueries({ + queryClient.refetchQueries({ queryKey: key, predicate: (query) => { expectTypeOf(query.state.data).toEqualTypeOf() @@ -653,15 +628,13 @@ describe('queryClient', () => { }) it('should accept being called without filters', () => { - assertType>([]) + assertType>([]) }) it('should return a promise of void', () => { const queryClient = new QueryClient() - expectTypeOf(cacheOperations(queryClient).refetchQueries()).toEqualTypeOf< - Promise - >() + expectTypeOf(queryClient.refetchQueries()).toEqualTypeOf>() }) }) @@ -669,7 +642,7 @@ describe('queryClient', () => { it('should type the predicate if the key is tagged', () => { const key = ['key'] as DataTag, number> const queryClient = new QueryClient() - cacheOperations(queryClient).resetQueries({ + queryClient.resetQueries({ queryKey: key, predicate: (query) => { expectTypeOf(query.state.data).toEqualTypeOf() @@ -680,20 +653,18 @@ describe('queryClient', () => { }) it('should accept being called without filters', () => { - assertType>([]) + assertType>([]) }) it('should return a promise of void', () => { const queryClient = new QueryClient() - expectTypeOf(cacheOperations(queryClient).resetQueries()).toEqualTypeOf< - Promise - >() + expectTypeOf(queryClient.resetQueries()).toEqualTypeOf>() }) it('should accept the refetch options it inherits as its second argument', () => { expectTypeOf< - NonNullable[1]> + NonNullable[1]> >().toEqualTypeOf<{ throwOnError?: boolean cancelRefetch?: boolean @@ -830,16 +801,16 @@ describe('queryClient', () => { const queryClient = new QueryClient() expectTypeOf( - cacheOperations(queryClient).getQueriesData({ queryKey: ['key'] }), + queryClient.getQueriesData({ queryKey: ['key'] }), ).toEqualTypeOf>() // @ts-expect-error filters are required - cacheOperations(queryClient).getQueriesData() + queryClient.getQueriesData() }) it('should infer the passed generic as the tuple data', () => { const queryClient = new QueryClient() - const data = cacheOperations(queryClient).getQueriesData({ + const data = queryClient.getQueriesData({ queryKey: ['key'], }) @@ -848,8 +819,7 @@ describe('queryClient', () => { it('should widen the tuple to the filter key and unknown when tagged', () => { const queryClient = new QueryClient() - const data = - cacheOperations(queryClient).getQueriesData(typedQueryFilters) + const data = queryClient.getQueriesData(typedQueryFilters) expectTypeOf(data).toEqualTypeOf< Array<[ReadonlyArray, unknown]> @@ -858,8 +828,7 @@ describe('queryClient', () => { it('should resolve QueryKey and unknown when untyped', () => { const queryClient = new QueryClient() - const data = - cacheOperations(queryClient).getQueriesData(untypedQueryFilters) + const data = queryClient.getQueriesData(untypedQueryFilters) expectTypeOf(data).toEqualTypeOf>() }) @@ -914,7 +883,9 @@ describe('queryClient', () => { it('should return the MutationCache', () => { const queryClient = new QueryClient() - expectTypeOf(getMutationCache(queryClient)).toEqualTypeOf() + expectTypeOf( + queryClient.getMutationCache(), + ).toEqualTypeOf() }) }) diff --git a/packages/query-core/src/__tests__/queryClient.test.tsx b/packages/query-core/src/__tests__/queryClient.test.tsx index b39ebaa9ffb..540813a81c7 100644 --- a/packages/query-core/src/__tests__/queryClient.test.tsx +++ b/packages/query-core/src/__tests__/queryClient.test.tsx @@ -1,8 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { - cacheOperations, - getMutationCache, -} from '@tanstack/query-test-utils/cacheOperations' import { selectOption } from '@tanstack/query-test-utils/projection' import { serialScope } from '@tanstack/query-test-utils/scope' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -429,7 +425,7 @@ describe('queryClient', () => { queryClient.setQueryData(['key', 1], 1) queryClient.setQueryData(['key', 2], 2) - const result = cacheOperations(queryClient).setQueriesData( + const result = queryClient.setQueriesData( { queryKey: ['key'] }, (old) => (old ? old + 5 : undefined), ) @@ -447,7 +443,7 @@ describe('queryClient', () => { queryClient.setQueryData(['key', 2], 2) const query1 = queryCache.find({ queryKey: ['key', 1] })! - const result = cacheOperations(queryClient).setQueriesData( + const result = queryClient.setQueriesData( { predicate: (query) => query === query1 }, (old) => old! + 5, ) @@ -458,7 +454,7 @@ describe('queryClient', () => { }) it('should not update non existing queries', () => { - const result = cacheOperations(queryClient).setQueriesData( + const result = queryClient.setQueriesData( { queryKey: ['key'] }, 'data', ) @@ -640,7 +636,7 @@ describe('queryClient', () => { pageParams: [0], }) await expect( - cacheOperations(queryClient).infiniteQuery({ + queryClient.infiniteQuery({ queryKey: [key, 'id'], queryFn, staleTime: 'static', @@ -658,7 +654,7 @@ describe('queryClient', () => { ) await expect( - cacheOperations(queryClient).infiniteQuery({ + queryClient.infiniteQuery({ queryKey: [key, 'id'], queryFn, staleTime: 'static', @@ -677,9 +673,7 @@ describe('queryClient', () => { queryClient.setQueryData([key1, 1], 1) queryClient.setQueryData([key1, 2], 2) queryClient.setQueryData([key2, 2], 2) - expect( - cacheOperations(queryClient).getQueriesData({ queryKey: [key1] }), - ).toStrictEqual([ + expect(queryClient.getQueriesData({ queryKey: [key1] })).toStrictEqual([ [[key1, 1], 1], [[key1, 2], 2], ]) @@ -687,9 +681,7 @@ describe('queryClient', () => { it('should return empty array if queries are not found', () => { const key = createKey() - expect( - cacheOperations(queryClient).getQueriesData({ queryKey: key }), - ).toStrictEqual([]) + expect(queryClient.getQueriesData({ queryKey: key })).toStrictEqual([]) }) it('should accept query filters', () => { @@ -697,7 +689,7 @@ describe('queryClient', () => { queryClient.setQueryData(['key', 2], 2) const query1 = queryCache.find({ queryKey: ['key', 1] })! - const result = cacheOperations(queryClient).getQueriesData({ + const result = queryClient.getQueriesData({ predicate: (query) => query === query1, }) @@ -931,7 +923,7 @@ describe('queryClient', () => { expect(first.data).toBe('data') expect(fetchFn).toHaveBeenCalledTimes(1) - await cacheOperations(queryClient).invalidateQueries({ + await queryClient.invalidateQueries({ queryKey: key, refetchType: 'none', }) @@ -1148,7 +1140,7 @@ describe('queryClient', () => { Promise.resolve(data.pages[0]) await expect( - cacheOperations(queryClient).infiniteQuery< + queryClient.infiniteQuery< StrictData, any, StrictData, @@ -1165,7 +1157,7 @@ describe('queryClient', () => { it('should return infinite query data', async () => { const key = createKey() - const result = await cacheOperations(queryClient).infiniteQuery({ + const result = await queryClient.infiniteQuery({ queryKey: key, getNextPageParam: () => undefined, initialPageParam: 10, @@ -1189,7 +1181,7 @@ describe('queryClient', () => { >(({ pageParam }: { pageParam: number }) => Promise.resolve(pageParam)) await expect( - cacheOperations(queryClient).infiniteQuery({ + queryClient.infiniteQuery({ queryKey: key, queryFn, getNextPageParam: () => undefined, @@ -1215,7 +1207,7 @@ describe('queryClient', () => { pageParams: [0], }) - const result = await cacheOperations(queryClient).infiniteQuery({ + const result = await queryClient.infiniteQuery({ queryKey: key, queryFn, getNextPageParam: () => undefined, @@ -1236,7 +1228,7 @@ describe('queryClient', () => { pageParams: [0], }) - const result = await cacheOperations(queryClient).infiniteQuery({ + const result = await queryClient.infiniteQuery({ queryKey: key, queryFn: skipToken, getNextPageParam: () => undefined, @@ -1255,7 +1247,7 @@ describe('queryClient', () => { ) await expect( - cacheOperations(queryClient).infiniteQuery({ + queryClient.infiniteQuery({ queryKey: key, queryFn: skipToken, getNextPageParam: () => undefined, @@ -1299,7 +1291,7 @@ describe('queryClient', () => { return query.state.data?.pages[0]?.staleTime ?? 0 } - const result = await cacheOperations(queryClient).infiniteQuery({ + const result = await queryClient.infiniteQuery({ queryKey: key, queryFn, getNextPageParam: () => undefined, @@ -1322,7 +1314,7 @@ describe('queryClient', () => { >(({ pageParam }: { pageParam: number }) => Promise.resolve({ value: `fetched-${String(pageParam)}` }), ) - const first = await cacheOperations(queryClient).infiniteQuery({ + const first = await queryClient.infiniteQuery({ queryKey: key, queryFn, getNextPageParam: () => undefined, @@ -1335,12 +1327,12 @@ describe('queryClient', () => { }) expect(queryFn).toHaveBeenCalledTimes(1) - await cacheOperations(queryClient).invalidateQueries({ + await queryClient.invalidateQueries({ queryKey: key, refetchType: 'none', }) - const second = await cacheOperations(queryClient).infiniteQuery({ + const second = await queryClient.infiniteQuery({ queryKey: key, queryFn, getNextPageParam: () => undefined, @@ -1354,7 +1346,7 @@ describe('queryClient', () => { it('should apply select to infinite query data', async () => { const key = createKey() - const result = await cacheOperations(queryClient).infiniteQuery({ + const result = await queryClient.infiniteQuery({ queryKey: key, getNextPageParam: () => undefined, initialPageParam: 10, @@ -1374,7 +1366,7 @@ describe('queryClient', () => { const fetchFn: QueryFunction = () => Promise.resolve('data') - await cacheOperations(queryClient) + await queryClient .infiniteQuery({ queryKey: key, queryFn: fetchFn, @@ -1394,7 +1386,7 @@ describe('queryClient', () => { it('should return infinite query data', async () => { const key = createKey() - await cacheOperations(queryClient) + await queryClient .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => Number(pageParam), @@ -1414,7 +1406,7 @@ describe('queryClient', () => { it('should prefetch multiple pages', async () => { const key = createKey() - await cacheOperations(queryClient) + await queryClient .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => String(pageParam), @@ -1437,7 +1429,7 @@ describe('queryClient', () => { const key = createKey() let count = 0 - await cacheOperations(queryClient) + await queryClient .infiniteQuery({ queryKey: key, queryFn: ({ pageParam }) => String(pageParam), @@ -1526,7 +1518,7 @@ describe('queryClient', () => { // check the error doesn't occur expect(() => - cacheOperations(queryClient).removeQueries({ + queryClient.removeQueries({ queryKey: key, exact: true, }), @@ -1548,7 +1540,7 @@ describe('queryClient', () => { }) await vi.advanceTimersByTimeAsync(10) - await cacheOperations(queryClient).cancelQueries() + await queryClient.cancelQueries() // with previous data present, imperative fetch should resolve to that data after cancel await expect(pending).resolves.toBe('data') @@ -1573,10 +1565,7 @@ describe('queryClient', () => { }) .catch(noop) await vi.advanceTimersByTimeAsync(10) - await cacheOperations(queryClient).cancelQueries( - { queryKey: key1 }, - { revert: false }, - ) + await queryClient.cancelQueries({ queryKey: key1 }, { revert: false }) const state1 = queryClient.getQueryState(key1) expect(state1).toMatchObject({ status: 'error', @@ -1592,7 +1581,7 @@ describe('queryClient', () => { }) await vi.advanceTimersByTimeAsync(10) - await cacheOperations(queryClient).cancelQueries({ queryKey: key }) + await queryClient.cancelQueries({ queryKey: key }) // we have to reject here because we can't resolve with `undefined` // the alternative would be a never-ending promise @@ -1621,7 +1610,7 @@ describe('queryClient', () => { enabled: false, }) observer1.subscribe(() => undefined) - await cacheOperations(queryClient).refetchQueries() + await queryClient.refetchQueries() observer1.destroy() expect(queryFn).toHaveBeenCalledTimes(1) }) @@ -1644,7 +1633,7 @@ describe('queryClient', () => { }) observer1.subscribe(() => undefined) observer2.subscribe(() => undefined) - await cacheOperations(queryClient).refetchQueries() + await queryClient.refetchQueries() observer1.destroy() observer2.destroy() expect(queryFn).toHaveBeenCalledTimes(2) @@ -1675,7 +1664,7 @@ describe('queryClient', () => { }) observer1.subscribe(() => undefined) observer2.subscribe(() => undefined) - await cacheOperations(queryClient).refetchQueries() + await queryClient.refetchQueries() observer1.destroy() observer2.destroy() expect(queryFn1).toHaveBeenCalledTimes(2) @@ -1699,7 +1688,7 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - await cacheOperations(queryClient).refetchQueries({ + await queryClient.refetchQueries({ type: 'active', stale: false, }) @@ -1724,8 +1713,8 @@ describe('queryClient', () => { queryFn: queryFn1, }) const unsubscribe = observer.subscribe(() => undefined) - cacheOperations(queryClient).invalidateQueries({ queryKey: key1 }) - await cacheOperations(queryClient).refetchQueries({ stale: true }) + queryClient.invalidateQueries({ queryKey: key1 }) + await queryClient.refetchQueries({ stale: true }) unsubscribe() // query, observer mount, invalidation (cancels observer mount) and refetch expect(queryFn1).toHaveBeenCalledTimes(4) @@ -1743,13 +1732,13 @@ describe('queryClient', () => { .mockReturnValue('data2') await queryClient.query({ queryKey: key1, queryFn: queryFn1 }) await queryClient.query({ queryKey: key2, queryFn: queryFn2 }) - cacheOperations(queryClient).invalidateQueries({ queryKey: key1 }) + queryClient.invalidateQueries({ queryKey: key1 }) const observer = new QueryObserver(queryClient, { queryKey: key1, queryFn: queryFn1, }) const unsubscribe = observer.subscribe(() => undefined) - await cacheOperations(queryClient).refetchQueries( + await queryClient.refetchQueries( { type: 'active', stale: true }, { cancelRefetch: false }, ) @@ -1758,7 +1747,7 @@ describe('queryClient', () => { expect(queryFn2).toHaveBeenCalledTimes(1) }) - it('should be able to refetch all active and inactive queries (cacheOperations(queryClient).refetchQueries()', async () => { + it('should be able to refetch all active and inactive queries (queryClient.refetchQueries()', async () => { const key1 = createKey() const key2 = createKey() const queryFn1 = vi @@ -1775,13 +1764,13 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - await cacheOperations(queryClient).refetchQueries() + await queryClient.refetchQueries() unsubscribe() expect(queryFn1).toHaveBeenCalledTimes(2) expect(queryFn2).toHaveBeenCalledTimes(2) }) - it('should be able to refetch all active and inactive queries (cacheOperations(queryClient).refetchQueries({ type: "all" }))', async () => { + it('should be able to refetch all active and inactive queries (queryClient.refetchQueries({ type: "all" }))', async () => { const key1 = createKey() const key2 = createKey() const queryFn1 = vi @@ -1798,7 +1787,7 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - await cacheOperations(queryClient).refetchQueries({ type: 'all' }) + await queryClient.refetchQueries({ type: 'all' }) unsubscribe() expect(queryFn1).toHaveBeenCalledTimes(2) expect(queryFn2).toHaveBeenCalledTimes(2) @@ -1821,7 +1810,7 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - await cacheOperations(queryClient).refetchQueries({ type: 'active' }) + await queryClient.refetchQueries({ type: 'active' }) unsubscribe() expect(queryFn1).toHaveBeenCalledTimes(2) expect(queryFn2).toHaveBeenCalledTimes(1) @@ -1844,7 +1833,7 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - await cacheOperations(queryClient).refetchQueries({ type: 'inactive' }) + await queryClient.refetchQueries({ type: 'inactive' }) unsubscribe() expect(queryFn1).toHaveBeenCalledTimes(1) expect(queryFn2).toHaveBeenCalledTimes(2) @@ -1862,7 +1851,7 @@ describe('queryClient', () => { } catch {} let error: any try { - await cacheOperations(queryClient).refetchQueries( + await queryClient.refetchQueries( { queryKey: key1 }, { throwOnError: true }, ) @@ -1880,7 +1869,7 @@ describe('queryClient', () => { await queryClient.query({ queryKey: key1, queryFn: queryFn1 }) mockOnlineManagerIsOnline(false) - await cacheOperations(queryClient).refetchQueries({ queryKey: key1 }) + await queryClient.refetchQueries({ queryKey: key1 }) // if we reach this point, the test succeeds because the Promise was resolved immediately expect(queryFn1).toHaveBeenCalledTimes(1) @@ -1899,7 +1888,7 @@ describe('queryClient', () => { await queryClient.query({ queryKey: key1, queryFn: () => 'data1' }) mockOnlineManagerIsOnline(false) - await cacheOperations(queryClient).refetchQueries( + await queryClient.refetchQueries( { queryKey: key1 }, { throwOnError: true }, ) @@ -1920,7 +1909,7 @@ describe('queryClient', () => { await queryClient.query({ queryKey: key1, queryFn: queryFn1 }) mockOnlineManagerIsOnline(false) - await cacheOperations(queryClient).refetchQueries({ queryKey: key1 }) + await queryClient.refetchQueries({ queryKey: key1 }) // initial fetch + refetch (even though we are offline) expect(queryFn1).toHaveBeenCalledTimes(2) @@ -1938,7 +1927,7 @@ describe('queryClient', () => { staleTime: 'static', }) const unsubscribe = observer.subscribe(() => undefined) - await cacheOperations(queryClient).refetchQueries() + await queryClient.refetchQueries() expect(queryFn).toHaveBeenCalledTimes(1) unsubscribe() @@ -1963,7 +1952,7 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - cacheOperations(queryClient).invalidateQueries({ queryKey: key1 }) + queryClient.invalidateQueries({ queryKey: key1 }) unsubscribe() expect(queryFn1).toHaveBeenCalledTimes(2) expect(queryFn2).toHaveBeenCalledTimes(1) @@ -1987,7 +1976,7 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - cacheOperations(queryClient).invalidateQueries({ queryKey: key1 }) + queryClient.invalidateQueries({ queryKey: key1 }) unsubscribe() expect(queryFn1).toHaveBeenCalledTimes(1) expect(queryFn2).toHaveBeenCalledTimes(1) @@ -2010,7 +1999,7 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - cacheOperations(queryClient).invalidateQueries({ + queryClient.invalidateQueries({ queryKey: key1, refetchType: 'none', }) @@ -2039,7 +2028,7 @@ describe('queryClient', () => { const unsubscribe = observer.subscribe(() => undefined) unsubscribe() - await cacheOperations(queryClient).invalidateQueries({ + await queryClient.invalidateQueries({ queryKey: key1, refetchType: 'inactive', }) @@ -2064,7 +2053,7 @@ describe('queryClient', () => { staleTime: Infinity, }) const unsubscribe = observer.subscribe(() => undefined) - cacheOperations(queryClient).invalidateQueries({ + queryClient.invalidateQueries({ refetchType: 'all', }) unsubscribe() @@ -2084,7 +2073,7 @@ describe('queryClient', () => { }) const unsubscribe = observer.subscribe(() => undefined) unsubscribe() - await cacheOperations(queryClient).invalidateQueries({ + await queryClient.invalidateQueries({ refetchType: 'all', }) expect(queryFn).toHaveBeenCalledTimes(0) @@ -2104,7 +2093,7 @@ describe('queryClient', () => { unsubscribe() expect(queryClient.getQueryState(key)?.dataUpdateCount).toBe(1) - await cacheOperations(queryClient).invalidateQueries({ + await queryClient.invalidateQueries({ refetchType: 'all', }) expect(queryClient.getQueryState(key)?.dataUpdateCount).toBe(1) @@ -2126,7 +2115,7 @@ describe('queryClient', () => { }) observer.subscribe(() => undefined) - cacheOperations(queryClient).refetchQueries() + queryClient.refetchQueries() await vi.advanceTimersByTimeAsync(10) observer.destroy() expect(abortFn).toHaveBeenCalledTimes(1) @@ -2150,7 +2139,7 @@ describe('queryClient', () => { }) observer.subscribe(() => undefined) - cacheOperations(queryClient).refetchQueries(undefined, { + queryClient.refetchQueries(undefined, { cancelRefetch: false, }) await vi.advanceTimersByTimeAsync(10) @@ -2176,7 +2165,7 @@ describe('queryClient', () => { expect(queryFn).toHaveBeenCalledTimes(1) expect(queryClient.getQueryState(key)?.status).toBe('error') - await cacheOperations(queryClient).invalidateQueries({ queryKey: key }) + await queryClient.invalidateQueries({ queryKey: key }) expect(queryFn).toHaveBeenCalledTimes(2) expect(queryClient.getQueryData(key)).toBe('data') @@ -2195,7 +2184,7 @@ describe('queryClient', () => { staleTime: 'static', }) const unsubscribe = observer.subscribe(() => undefined) - await cacheOperations(queryClient).invalidateQueries() + await queryClient.invalidateQueries() expect(queryFn).toHaveBeenCalledTimes(1) unsubscribe() @@ -2216,7 +2205,7 @@ describe('queryClient', () => { const unsubscribe = observer.subscribe(noop) expect(queryFn).toHaveBeenCalledTimes(1) - await cacheOperations(queryClient).resetQueries({ queryKey: key }) + await queryClient.resetQueries({ queryKey: key }) expect(queryFn).toHaveBeenCalledTimes(2) expect(queryClient.getQueryData(key)).toBe('data') @@ -2235,7 +2224,7 @@ describe('queryClient', () => { const unsubscribe = observer.subscribe(noop) queryClient.setQueryData(key, 2) - await cacheOperations(queryClient).resetQueries({ queryKey: key }) + await queryClient.resetQueries({ queryKey: key }) expect(queryFn).not.toHaveBeenCalled() expect(queryClient.getQueryData(key)).toBe(0) @@ -2253,7 +2242,7 @@ describe('queryClient', () => { queryCache.subscribe(callback) - cacheOperations(queryClient).resetQueries({ queryKey: key }) + queryClient.resetQueries({ queryKey: key }) const query = queryCache.find({ queryKey: key }) expect(callback).toHaveBeenNthCalledWith( @@ -2277,7 +2266,7 @@ describe('queryClient', () => { expect(state?.data).toBe('data') expect(state?.status).toBe('success') - cacheOperations(queryClient).resetQueries({ queryKey: key }) + queryClient.resetQueries({ queryKey: key }) state = queryClient.getQueryState(key) @@ -2300,7 +2289,7 @@ describe('queryClient', () => { let state = queryClient.getQueryState(key) expect(state?.data).toBe('data') - cacheOperations(queryClient).resetQueries({ queryKey: key }) + queryClient.resetQueries({ queryKey: key }) state = queryClient.getQueryState(key) @@ -2330,7 +2319,7 @@ describe('queryClient', () => { }) const unsubscribe = observer.subscribe(() => undefined) - await cacheOperations(queryClient).resetQueries({ + await queryClient.resetQueries({ predicate: (query) => query.state.status === 'error', }) expect(queryFn).toHaveBeenCalledTimes(2) @@ -2367,7 +2356,7 @@ describe('queryClient', () => { observer1.subscribe(() => undefined) observer2.subscribe(() => undefined) observer3.subscribe(() => (didSkipTokenRun = true)) - await cacheOperations(queryClient).resetQueries() + await queryClient.resetQueries() observer3.destroy() observer2.destroy() observer1.destroy() @@ -2396,7 +2385,7 @@ describe('queryClient', () => { 'onOnline', ) const mutationCacheResumePausedMutationsSpy = vi.spyOn( - getMutationCache(testClient), + testClient.getMutationCache(), 'resumePausedMutations', ) @@ -2425,7 +2414,7 @@ describe('queryClient', () => { 'onOnline', ) const mutationCacheResumePausedMutationsSpy = vi.spyOn( - getMutationCache(testClient), + testClient.getMutationCache(), 'resumePausedMutations', ) @@ -2589,15 +2578,15 @@ describe('queryClient', () => { hydrate(newQueryClient, state) // still paused because we are still offline - expect(getMutationCache(newQueryClient).getAll()[0]?.state.isPaused).toBe( - true, - ) + expect( + newQueryClient.getMutationCache().getAll()[0]?.state.isPaused, + ).toBe(true) await newQueryClient.resumePausedMutations() onlineManager.setOnline(true) await vi.advanceTimersByTimeAsync(0) - expect(getMutationCache(newQueryClient).getAll()[0]?.state.status).toBe( + expect(newQueryClient.getMutationCache().getAll()[0]?.state.status).toBe( 'success', ) @@ -2698,7 +2687,7 @@ describe('queryClient', () => { 'onOnline', ) const mutationCacheResumePausedMutationsSpy = vi.spyOn( - getMutationCache(testClient), + testClient.getMutationCache(), 'resumePausedMutations', ) @@ -2733,7 +2722,7 @@ describe('queryClient', () => { 'onOnline', ) const mutationCacheResumePausedMutationsSpy = vi.spyOn( - getMutationCache(testClient), + testClient.getMutationCache(), 'resumePausedMutations', ) diff --git a/packages/query-core/src/__tests__/queryObserver.test.tsx b/packages/query-core/src/__tests__/queryObserver.test.tsx index 6d78c46a24f..bb31cf5ab02 100644 --- a/packages/query-core/src/__tests__/queryObserver.test.tsx +++ b/packages/query-core/src/__tests__/queryObserver.test.tsx @@ -1,5 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { refetchInterval } from '@tanstack/query-test-utils/polling' import { placeholderOption, @@ -158,7 +157,7 @@ describe('queryObserver', () => { it('should not be re-fetched when invalidated with refetchType: all', async () => { const unsubscribe = observer.subscribe(vi.fn()) - cacheOperations(queryClient).invalidateQueries({ + queryClient.invalidateQueries({ queryKey: key, refetchType: 'all', }) @@ -231,7 +230,7 @@ describe('queryObserver', () => { unsubscribe() - cacheOperations(queryClient).invalidateQueries({ + queryClient.invalidateQueries({ queryKey: key, refetchType: 'active', }) @@ -249,7 +248,7 @@ describe('queryObserver', () => { // Toggle enabled enabled = true - cacheOperations(queryClient).invalidateQueries({ + queryClient.invalidateQueries({ queryKey: key, refetchType: 'active', }) @@ -270,7 +269,7 @@ describe('queryObserver', () => { // Toggle enabled enabled = true - cacheOperations(queryClient).invalidateQueries({ + queryClient.invalidateQueries({ queryKey: key, refetchType: 'inactive', }) @@ -279,7 +278,7 @@ describe('queryObserver', () => { await vi.advanceTimersByTimeAsync(10) expect(count).toBe(0) - cacheOperations(queryClient).invalidateQueries({ + queryClient.invalidateQueries({ queryKey: key, refetchType: 'active', }) @@ -292,7 +291,7 @@ describe('queryObserver', () => { enabled = false // should not refetch since it is not active and we only refetch active - cacheOperations(queryClient).invalidateQueries({ + queryClient.invalidateQueries({ queryKey: key, refetchType: 'active', }) @@ -786,7 +785,7 @@ describe('queryObserver', () => { }) shouldThrow = false - cacheOperations(queryClient).resetQueries({ queryKey: key }) + queryClient.resetQueries({ queryKey: key }) expect(observer.getCurrentResult()).toMatchObject({ status: 'pending', data: undefined, @@ -1702,7 +1701,7 @@ describe('queryObserver', () => { const observer = new QueryObserver(queryClient, options) const unsubscribe = observer.subscribe(noop) - cacheOperations(queryClient).removeQueries({ queryKey: key }) + queryClient.removeQueries({ queryKey: key }) // Broadcast can recreate the query without a queryFn before the observer updates. queryClient.getQueryCache().build(queryClient, { queryKey: key, diff --git a/packages/query-core/src/__tests__/queryObserverProjection.test.ts b/packages/query-core/src/__tests__/queryObserverProjection.test.ts index 51728c55a91..ee94a4fd1d1 100644 --- a/packages/query-core/src/__tests__/queryObserverProjection.test.ts +++ b/packages/query-core/src/__tests__/queryObserverProjection.test.ts @@ -1,5 +1,4 @@ import { createKey } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { placeholderOption, selectOption, @@ -40,7 +39,7 @@ describe('observer data outcome after reset', () => { isPlaceholderData: false, }) - await cacheOperations(queryClient).resetQueries({ queryKey: key }) + await queryClient.resetQueries({ queryKey: key }) expect(queryClient.getQueryData(key)).toBeUndefined() expect(observer.getCurrentResult()).toMatchObject({ @@ -79,7 +78,7 @@ describe('observer data outcome after reset', () => { }) expect(select).toHaveBeenCalledTimes(2) - await cacheOperations(queryClient).resetQueries({ queryKey: key }) + await queryClient.resetQueries({ queryKey: key }) expect(queryClient.getQueryData(key)).toBeUndefined() const callsAfterReset = select.mock.calls.length diff --git a/packages/query-core/src/__tests__/streamedQuery.test.tsx b/packages/query-core/src/__tests__/streamedQuery.test.tsx index 38256c1f455..75e3307b61b 100644 --- a/packages/query-core/src/__tests__/streamedQuery.test.tsx +++ b/packages/query-core/src/__tests__/streamedQuery.test.tsx @@ -1,5 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { QueryClient, QueryObserver, streamedQuery } from '..' @@ -412,7 +411,7 @@ describe('streamedQuery', () => { const unsubscribe = observer.subscribe(vi.fn()) await vi.advanceTimersByTimeAsync(50) - await cacheOperations(queryClient).cancelQueries({ queryKey: key }) + await queryClient.cancelQueries({ queryKey: key }) const cancelledData = queryClient.getQueryData(key) expect(cancelledData).toStrictEqual( refetchMode === 'append' ? [99, 0] : [99], @@ -492,7 +491,7 @@ describe('streamedQuery', () => { const unsubscribe = observer.subscribe(vi.fn()) await vi.advanceTimersByTimeAsync(0) resolveChunk({ done: false, value: 1 }) - void cacheOperations(queryClient).cancelQueries({ queryKey: key }) + void queryClient.cancelQueries({ queryKey: key }) await vi.advanceTimersByTimeAsync(0) expect(queryClient.getQueryData(key)).toStrictEqual([99]) @@ -528,7 +527,7 @@ describe('streamedQuery', () => { }) const unsubscribe = observer.subscribe(vi.fn()) - await cacheOperations(queryClient).cancelQueries({ queryKey: key }) + await queryClient.cancelQueries({ queryKey: key }) queryClient.setQueryData(key, [100]) await vi.advanceTimersByTimeAsync(100) diff --git a/packages/query-core/src/__tests__/utils.test-d.tsx b/packages/query-core/src/__tests__/utils.test-d.tsx index 94695fd5d89..7fc9ca752b4 100644 --- a/packages/query-core/src/__tests__/utils.test-d.tsx +++ b/packages/query-core/src/__tests__/utils.test-d.tsx @@ -1,4 +1,3 @@ -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { assertType, describe, expectTypeOf, it } from 'vitest' import { QueryClient } from '../queryClient' import { @@ -25,15 +24,10 @@ import { sleep, timeUntilStale, } from '../utils' -import type { DataTag, MutationStatus } from '..' +import type { DataTag, EqualityFn, MutationStatus } from '..' import type { Mutation } from '../mutation' import type { Query } from '../query' -import type { - EqualityFn, - QueryFunction, - QueryKey, - QueryOptions, -} from '../types' +import type { QueryFunction, QueryKey, QueryOptions } from '../types' import type { DefaultQueryFn, MutationFilters, @@ -125,7 +119,7 @@ describe('QueryFilters', () => { const queryKey: Key = ['foo', 'bar'] as any as Key - const result = cacheOperations(new QueryClient()).invalidateQueries({ + const result = new QueryClient().invalidateQueries({ queryKey, }) expectTypeOf(result).toEqualTypeOf>() diff --git a/packages/query-core/src/__tests__/utils.test.tsx b/packages/query-core/src/__tests__/utils.test.tsx index b3169c0be13..1fa46835e7d 100644 --- a/packages/query-core/src/__tests__/utils.test.tsx +++ b/packages/query-core/src/__tests__/utils.test.tsx @@ -1,5 +1,4 @@ import { createKey } from '@tanstack/query-test-utils' -import { getMutationCache } from '@tanstack/query-test-utils/cacheOperations' import { describe, expect, it, vi } from 'vitest' import { QueryClient } from '..' import { Mutation } from '../mutation' @@ -560,7 +559,7 @@ describe('core/utils', () => { const mutation = new Mutation({ client: queryClient, mutationId: 1, - mutationCache: getMutationCache(queryClient), + mutationCache: queryClient.getMutationCache(), options: {}, }) diff --git a/packages/query-core/src/environmentManager.ts b/packages/query-core/src/environmentManager.ts index 8768c79d2da..3a8997be946 100644 --- a/packages/query-core/src/environmentManager.ts +++ b/packages/query-core/src/environmentManager.ts @@ -1,4 +1,7 @@ -import type { IsServerValue } from '@tanstack/query-types/bindings' +/** + * A function that returns whether the code is running on the server. + */ +export type IsServerValue = () => boolean const defaultIsServer = typeof window === 'undefined' || 'Deno' in globalThis @@ -37,5 +40,3 @@ export const environmentManager = { isServerFn = isServerValue }, } - -export type { IsServerValue } from '@tanstack/query-types/bindings' diff --git a/packages/query-core/src/focusManager.ts b/packages/query-core/src/focusManager.ts index 50495d69580..0dd0c9e8d1a 100644 --- a/packages/query-core/src/focusManager.ts +++ b/packages/query-core/src/focusManager.ts @@ -1,8 +1,10 @@ import { Subscribable } from './subscribable' -import type { - FocusManagerListener as Listener, - FocusManagerSetupFn as SetupFn, -} from '@tanstack/query-types/bindings' + +type Listener = (focused: boolean) => void + +type SetupFn = ( + setFocused: (focused?: boolean) => void, +) => (() => void) | undefined /** * The `FocusManager` manages the focus state within TanStack Query. diff --git a/packages/query-core/src/hydration.ts b/packages/query-core/src/hydration.ts index 9f431f465e9..49b24a8ed1b 100644 --- a/packages/query-core/src/hydration.ts +++ b/packages/query-core/src/hydration.ts @@ -1,15 +1,21 @@ import { Mutation } from './mutation' import { noop } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - DehydratedMutation, - DehydratedQuery, - DehydratedState, - TransformerFn, -} from '@tanstack/query-types/bindings' -import type { Query } from './query' +import type { MutationState } from './mutation' +import type { Query, QueryState } from './query' import type { QueryClient } from './queryClient' -import type { QueryRuntime } from './runtimeBinding' +import type { + DefaultError, + MutationKey, + MutationMeta, + MutationOptions, + MutationScope, + QueryKey, + QueryMeta, + QueryOptions, +} from './types' + +// TYPES +type TransformerFn = (data: any) => any /** * Reads the value of a promise synchronously if it has already resolved, e.g. a thenable that @@ -37,9 +43,73 @@ function tryResolveSync(promise: PromiseLike) { return undefined } -type DehydrateOptions = Shared.DehydrateOptions +/** + * 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 + } +} + +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' +} -type HydrateOptions = Shared.HydrateOptions +/** + * 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 +} // FUNCTIONS @@ -364,7 +434,3 @@ export function hydrate( }, ) } - -export type { DehydratedState } from '@tanstack/query-types/bindings' - -export type { DehydrateOptions, HydrateOptions } diff --git a/packages/query-core/src/index.ts b/packages/query-core/src/index.ts index b2706f657e9..0b313930aa5 100644 --- a/packages/query-core/src/index.ts +++ b/packages/query-core/src/index.ts @@ -165,4 +165,3 @@ export type { NotifyEventType, NotifyEvent, } from './types' -export type { QueryRuntime } from './runtimeBinding' diff --git a/packages/query-core/src/infiniteQueryObserver.ts b/packages/query-core/src/infiniteQueryObserver.ts index 8fbd5546791..b662821e5ab 100644 --- a/packages/query-core/src/infiniteQueryObserver.ts +++ b/packages/query-core/src/infiniteQueryObserver.ts @@ -1,17 +1,11 @@ import { hasNextPage, hasPreviousPage } from './infiniteQueryBehavior' import { QueryObserver } from './queryObserver' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - InfiniteQueryObserverListener, - ReplaceReturnType, -} from '@tanstack/query-types/bindings' import type { Query } from './query' import type { QueryClient } from './queryClient' import type { QueryObserverResultContext, QueryObserverResultReader, } from './queryObserver' -import type { QueryRuntime } from './runtimeBinding' import type { Subscribable } from './subscribable' import type { DefaultError, @@ -20,25 +14,37 @@ import type { FetchPreviousPageOptions, InfiniteData, InfiniteQueryObserverBaseResult, + InfiniteQueryObserverOptions, InfiniteQueryObserverResult, QueryKey, QueryObserverResult, } from './types' +type InfiniteQueryObserverListener = ( + result: InfiniteQueryObserverResult, +) => void + type InfiniteObserverOptionsInput< TQueryFnData, TError, TData, TQueryKey extends QueryKey, TPageParam, -> = Shared.InfiniteObserverOptionsInput< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> +> = + | InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + | DefaultedInfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > /** * An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch @@ -275,3 +281,8 @@ export class InfiniteQueryObserver< return result as InfiniteQueryObserverResult } } + +type ReplaceReturnType< + TFunction extends (...args: Array) => unknown, + TReturn, +> = (...args: Parameters) => TReturn diff --git a/packages/query-core/src/mutation.ts b/packages/query-core/src/mutation.ts index 79a3c27bf95..0c7690b84b8 100644 --- a/packages/query-core/src/mutation.ts +++ b/packages/query-core/src/mutation.ts @@ -1,31 +1,121 @@ import { notifyManager } from './notifyManager' import { Removable } from './removable' import { createRetryer } from './retryer' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - MutationAction as Action, - MutationState, -} from '@tanstack/query-types/bindings' import type { MutationCache } from './mutationCache' import type { MutationObserver } from './mutationObserver' import type { QueryClient } from './queryClient' import type { Retryer } from './retryer' -import type { QueryRuntime } from './runtimeBinding' import type { DefaultError, MutationFunctionContext, MutationMeta, MutationOptions, + MutationStatus, } from './types' -type MutationConfig = - Shared.MutationConfig< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult - > +// TYPES + +interface MutationConfig { + client: QueryClient + mutationId: number + mutationCache: MutationCache + options: MutationOptions + state?: MutationState +} + +/** + * 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 // CLASS @@ -496,8 +586,3 @@ export function getDefaultState< submittedAt: 0, } } - -export type { - MutationState, - MutationAction as Action, -} from '@tanstack/query-types/bindings' diff --git a/packages/query-core/src/mutationCache.ts b/packages/query-core/src/mutationCache.ts index 8b6e4a73e54..ae102bfc2b4 100644 --- a/packages/query-core/src/mutationCache.ts +++ b/packages/query-core/src/mutationCache.ts @@ -1,17 +1,114 @@ import { notifyManager } from './notifyManager' import { Subscribable } from './subscribable' import { matchMutation, noop } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { Mutation } from './mutation' -import type { QueryRuntime } from './runtimeBinding' -import type { DefaultError } from './types' +import type { Action, Mutation } from './mutation' +import type { MutationObserver } from './mutationObserver' +import type { + CacheKeyConfig, + DefaultError, + MutationFunctionContext, + MutationKey, + NotifyEvent, +} from './types' import type { MutationFilters } from './utils' -type MutationCacheConfig = Shared.MutationCacheConfig +// TYPES -type MutationCacheNotifyEvent = Shared.MutationCacheNotifyEvent +/** + * 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 +} -type MutationCacheListener = Shared.MutationCacheListener +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: Action +} + +/** + * 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 // CLASS @@ -267,5 +364,3 @@ export class MutationCache extends Subscribable { function scopeFor(mutation: Mutation) { return mutation.options.scope?.id } - -export type { MutationCacheConfig, MutationCacheNotifyEvent } diff --git a/packages/query-core/src/mutationObserver.ts b/packages/query-core/src/mutationObserver.ts index 2feb3590d83..698416578bf 100644 --- a/packages/query-core/src/mutationObserver.ts +++ b/packages/query-core/src/mutationObserver.ts @@ -2,10 +2,8 @@ import { Mutation, getDefaultState } from './mutation' import { notifyManager } from './notifyManager' import { Subscribable } from './subscribable' import { hashKeyByOptions, shallowEqualObjects } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' import type { Action } from './mutation' import type { QueryClient } from './queryClient' -import type { QueryRuntime } from './runtimeBinding' import type { DefaultError, MutateOptions, @@ -14,14 +12,11 @@ import type { MutationObserverResult, } from './types' -type MutationObserverListener = - Shared.MutationObserverListener< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult - > +// TYPES + +type MutationObserverListener = ( + result: MutationObserverResult, +) => void // CLASS diff --git a/packages/query-core/src/notifyManager.ts b/packages/query-core/src/notifyManager.ts index 97ae9dd8bf3..1155f77841f 100644 --- a/packages/query-core/src/notifyManager.ts +++ b/packages/query-core/src/notifyManager.ts @@ -1,10 +1,12 @@ -import type { - BatchCallsCallback, - BatchNotifyFunction, - NotifyCallback, - NotifyFunction, - ScheduleFunction, -} from '@tanstack/query-types/bindings' +type NotifyCallback = () => void + +type NotifyFunction = (callback: () => void) => void + +type BatchNotifyFunction = (callback: () => void) => void + +type BatchCallsCallback> = (...args: T) => void + +type ScheduleFunction = (callback: () => void) => void /** * Default scheduling function used by the notify manager. diff --git a/packages/query-core/src/onlineManager.ts b/packages/query-core/src/onlineManager.ts index 4548b0fa815..f6704ede01a 100644 --- a/packages/query-core/src/onlineManager.ts +++ b/packages/query-core/src/onlineManager.ts @@ -1,8 +1,7 @@ import { Subscribable } from './subscribable' -import type { - OnlineManagerListener as Listener, - OnlineManagerSetupFn as SetupFn, -} from '@tanstack/query-types/bindings' + +type Listener = (online: boolean) => void +type SetupFn = (setOnline: Listener) => (() => void) | undefined /** * The `OnlineManager` manages the online state within TanStack Query. It can diff --git a/packages/query-core/src/primitives.ts b/packages/query-core/src/primitives.ts new file mode 100644 index 00000000000..548cdb09166 --- /dev/null +++ b/packages/query-core/src/primitives.ts @@ -0,0 +1,57 @@ +// Shared runtime for adapters with their own query clients and observers. +export { environmentManager, isServer } from './environmentManager' +export type { IsServerValue } from './environmentManager' +export { FocusManager, focusManager } from './focusManager' +export { OnlineManager, onlineManager } from './onlineManager' +export type { Action as MutationAction } from './mutation' +export type { + Action as QueryAction, + FetchDirection, + FetchMeta, + FetchOptions, +} from './query' +export { fetchState, getDefaultQueryState, successState } from './queryState' +export { Removable } from './removable' +export { CancelledError, canFetch, createRetryer } from './retryer' +export type { Retryer, RetryDelayValue, RetryValue } from './retryer' +export { Subscribable } from './subscribable' +export { + TimeoutManager, + defaultTimeoutProvider, + timeoutManager, +} from './timeoutManager' +export type { + ManagedTimerId, + TimeoutCallback, + TimeoutProvider, +} from './timeoutManager' +export { dataTagSymbol, dataTagErrorSymbol, unsetMarker } from './types' +export type { QueryObserverOptionsBase } from './types' +export { + addConsumeAwareSignal, + addToArray, + defaultQueryFn, + fetchSignal, + functionalUpdate, + hashKey, + hashKeyByOptions, + isPlainArray, + isPlainObject, + isValidTimeout, + noop, + partialMatchKey, + replaceData, + replaceEqualDeep, + shallowEqualObjects, + shouldThrowError, + skipToken, + sleep, + timeUntilStale, +} from './utils' +export type { + DefaultQueryFn, + FetchSignalContext, + QueryTypeFilter, + SkipToken, + Updater, +} from './utils' diff --git a/packages/query-core/src/queriesObserver.ts b/packages/query-core/src/queriesObserver.ts index 1a9392c5ca5..a1ea988b4f7 100644 --- a/packages/query-core/src/queriesObserver.ts +++ b/packages/query-core/src/queriesObserver.ts @@ -6,18 +6,15 @@ import { shallowEqualObjects, shouldThrowError, } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - CombineContext, - CombineFn, - QueriesObserverListener, - QueriesObserverOptions, - QueriesObserverResultReader, -} from '@tanstack/query-types/bindings' import type { QueryClient } from './queryClient' -import type { ObserverOptionsInput } from './queryObserver' -import type { QueryRuntime } from './runtimeBinding' -import type { QueryObserverResult } from './types' +import type { + ObserverOptionsInput, + QueryObserverResultReader, +} from './queryObserver' +import type { + DefaultedQueryObserverOptions, + QueryObserverResult, +} from './types' /** * Returns the items of `array1` that are not in `array2`. @@ -47,6 +44,44 @@ function equalResults( ) } +type QueriesObserverListener = (result: Array) => void + +type CombineFn = ( + result: Array, +) => TCombinedResult + +/** A cached reader for multiple query results and their combined value. */ +export interface QueriesObserverResultReader< + TCombinedResult, +> extends QueryObserverResultReader> { + /** Track result properties and combine the results with this reader's options. */ + combineResult: (result: Array) => TCombinedResult +} + +type CombineContext = { + result?: Array + combine?: CombineFn + value?: TCombinedResult + queryHashes?: Array +} + +/** + * Options for a `QueriesObserver` that apply to all of its queries at once. + */ +export interface QueriesObserverOptions< + TCombinedResult = Array, +> { + /** + * A function that combines the array of `QueryObserverResult`s (one per + * observed query) into a single value. The combined value is memoized and + * only recomputed when one of the underlying results, the query hashes, or + * the `combine` function itself changes. + * + * Defaults to returning the array of `QueryObserverResult`s unchanged. + */ + combine?: CombineFn +} + /** * A `QueriesObserver` watches an array of queries at once, exposing them as * a single array of `QueryObserverResult`s (or, when a `combine` option is @@ -460,9 +495,8 @@ export class QueriesObserver< } } -type QueryObserverMatch = Shared.QueryObserverMatch - -export type { - QueriesObserverResultReader, - QueriesObserverOptions, -} from '@tanstack/query-types/bindings' +type QueryObserverMatch = { + defaultedQueryOptions: DefaultedQueryObserverOptions + observer: QueryObserver + reader?: QueryObserverResultReader +} diff --git a/packages/query-core/src/query.ts b/packages/query-core/src/query.ts index 5cf7cb228ab..6c9c66950d4 100644 --- a/packages/query-core/src/query.ts +++ b/packages/query-core/src/query.ts @@ -1,7 +1,8 @@ import { infiniteQueryBehavior } from './infiniteQueryBehavior' import { notifyManager } from './notifyManager' +import { fetchState, getDefaultQueryState, successState } from './queryState' import { Removable } from './removable' -import { CancelledError, canFetch, createRetryer } from './retryer' +import { CancelledError, createRetryer } from './retryer' import { ensureQueryFn, fetchSignal, @@ -11,48 +12,252 @@ import { skipToken, timeUntilStale, } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - QueryAction as Action, - FetchOptions, - QueryState, -} from '@tanstack/query-types/bindings' import type { QueryCache } from './queryCache' import type { QueryClient } from './queryClient' import type { QueryObserver } from './queryObserver' import type { Retryer } from './retryer' -import type { QueryRuntime } from './runtimeBinding' import type { CancelOptions, DefaultError, - InitialDataFunction, + FetchStatus, QueryKey, QueryMeta, QueryOptions, + QueryStatus, SetDataOptions, StaleTime, } from './types' -type QueryConfig< +// TYPES + +interface QueryConfig< TQueryFnData, TError, TData, TQueryKey extends QueryKey = QueryKey, -> = Shared.QueryConfig +> { + client: QueryClient + queryKey: TQueryKey + queryHash: string + options?: QueryOptions + defaultOptions?: QueryOptions + state?: QueryState +} + +/** + * The raw state stored on a `Query` instance. This is the underlying state + * that observer results (e.g. `QueryObserverResult`) are derived from. + */ +export interface QueryState { + /** + * The last successfully resolved data for the query. + */ + data: TData | undefined + /** + * The number of times the query has successfully resolved. + */ + dataUpdateCount: number + /** + * The timestamp for when the query most recently returned the `status` as `"success"`. + */ + dataUpdatedAt: number + /** + * The error object for the query, if the last attempt resulted in an error. + * - Defaults to `null`. + */ + error: TError | null + /** + * The sum of all errors, incremented every time the query resolves with an error. + */ + errorUpdateCount: number + /** + * The timestamp for when the query most recently returned the `status` as `"error"`. + */ + errorUpdatedAt: number + /** + * The failure count for the current fetch. + * - Incremented every time the fetch fails. + * - Reset to `0` when the fetch succeeds. + */ + fetchFailureCount: number + /** + * The reason the current fetch failed, as reported by the retryer. + * - Reset to `null` when the fetch succeeds. + */ + fetchFailureReason: TError | null + /** + * Metadata passed to the currently in-flight (or most recent) fetch, e.g. the + * `fetchMore` direction for infinite queries. + */ + fetchMeta: FetchMeta | null + /** + * Whether the query has been marked as invalidated via `invalidate()`. + * - Reset to `false` whenever the query resolves successfully. + */ + isInvalidated: boolean + /** + * The status of the query. + * - `pending` if there's no cached data and no attempt was finished yet. + * - `error` if the last attempt resulted in an error. + * - `success` if the query has data. + */ + status: QueryStatus + /** + * The fetch status of the query. + * - `fetching`: the `queryFn` is currently executing. + * - `paused`: a fetch wanted to run but has been paused (see network mode). + * - `idle`: the query is not fetching. + */ + fetchStatus: FetchStatus +} -type FetchContext< +/** + * The context passed to a {@link QueryBehavior}'s `onFetch`, which can replace `fetchFn` to change + * how the query fetches (e.g. to fetch pages for an infinite query). + */ +export interface FetchContext< TQueryFnData, TError, TData, TQueryKey extends QueryKey = QueryKey, -> = Shared.FetchContext +> { + /** + * The function that runs the fetch. By default it calls `queryFn`; `onFetch` can replace it. + */ + fetchFn: () => unknown | Promise + /** + * The options of this fetch. + */ + fetchOptions?: FetchOptions + /** + * The `AbortSignal` that aborts when the fetch is cancelled. + */ + signal: AbortSignal + /** + * The options of the query. + */ + options: QueryOptions + /** + * The `QueryClient` the query belongs to. + */ + client: QueryClient + /** + * The key of the query. + */ + queryKey: TQueryKey + /** + * The state of the query when the fetch starts. + */ + state: QueryState +} -type QueryBehavior< +/** + * Customizes how a query fetches, e.g. the behavior that fetches the pages of an infinite query. + */ +export interface QueryBehavior< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> = Shared.QueryBehavior +> { + /** + * Called before each fetch of the query, e.g. to replace `fetchFn` in the context. + */ + onFetch: ( + context: FetchContext, + query: Query, + ) => void +} + +/** + * The direction an infinite query fetches in: `'forward'` for the next page, `'backward'` for the + * previous one. + */ +export type FetchDirection = 'forward' | 'backward' + +/** + * Metadata for a fetch, e.g. the direction when an infinite query fetches more pages. + */ +export interface FetchMeta { + /** + * Set when an infinite query fetches another page, with the direction to fetch in. + */ + fetchMore?: { direction: FetchDirection } +} + +/** + * Options for a single fetch of a query. + */ +export interface FetchOptions { + /** + * If `true`, an in-flight fetch is cancelled before starting a new one, when the query already + * has data. Otherwise, the in-flight fetch is reused. + */ + cancelRefetch?: boolean + /** + * Metadata of the fetch, stored in the query's `fetchMeta` state. + */ + meta?: FetchMeta + /** + * A promise to use for the first attempt instead of calling `fetchFn`, e.g. a pending promise + * restored by `hydrate`. + */ + initialPromise?: Promise +} + +interface FailedAction { + type: 'failed' + failureCount: number + error: TError +} + +interface FetchAction { + type: 'fetch' + meta?: FetchMeta +} + +interface SuccessAction { + data: TData | undefined + type: 'success' + dataUpdatedAt?: number + manual?: boolean +} + +interface ErrorAction { + type: 'error' + error: TError +} + +interface InvalidateAction { + type: 'invalidate' +} + +interface PauseAction { + type: 'pause' +} + +interface ContinueAction { + type: 'continue' +} + +interface SetStateAction { + type: 'setState' + state: Partial> +} + +/** + * The actions a query dispatches to update its state, e.g. when it starts fetching, fails, or + * succeeds. + */ +export type Action = + | ContinueAction + | ErrorAction + | FailedAction + | FetchAction + | InvalidateAction + | PauseAction + | SetStateAction + | SuccessAction // CLASS @@ -107,7 +312,7 @@ export class Query< this.#cache = this.#client.getQueryCache() this.queryKey = config.queryKey this.queryHash = config.queryHash - this.#initialState = getDefaultState(this.options) + this.#initialState = getDefaultQueryState(this.options) this.state = config.state ?? this.#initialState this.scheduleGc() } @@ -156,7 +361,7 @@ export class Query< // oxlint-disable-next-line typescript/no-unnecessary-condition -- the constructor calls 'setOptions' before it assigns 'state' if (this.state && this.state.data === undefined) { - const defaultState = getDefaultState(this.options) + const defaultState = getDefaultQueryState(this.options) if (defaultState.data !== undefined) { this.setState( successState(defaultState.data, defaultState.dataUpdatedAt), @@ -813,100 +1018,4 @@ export class Query< } } -/** - * Returns the state changes applied when a query starts fetching. - * @param data - The query's current data. If it is `undefined`, the query is also reset to - * `'pending'` with no error. - * @param options - The query options, whose `networkMode` decides whether the query is `'fetching'` - * or `'paused'`. - * @returns The partial query state for a starting fetch. - */ -export function fetchState< - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey, ->( - data: TData | undefined, - options: QueryOptions, -) { - return { - fetchFailureCount: 0, - fetchFailureReason: null, - fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused', - ...(data === undefined && - ({ - error: null, - status: 'pending', - } as const)), - } as const -} - -/** - * Returns the state changes applied when a query receives data. - * @param data - The new data. - * @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to the current time. - * @returns The partial query state for a successful update. - */ -function successState(data: TData | undefined, dataUpdatedAt?: number) { - return { - data, - dataUpdatedAt: dataUpdatedAt ?? Date.now(), - error: null, - isInvalidated: false, - status: 'success' as const, - } -} - -/** - * Returns the initial state of a query, based on its `initialData` and `initialDataUpdatedAt` - * options. - * @param options - The query options. - * @returns The initial query state: `'success'` if `initialData` is set, otherwise `'pending'`. - */ -function getDefaultState< - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey, ->( - options: QueryOptions, -): QueryState { - const data = - typeof options.initialData === 'function' - ? (options.initialData as InitialDataFunction)() - : options.initialData - - const hasData = data !== undefined - - const initialDataUpdatedAt = hasData - ? typeof options.initialDataUpdatedAt === 'function' - ? options.initialDataUpdatedAt() - : options.initialDataUpdatedAt - : 0 - - return { - data, - dataUpdateCount: 0, - dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0, - error: null, - errorUpdateCount: 0, - errorUpdatedAt: 0, - fetchFailureCount: 0, - fetchFailureReason: null, - fetchMeta: null, - isInvalidated: false, - status: hasData ? 'success' : 'pending', - fetchStatus: 'idle', - } -} - -export type { - QueryState, - FetchDirection, - FetchMeta, - FetchOptions, - QueryAction as Action, -} from '@tanstack/query-types/bindings' - -export type { FetchContext, QueryBehavior } +export { fetchState } from './queryState' diff --git a/packages/query-core/src/queryCache.ts b/packages/query-core/src/queryCache.ts index 3cd097549f1..00279784a57 100644 --- a/packages/query-core/src/queryCache.ts +++ b/packages/query-core/src/queryCache.ts @@ -2,25 +2,129 @@ import { notifyManager } from './notifyManager' import { Query } from './query' import { Subscribable } from './subscribable' import { hashKeyByOptions, matchQuery } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { QueryState } from './query' +import type { Action, QueryState } from './query' import type { QueryClient } from './queryClient' -import type { QueryRuntime } from './runtimeBinding' +import type { QueryObserver } from './queryObserver' import type { + CacheKeyConfig, DefaultError, + NotifyEvent, QueryKey, QueryOptions, WithRequired, } from './types' import type { QueryFilters } from './utils' -type QueryCacheConfig = Shared.QueryCacheConfig +// TYPES -type QueryCacheNotifyEvent = Shared.QueryCacheNotifyEvent +/** + * Global callbacks that fire for every query handled by a `QueryCache`, regardless of which + * component or observer triggered it. Unlike `QueryClient`'s `defaultOptions`, which a query can + * override, these callbacks are always called. Unlike `MutationCacheConfig`'s callbacks, these + * are fire-and-forget: their return value is not awaited before the query settles. + */ +export interface QueryCacheConfig { + /** + * Configures query key comparison and hashing globally. + * `equalityFn` compares individual values during partial matching and defaults to strict equality. + * `hashFn` hashes query keys and defaults to `hashKey`. + */ + queryKey?: CacheKeyConfig + /** Called when any query in the cache encounters an error. */ + onError?: ( + error: DefaultError, + query: Query, + ) => void + /** Called when any query in the cache is successful. */ + onSuccess?: (data: unknown, query: Query) => void + /** Called when any query in the cache is settled, either successfully or with an error. */ + onSettled?: ( + data: unknown | undefined, + error: DefaultError | null, + query: Query, + ) => void +} + +interface NotifyEventQueryAdded extends NotifyEvent { + type: 'added' + query: Query +} + +interface NotifyEventQueryRemoved extends NotifyEvent { + type: 'removed' + query: Query +} + +interface NotifyEventQueryUpdated extends NotifyEvent { + type: 'updated' + query: Query + action: Action +} + +interface NotifyEventQueryObserverAdded extends NotifyEvent { + type: 'observerAdded' + query: Query + observer: QueryObserver +} + +interface NotifyEventQueryObserverRemoved extends NotifyEvent { + type: 'observerRemoved' + query: Query + observer: QueryObserver +} + +interface NotifyEventQueryObserverResultsUpdated extends NotifyEvent { + type: 'observerResultsUpdated' + query: Query +} + +interface NotifyEventQueryObserverOptionsUpdated extends NotifyEvent { + type: 'observerOptionsUpdated' + query: Query + observer: QueryObserver +} -type QueryCacheListener = Shared.QueryCacheListener +/** + * The event passed to a `QueryCache` subscriber. Fired whenever a query is added or removed from + * the cache, its state is updated (e.g. via `query.setState` or `queryClient.removeQueries`), or + * one of its observers is added, removed, or has its results or options updated. + */ +export type QueryCacheNotifyEvent = + | NotifyEventQueryAdded + | NotifyEventQueryRemoved + | NotifyEventQueryUpdated + | NotifyEventQueryObserverAdded + | NotifyEventQueryObserverRemoved + | NotifyEventQueryObserverResultsUpdated + | NotifyEventQueryObserverOptionsUpdated -type QueryStore = Shared.QueryStore +type QueryCacheListener = (event: QueryCacheNotifyEvent) => void + +/** + * The store a `QueryCache` keeps its queries in, keyed by query hash. + */ +export interface QueryStore { + /** + * Returns whether a query with the given hash is stored. + */ + has: (queryHash: string) => boolean + /** + * Stores a query under its hash. + */ + set: (queryHash: string, query: Query) => void + /** + * Returns the query with the given hash, if any. + */ + get: (queryHash: string) => Query | undefined + /** + * Removes the query with the given hash. + */ + delete: (queryHash: string) => void + /** + * Returns an iterator over all stored queries. + */ + values: () => IterableIterator +} // CLASS @@ -296,5 +400,3 @@ export class QueryCache extends Subscribable { }) } } - -export type { QueryCacheConfig, QueryCacheNotifyEvent, QueryStore } diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index 481e1ca0c92..98b4771382c 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -12,10 +12,7 @@ import { resolveQueryValue, skipToken, } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { WithoutSkipToken } from '@tanstack/query-types/bindings' import type { QueryState } from './query' -import type { QueryRuntime } from './runtimeBinding' import type { CancelOptions, DefaultError, @@ -35,6 +32,7 @@ import type { QueryExecuteOptions, QueryKey, QueryObserverOptionsBase, + QueryOptions, RefetchOptions, RefetchQueryFilters, ResetOptions, @@ -42,9 +40,21 @@ import type { } from './types' import type { MutationFilters, QueryFilters, Updater } from './utils' -type QueryDefaults = Shared.QueryDefaults +type WithoutSkipToken = Omit & { + queryFn?: Exclude +} + +// TYPES -type MutationDefaults = Shared.MutationDefaults +interface QueryDefaults { + queryKey: QueryKey + defaultOptions: OmitKeyof, 'queryKey'> +} + +interface MutationDefaults { + mutationKey: MutationKey + defaultOptions: MutationOptions +} // CLASS diff --git a/packages/query-core/src/queryObserver.ts b/packages/query-core/src/queryObserver.ts index 76163eba849..aecb095aa7f 100644 --- a/packages/query-core/src/queryObserver.ts +++ b/packages/query-core/src/queryObserver.ts @@ -1,7 +1,7 @@ import { isServer as isServerEnvironment } from './environmentManager' import { focusManager } from './focusManager' import { notifyManager } from './notifyManager' -import { fetchState } from './query' +import { fetchState } from './queryState' import { Subscribable } from './subscribable' import { timeoutManager } from './timeoutManager' import { @@ -12,16 +12,8 @@ import { shallowEqualObjects, timeUntilStale, } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - ObserverFetchOptions, - ProjectionFailure, - QueryObserverListener, - QueryObserverResultReader, -} from '@tanstack/query-types/bindings' -import type { Query, QueryState } from './query' +import type { FetchOptions, Query, QueryState } from './query' import type { QueryClient } from './queryClient' -import type { QueryRuntime } from './runtimeBinding' import type { ManagedTimerId } from './timeoutManager' import type { DefaultError, @@ -29,40 +21,113 @@ import type { PlaceholderDataFunction, QueryKey, QueryObserverBaseResult, + QueryObserverOptions, QueryObserverOptionsBase, QueryObserverResult, + QueryOptions, RefetchOptions, } from './types' -type QueryObserverResultContext< +type QueryObserverListener = ( + result: QueryObserverResult, +) => void + +interface ObserverFetchOptions extends FetchOptions { + throwOnError?: boolean +} + +/** A cached view of an observer for one set of render options. */ +export interface QueryObserverResultReader { + /** Read the result, retaining its reference while all fields are unchanged. */ + getSnapshot: () => TResult + /** Apply this reader's options and reusable computation state after commit. */ + commit: () => void +} + +type ProjectionFailure = { + error: TError + errorUpdatedAt: number +} + +/** + * Selection and placeholder computation state shared by reads of the same result. + * @internal + */ +export interface QueryObserverResultContext< TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey, -> = Shared.QueryObserverResultContext< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey -> +> { + /** The memo key and failure of the most recent selection. */ + selection?: { + key: { + input: TQueryData + select: (data: TQueryData) => TData + structuralSharing: QueryOptions< + TQueryFnData, + TError, + TQueryData, + TQueryKey + >['structuralSharing'] + } + failure?: ProjectionFailure + } + /** The last successful selection, used if selection fails. */ + selected?: { + data: TData + query?: Query + } + /** The unselected placeholder or factory error. */ + placeholder?: { + key: { + placeholderData: QueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + >['placeholderData'] + structuralSharing: QueryOptions< + TQueryFnData, + TError, + TQueryData, + TQueryKey + >['structuralSharing'] + previousQuery: + | Query + | undefined + previousState: QueryState | undefined + previousOptions: + | QueryOptions + | undefined + } + sourceQuery?: Query + input: TQueryData | undefined + failure?: ProjectionFailure + } +} -type ObserverOptionsInput< +/** + * Options supplied to an observer by a caller or already resolved by the client. + * @internal + */ +export type ObserverOptionsInput< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> = Shared.ObserverOptionsInput< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey -> +> = + | QueryObserverOptions + | DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + > /** * A `QueryObserver` watches a single query in the `QueryCache` and computes a @@ -1041,7 +1106,3 @@ function isStale( query.isStaleByTime(resolveQueryValue(options.staleTime, query)) ) } - -export type { QueryObserverResultReader } from '@tanstack/query-types/bindings' - -export type { QueryObserverResultContext, ObserverOptionsInput } diff --git a/packages/query-core/src/queryState.ts b/packages/query-core/src/queryState.ts new file mode 100644 index 00000000000..cf8b318a0ce --- /dev/null +++ b/packages/query-core/src/queryState.ts @@ -0,0 +1,84 @@ +import { canFetch } from './retryer' +import type { QueryState } from './query' +import type { InitialDataFunction, QueryOptions } from './types' + +/** + * Returns the state changes applied when a query starts fetching. + * @param data - The query's current data. If it is `undefined`, the query is also reset to + * `'pending'` with no error. + * @param options - The query options, whose `networkMode` decides whether the query is `'fetching'` + * or `'paused'`. + * @returns The partial query state for a starting fetch. + */ +export function fetchState( + data: TData | undefined, + options: Pick, +) { + return { + fetchFailureCount: 0, + fetchFailureReason: null, + fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused', + ...(data === undefined && + ({ + error: null, + status: 'pending', + } as const)), + } as const +} + +/** + * Returns the state changes applied when a query receives data. + * @param data - The new data. + * @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to the current time. + * @returns The partial query state for a successful update. + */ +export function successState( + data: TData | undefined, + dataUpdatedAt?: number, +) { + return { + data, + dataUpdatedAt: dataUpdatedAt ?? Date.now(), + error: null, + isInvalidated: false, + status: 'success' as const, + } +} + +/** + * Returns the initial state of a query, based on its `initialData` and `initialDataUpdatedAt` + * options. + * @param options - Supplies the initial cache value and its update time. + * @returns The initial query state: `'success'` if `initialData` is set, otherwise `'pending'`. + */ +export function getDefaultQueryState( + options: Pick, 'initialData' | 'initialDataUpdatedAt'>, +): QueryState { + const data = + typeof options.initialData === 'function' + ? (options.initialData as InitialDataFunction)() + : options.initialData + + const hasData = data !== undefined + + const initialDataUpdatedAt = hasData + ? typeof options.initialDataUpdatedAt === 'function' + ? options.initialDataUpdatedAt() + : options.initialDataUpdatedAt + : 0 + + return { + data, + dataUpdateCount: 0, + dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0, + error: null, + errorUpdateCount: 0, + errorUpdatedAt: 0, + fetchFailureCount: 0, + fetchFailureReason: null, + fetchMeta: null, + isInvalidated: false, + status: hasData ? 'success' : 'pending', + fetchStatus: 'idle', + } +} diff --git a/packages/query-core/src/retryer.ts b/packages/query-core/src/retryer.ts index 5ac6a5eece1..3e7ad7bb771 100644 --- a/packages/query-core/src/retryer.ts +++ b/packages/query-core/src/retryer.ts @@ -2,13 +2,83 @@ import { isServer as isServerEnvironment } from './environmentManager' import { focusManager } from './focusManager' import { onlineManager } from './onlineManager' import { noop, sleep } from './utils' -import type { - Retryer, - RetryerConfig, - RetryerStatus, -} from '@tanstack/query-types/bindings' import type { CancelOptions, DefaultError, NetworkMode } from './types' +// TYPES + +interface RetryerConfig { + fn: () => TData | Promise + initialPromise?: Promise + onCancel?: (error: TError) => void + onFail?: (failureCount: number, error: TError) => void + onPause?: () => void + onContinue?: () => void + retry?: RetryValue + retryDelay?: RetryDelayValue + networkMode: NetworkMode | undefined + canRun: () => boolean +} + +/** + * Runs a function with retries, and can pause, continue, or cancel it. Queries and mutations use + * one for each fetch or execution. + */ +export interface Retryer { + /** + * The promise that resolves with the data, or rejects once retries are exhausted or it is + * cancelled. + */ + promise: Promise + /** + * Cancels the run, rejecting `promise` with a `CancelledError`. + */ + cancel: (cancelOptions?: CancelOptions) => void + /** + * Resumes a paused run, and returns `promise`. + */ + continue: () => Promise + /** + * Stops further retries. The current attempt still finishes. + */ + cancelRetry: () => void + /** + * Allows retries again after `cancelRetry`. + */ + continueRetry: () => void + /** + * Returns whether the run can start now, based on the network mode and `canRun`. + */ + canStart: () => boolean + /** + * Starts the run, or waits until it can start, and returns `promise`. + */ + start: () => Promise + /** + * Returns whether `promise` is still pending, resolved, or rejected. + */ + status: () => 'pending' | 'resolved' | 'rejected' +} + +type RetryerStatus = 'pending' | 'resolved' | 'rejected' + +/** @inline */ +export type RetryValue = boolean | number | ShouldRetryFunction + +/** @inline */ +type ShouldRetryFunction = ( + failureCount: number, + error: TError, +) => boolean + +/** @inline */ +export type RetryDelayValue = number | RetryDelayFunction + +/** @inline */ +type RetryDelayFunction = ( + failureCount: number, + error: TError, +) => number + /** * Applies exponential backoff with jitter. The base delay starts at 1 second * and doubles for each retry, up to 30 seconds. @@ -233,9 +303,3 @@ export function createRetryer( }, } } - -export type { - Retryer, - RetryValue, - RetryDelayValue, -} from '@tanstack/query-types/bindings' diff --git a/packages/query-core/src/runtimeBinding.ts b/packages/query-core/src/runtimeBinding.ts deleted file mode 100644 index 0f604c89738..00000000000 --- a/packages/query-core/src/runtimeBinding.ts +++ /dev/null @@ -1,42 +0,0 @@ -import type { RuntimeBinding } from '@tanstack/query-types/bindings' -import type { Mutation } from './mutation' -import type { MutationCache } from './mutationCache' -import type { MutationObserver } from './mutationObserver' -import type { Query } from './query' -import type { QueryCache } from './queryCache' -import type { QueryClient } from './queryClient' -import type { QueryObserver } from './queryObserver' - -/** Binds shared option and callback types to the concrete classes in this runtime. */ -interface QueryRuntime extends RuntimeBinding { - QueryClient: QueryClient - QueryCache: QueryCache - MutationCache: MutationCache - Query: Query< - this['queryFnData'], - this['error'], - this['data'], - this['queryKey'][0] - > - Mutation: Mutation< - this['data'], - this['error'], - this['variables'], - this['onMutateResult'] - > - QueryObserver: QueryObserver< - this['queryFnData'], - this['error'], - this['data'], - this['queryData'], - this['queryKey'][0] - > - MutationObserver: MutationObserver< - this['data'], - this['error'], - this['variables'], - this['onMutateResult'] - > -} - -export type { QueryRuntime } diff --git a/packages/query-core/src/streamedQuery.ts b/packages/query-core/src/streamedQuery.ts index 6efb1dbfcdd..6e43572f762 100644 --- a/packages/query-core/src/streamedQuery.ts +++ b/packages/query-core/src/streamedQuery.ts @@ -1,14 +1,53 @@ import { addConsumeAwareSignal, fetchSignal } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { QueryRuntime } from './runtimeBinding' -import type { OmitKeyof, QueryFunction, QueryKey } from './types' +import type { + OmitKeyof, + QueryFunction, + QueryFunctionContext, + QueryKey, +} from './types' import type { FetchSignalContext } from './utils' -type StreamedQueryParams< +type BaseStreamedQueryParams = { + /** Returns an `AsyncIterable` or a promise that resolves to one. */ + streamFn: ( + context: QueryFunctionContext, + ) => AsyncIterable | Promise> + /** + * Defines how refetches are handled. + * - `'reset'` (default): resets the query to its initial state before reading the stream. + * - `'append'`: appends new data to the existing data. + * - `'replace'`: writes all data to the cache once the stream ends. + */ + refetchMode?: 'append' | 'reset' | 'replace' +} + +type SimpleStreamedQueryParams< + TQueryFnData, + TQueryKey extends QueryKey, +> = BaseStreamedQueryParams & { + reducer?: never + initialValue?: never +} + +type ReducibleStreamedQueryParams< TQueryFnData, TData, TQueryKey extends QueryKey, -> = Shared.StreamedQueryParams +> = BaseStreamedQueryParams & { + /** + * Combines the accumulated data with the next chunk. Provide `initialValue` with a custom reducer. + */ + reducer: (acc: TData, chunk: TQueryFnData) => TData + /** + * The starting value for the reducer when there is no cached data or when + * `refetchMode` is `'replace'` during a refetch. + */ + initialValue: TData +} + +type StreamedQueryParams = + | SimpleStreamedQueryParams + | ReducibleStreamedQueryParams /** * Creates a query function that streams data from an `AsyncIterable`. diff --git a/packages/query-core/src/timeoutManager.ts b/packages/query-core/src/timeoutManager.ts index 44a50f32803..e4c259f36c7 100644 --- a/packages/query-core/src/timeoutManager.ts +++ b/packages/query-core/src/timeoutManager.ts @@ -1,9 +1,52 @@ -import type { - ManagedTimerId, - SystemTimerId, - TimeoutCallback, - TimeoutProvider, -} from '@tanstack/query-types/bindings' +/** + * {@link TimeoutManager} does not support passing arguments to the callback. + * + * `(_: void)` is the argument type inferred by TypeScript's default typings for + * `setTimeout(cb, number)`. + * If we don't accept a single void argument, then + * `new Promise(resolve => timeoutManager.setTimeout(resolve, N))` is a type error. + */ +export type TimeoutCallback = (_: void) => void + +/** + * Wrapping `setTimeout` is awkward from a typing perspective because platform + * typings may extend the return type of `setTimeout`. For example, NodeJS + * typings add `NodeJS.Timeout`; but a non-default `timeoutManager` may not be + * able to return such a type. + */ +export type ManagedTimerId = number | { [Symbol.toPrimitive]: () => number } + +/** + * Backend for timer functions. + * + * Timers are performance-sensitive: short-lived timers (delays under a few seconds) tend to be + * latency-sensitive, while long-lived ones may benefit more from coalescing — batching timers + * with similar deadlines together — which the default provider (backed by the platform's global + * `setTimeout`/`setInterval`) does not do. A custom provider can implement coalescing, and can + * also support delays longer than the ~24-day maximum of the global `setTimeout`. + */ +export type TimeoutProvider = + { + /** + * Schedules `callback` to run once after `delay` milliseconds, like the global `setTimeout`. + */ + readonly setTimeout: (callback: TimeoutCallback, delay: number) => TTimerId + /** + * Cancels a timeout scheduled with `setTimeout`. + */ + readonly clearTimeout: (timeoutId: TTimerId | undefined) => void + + /** + * Schedules `callback` to run every `delay` milliseconds, like the global `setInterval`. + */ + readonly setInterval: (callback: TimeoutCallback, delay: number) => TTimerId + /** + * Cancels an interval scheduled with `setInterval`. + */ + readonly clearInterval: (intervalId: TTimerId | undefined) => void + } + +type SystemTimerId = ReturnType export const defaultTimeoutProvider: TimeoutProvider = { // We need the wrapper function syntax below instead of direct references to @@ -203,9 +246,3 @@ export class TimeoutManager implements Omit { * Singleton instance of {@link TimeoutManager}, used throughout TanStack Query to schedule and cancel timers. */ export const timeoutManager = new TimeoutManager() - -export type { - TimeoutCallback, - ManagedTimerId, - TimeoutProvider, -} from '@tanstack/query-types/bindings' diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index d326387cc0e..113b83210cb 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -1,488 +1,2398 @@ -import type * as Shared from '@tanstack/query-types/bindings' +/* istanbul ignore file */ + +import type { DehydrateOptions, HydrateOptions } from './hydration' +import type { MutationState } from './mutation' +import type { MutationCache } from './mutationCache' +import type { Query } from './query' +import type { QueryCache } from './queryCache' +import type { QueryClient } from './queryClient' +import type { RetryDelayValue, RetryValue } from './retryer' import type { - DefaultError, - InfiniteData, - QueryKey, - dataTagErrorSymbol as dataTagErrorSymbolType, - dataTagSymbol as dataTagSymbolType, - UnsetMarker as unsetMarkerType, -} from '@tanstack/query-types/bindings' -import type { QueryRuntime } from './runtimeBinding' - -export const dataTagSymbol: dataTagSymbolType = Symbol.for( - '@tanstack/query/dataTagSymbol', -) as dataTagSymbolType + DefaultQueryFn, + QueryFilters, + QueryTypeFilter, + SkipToken, +} from './utils' + +/** + * Excludes `undefined` from `T`. Used where a value must be defined, such as the data type that a + * defined `initialData` resolves to. + */ +export type NonUndefinedGuard = T extends undefined ? never : T + +/** + * Like `Omit`, but applied to each member of a union separately, so each member keeps its own keys. + */ +export type DistributiveOmit< + TObject, + TKey extends keyof TObject, +> = TObject extends any ? Omit : never + +/** + * Like `Omit`, but by default (`'strictly'`) `TKey` must be a key of `TObject`, so omitting a key + * that doesn't exist is a type error. Pass `'safely'` to allow other keys too. + */ +export type OmitKeyof< + TObject, + TKey extends (TStrictly extends 'safely' + ? | keyof TObject + | (string & Record) + | (number & Record) + | (symbol & Record) + : keyof TObject), + TStrictly extends 'strictly' | 'safely' = 'strictly', +> = Omit + +/** + * Replaces the types of the properties of `TTargetA` that also exist in `TTargetB` with their types + * in `TTargetB`. Properties that only exist in `TTargetB` are not added. + */ +export type Override = { + [AKey in keyof TTargetA]: AKey extends keyof TTargetB + ? TTargetB[AKey] + : TTargetA[AKey] +} + +/** + * The interface to augment via declaration merging to override Query's default types repository-wide. + * Each field it declares replaces the default of the matching type: `defaultError` for {@link DefaultError}, + * `queryKey` for {@link QueryKey}, `mutationKey` for {@link MutationKey}, `queryMeta` for {@link QueryMeta} and + * `mutationMeta` for {@link MutationMeta}. Leave a field out to keep that type's default. + * Augment the module you install — `@tanstack/react-query`, `@tanstack/vue-query`, + * `@tanstack/solid-query`, `@tanstack/svelte-query`, `@tanstack/preact-query`, + * `@tanstack/angular-query` or `@tanstack/lit-query`. Augmenting `@tanstack/query-core` + * works too and covers every adapter at once. + * @example + * ```ts + * // Use the module you installed — here, the React adapter. + * declare module '@tanstack/react-query' { + * interface Register { + * defaultError: AxiosError + * } + * } + * ``` + */ +export interface Register { + // defaultError: Error + // queryMeta: Record + // mutationMeta: Record + // queryKey: ReadonlyArray + // mutationKey: ReadonlyArray +} + +/** + * The error type used wherever an error is not given an explicit type parameter. + * Defaults to `Error`; declare `defaultError` on {@link Register} to change it everywhere at once. + */ +export type DefaultError = Register extends { + defaultError: infer TError +} + ? TError + : Error + +/** + * The type of a query key — the serializable array that identifies a query in the cache. + * Defaults to `ReadonlyArray`; declare `queryKey` on {@link Register} to narrow it repository-wide. + */ +export type QueryKey = Register extends { + queryKey: infer TQueryKey +} + ? TQueryKey extends ReadonlyArray + ? TQueryKey + : TQueryKey extends Array + ? TQueryKey + : ReadonlyArray + : ReadonlyArray + +export const dataTagSymbol = Symbol() /** * The type of the `dataTagSymbol` key, under which a {@link DataTag} stores its data type. */ export type dataTagSymbol = typeof dataTagSymbol -export const dataTagErrorSymbol: dataTagErrorSymbolType = Symbol.for( - '@tanstack/query/dataTagErrorSymbol', -) as dataTagErrorSymbolType +export const dataTagErrorSymbol = Symbol() /** * The type of the `dataTagErrorSymbol` key, under which a {@link DataTag} stores its error type. */ export type dataTagErrorSymbol = typeof dataTagErrorSymbol -export const unsetMarker: unsetMarkerType = Symbol.for( - '@tanstack/query/unsetMarker', -) as unsetMarkerType +export const unsetMarker = Symbol() +/** + * The type of `unsetMarker`, the default error type of a {@link DataTag}. It marks that no error + * type was tagged. + */ +export type UnsetMarker = typeof unsetMarker +/** + * Matches any type that has been tagged with {@link DataTag}, whatever its data and error types. + */ +export type AnyDataTag = { + /** + * The data type the key was tagged with. + */ + [dataTagSymbol]: any + /** + * The error type the key was tagged with. + */ + [dataTagErrorSymbol]: any +} +/** + * Tags `TType` (usually a query key) with a data type and an optional error type, so that APIs that + * receive it, like `queryClient.getQueryData`, can infer them. A type that is already tagged is + * returned as is. + */ +export type DataTag< + TType, + TValue, + TError = UnsetMarker, +> = TType extends AnyDataTag + ? TType + : TType & { + [dataTagSymbol]: TValue + [dataTagErrorSymbol]: TError + } -type QueryFunction< +/** + * An object whose `queryKey` is tagged with {@link DataTag}, like the options returned by + * `queryOptions`. + */ +export type QueryKeyWithDataTag< + TQueryKey extends QueryKey = QueryKey, + TQueryFnData = unknown, + TError = DefaultError, +> = { + /** + * The query key, tagged with the query's data and error types. + */ + queryKey: DataTag +} + +/** + * The data type tagged on a query key by {@link DataTag}, or `TQueryFnData` if the key is not + * tagged. + */ +export type InferDataFromTag = + TTaggedQueryKey extends DataTag + ? TaggedValue + : TQueryFnData + +/** + * The error type tagged on a query key by {@link DataTag}, or `TError` if the key is not tagged or + * was tagged without an error type. + */ +export type InferErrorFromTag = + TTaggedQueryKey extends DataTag + ? TaggedError extends UnsetMarker + ? TError + : TaggedError + : TError + +/** @inline */ +export type QueryFunction< T = unknown, TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> = Shared.QueryFunction +> = (context: QueryFunctionContext) => T | Promise + +/** @inline */ +export type StaleTime = number | 'static' -type StaleTimeFunction< +/** @inline */ +export type StaleTimeFunction< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> = Shared.StaleTimeFunction< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey -> +> = + | StaleTime + | ((query: Query) => StaleTime) -type QueryBooleanOption< +/** @inline */ +export type QueryBooleanOption< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> = Shared.QueryBooleanOption< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey -> +> = + | boolean + | ((query: Query) => boolean) -type QueryPersister< +/** @inline */ +export type QueryPersister< T = unknown, TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> = Shared.QueryPersister +> = [TPageParam] extends [never] + ? ( + queryFn: QueryFunction, + context: QueryFunctionContext, + query: Query, + ) => T | Promise + : ( + queryFn: QueryFunction, + context: QueryFunctionContext, + query: Query, + ) => T | Promise -type QueryFunctionContext< +/** + * The object passed to `queryFn`: the `QueryClient`, the `queryKey`, an `AbortSignal` that aborts + * when the query is cancelled, the query's `meta`, and for infinite queries the `pageParam` of the + * page being fetched. + */ +export type QueryFunctionContext< TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> = Shared.QueryFunctionContext +> = [TPageParam] extends [never] + ? { + client: QueryClient + queryKey: TQueryKey + signal: AbortSignal + meta: QueryMeta | undefined + pageParam?: unknown + } + : { + client: QueryClient + queryKey: TQueryKey + signal: AbortSignal + pageParam: TPageParam + meta: QueryMeta | undefined + } -type PlaceholderDataFunction< +/** @inline */ +export type InitialDataFunction = () => T | undefined + +// oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes every function-like value, including constructors, from the value branch +type NonFunctionGuard = T extends Function ? never : T + +/** @inline */ +export type PlaceholderDataFunction< TQueryFnData = unknown, TError = DefaultError, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> = Shared.PlaceholderDataFunction< - QueryRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey -> +> = ( + previousData: TQueryData | undefined, + previousQuery: Query | undefined, +) => TQueryData | undefined + +/** + * The `placeholderData` function of a query in `useQueries` and its counterparts. Unlike + * {@link PlaceholderDataFunction}, it receives no previous data or query, because the number of + * queries can differ between renders. + */ +export type QueriesPlaceholderDataFunction = ( + previousData: undefined, + previousQuery: undefined, +) => TQueryData | undefined + +/** @inline */ +export type EqualityFn = (a: unknown, b: unknown) => boolean + +/** @inline */ +export type CacheKeyHashFunction< + TCacheKey extends ReadonlyArray = ReadonlyArray, +> = (cacheKey: TCacheKey) => string + +/** Configures the comparison and hashing of query or mutation keys for a cache. */ +export interface CacheKeyConfig< + TCacheKey extends ReadonlyArray = ReadonlyArray, +> { + /** + * Function used to compare values while partially matching keys. + * Defaults to strict equality. + */ + equalityFn?: EqualityFn + /** + * Function used to hash keys globally. + */ + hashFn?: CacheKeyHashFunction +} + +/** @inline */ +export type GetPreviousPageParamFunction = ( + firstPage: TQueryFnData, + allPages: Array, + firstPageParam: TPageParam, + allPageParams: Array, +) => TPageParam | undefined | null + +/** @inline */ +export type GetNextPageParamFunction = ( + lastPage: TQueryFnData, + allPages: Array, + lastPageParam: TPageParam, + allPageParams: Array, +) => TPageParam | undefined | null + +/** + * The data shape of an infinite query: every page fetched so far, plus the page param each one was fetched with. + * `pages` and `pageParams` are index-aligned — `pageParams[i]` is the param that produced `pages[i]`. + */ +export interface InfiniteData { + /** + * The data of every page fetched so far, in order. + */ + pages: Array + /** + * The page param each page was fetched with, aligned by index with `pages`. + */ + pageParams: Array +} + +/** + * The type of the `meta` object that can be attached to a query and read back from `queryFn`, callbacks and + * cache-level handlers. Defaults to `Record`; declare `queryMeta` on {@link Register} to narrow it. + */ +export type QueryMeta = Register extends { + queryMeta: infer TQueryMeta +} + ? TQueryMeta extends Record + ? TQueryMeta + : Record + : Record + +/** @inline */ +export type NetworkMode = 'online' | 'always' | 'offlineFirst' + +/** @inline */ +export type NotifyOnChangeProps = 'all' | 'none' -type QueryOptions< +/** + * The options of a query itself — its `queryKey`, `queryFn`, retries, `gcTime`, `initialData`, + * `meta`, and so on — shared by observers and the `QueryClient` methods that fetch queries. + */ +export interface QueryOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> = Shared.QueryOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> +> { + /** + * If `false`, failed queries will not retry by default. + * If `true`, failed queries will retry infinitely. + * If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. + * If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. + * + * Defaults to `3` on the client and `0` on the server. + */ + retry?: RetryValue + /** + * The delay in milliseconds before a retry. Use a number for a fixed delay or a function that receives + * the failure count and error and returns the delay. The count starts at 0 for the first retry. + * + * A function like `attempt => Math.min(1000 * 2 ** attempt, 30000)` applies exponential + * backoff. + * + * A function like `attempt => attempt * 1000` applies linear backoff. + * + * By default, each retry waits a random duration from 80% to 100% of the base delay. + * The base delay starts at 1 second and doubles for each retry, up to 30 seconds. + */ + retryDelay?: RetryDelayValue + /** + * Controls whether a query is allowed to run based on the current network connectivity. + * @defaultValue 'online' + * @see [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. + */ + networkMode?: NetworkMode + /** + * The time in milliseconds that unused/inactive cache data remains in memory. + * When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. + * When different garbage collection times are specified, the longest one will be used. + * Setting it to `Infinity` will disable garbage collection. + * + * Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. + * + * Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see + * `timeoutManager.setTimeoutProvider` for a workaround. + */ + gcTime?: number + /** + * The function that the query will use to request data. + * Pass `defaultQueryFn` to use the function configured in the client's query defaults. + * Pass `skipToken` to disable a query without a function where supported. + * Receives a {@link QueryFunctionContext}. + * Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. + */ + queryFn?: + | QueryFunction + | SkipToken + | DefaultQueryFn + /** + * This option can be used to persist the result of a query to an external storage, bypassing the need to actually + * call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. + */ + persister?: QueryPersister, TPageParam> + /** + * The cache key. If omitted, the query cache computes it from `queryKey` + * using its configured `hashFn` or the default hash function. + */ + queryHash?: string + /** + * The query key to use for this query. + * + * The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) + * for more information. + * + * The query will automatically update when this key changes (as long as `enabled` is not set to `false`). + */ + queryKey?: TQueryKey + /** + * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been + * created or cached yet). + * If set to a function, the function will be called **once** during the shared/root query initialization, and be + * expected to synchronously return the initial data. + * Initial data is considered stale by default unless a `staleTime` has been set. + * `initialData` **is persisted** to the cache. + */ + initialData?: TData | InitialDataFunction + /** + * If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. + */ + initialDataUpdatedAt?: number | (() => number | undefined) + /** + * Set this to `false` to disable structural sharing between query results. + * Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. + * @defaultValue true + */ + structuralSharing?: + | boolean + | ((oldData: unknown | undefined, newData: unknown) => unknown) + /** @internal */ + _defaulted?: boolean + /** @internal */ + _type?: 'infinite' + /** + * Additional payload to be stored on each query. + * Use this property to pass information that can be used in other places. + */ + meta?: QueryMeta + /** + * Maximum number of pages to store in the data of an infinite query. + */ + maxPages?: number +} + +/** + * Holds the `initialPageParam` option that every infinite query requires. + */ +export interface InitialPageParam { + /** + * The page param to start from when an infinite query has no pages yet. + * It is passed to `queryFn` as `pageParam` for the first page; every page after that gets the + * value returned by `getNextPageParam` or `getPreviousPageParam`. + * It only applies while the query has no pages: once a first page exists, refetching starts from + * that page's own param instead. + */ + initialPageParam: TPageParam +} -type ThrowOnError< +/** + * The page param options of an infinite query: `initialPageParam`, and the `getNextPageParam` and + * `getPreviousPageParam` functions that compute the params of the pages around it. + */ +export interface InfiniteQueryPageParamsOptions< + TQueryFnData = unknown, + TPageParam = unknown, +> extends InitialPageParam { + /** + * This function can be set to automatically get the previous cursor for infinite queries. + * The result will also be used to determine the value of `hasPreviousPage`. + */ + getPreviousPageParam?: GetPreviousPageParamFunction + /** + * This function can be set to automatically get the next cursor for infinite queries. + * The result will also be used to determine the value of `hasNextPage`. + */ + getNextPageParam: GetNextPageParamFunction +} + +/** @inline */ +export type ThrowOnError< TQueryFnData, TError, TQueryData, TQueryKey extends QueryKey, -> = Shared.ThrowOnError< - QueryRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey -> +> = + | boolean + | (( + error: TError, + query: Query, + ) => boolean) -type QueryObserverOptionsBase< +/** + * Shared options for default resolution and resolved observer state. + * @internal + */ +export interface QueryObserverOptionsBase< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> = Shared.QueryObserverOptionsBase< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam -> +> extends WithRequired< + QueryOptions, + 'queryKey' +> { + /** + * Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. + * To refetch the query, use the `refetch` method returned from the `useQuery` instance. + * Accepts a boolean or function that returns a boolean. + * @defaultValue true + */ + enabled?: QueryBooleanOption + /** + * The time in milliseconds after data is considered stale. + * If set to `Infinity`, the data will never be considered stale. + * If set to `'static'`, the data will never be considered stale. + * If set to a function, the function will be executed with the query to compute a `staleTime`. + * @defaultValue 0 + */ + staleTime?: StaleTimeFunction + /** + * If set to a number, the query will continuously refetch at this frequency in milliseconds. + * If set to a function, the function will be executed with the latest data and query to compute a frequency + * @defaultValue false + */ + refetchInterval?: + | number + | false + | (( + query: Query, + ) => number | false | undefined) + /** + * If set to `true`, the query will continue to refetch while their tab/window is in the background. + * @defaultValue false + */ + refetchIntervalInBackground?: boolean + /** + * If set to `true`, the query will refetch on window focus if the data is stale. + * If set to `false`, the query will not refetch on window focus. + * If set to `'always'`, the query will always refetch on window focus (except when `staleTime: 'static'` is used). + * If set to a function, the function will be executed with the latest data and query to compute the value. + * @defaultValue true + */ + refetchOnWindowFocus?: + | boolean + | 'always' + | (( + query: Query, + ) => boolean | 'always') + /** + * If set to `true`, the query will refetch on reconnect if the data is stale. + * If set to `false`, the query will not refetch on reconnect. + * If set to `'always'`, the query will always refetch on reconnect (except when `staleTime: 'static'` is used). + * If set to a function, the function will be executed with the latest data and query to compute the value. + * + * Defaults to `true` unless `networkMode` is `'always'`. + */ + refetchOnReconnect?: + | boolean + | 'always' + | (( + query: Query, + ) => boolean | 'always') + /** + * If set to `true`, the query will refetch on mount if the data is stale. + * If set to `false`, will disable additional instances of a query to trigger background refetch. + * If set to `'always'`, the query will always refetch on mount (except when `staleTime: 'static'` is used). + * If set to a function, the function will be executed with the latest data and query to compute the value + * @defaultValue true + */ + refetchOnMount?: + | boolean + | 'always' + | (( + query: Query, + ) => boolean | 'always') + /** + * If set to `false`, the query will not be retried on mount if it contains an error. + * If set to a function, the function will be executed with the query to compute the value. + * @defaultValue true + */ + retryOnMount?: QueryBooleanOption + /** + * Controls when changes to the query result notify this observer's listeners. + * Use `'all'` to notify on every result change. + * Use `'none'` to suppress notifications while the query remains subscribed and can fetch. + * If `throwOnError` is set, changes to `error` still notify listeners. + * + * By default, adapters that track property reads notify listeners when a tracked property changes. + * If no properties are tracked, every result change notifies listeners. + */ + notifyOnChangeProps?: NotifyOnChangeProps + /** + * Whether errors should be thrown instead of setting the `error` property. + * If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. + * If set to `false` and `suspense` is `false`, errors are returned as state. + * If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`). + * @defaultValue false + */ + throwOnError?: ThrowOnError + /** + * This option can be used to transform or select a part of the data returned by the query function. It affects + * the returned `data` value, but does not affect what gets stored in the query cache. + * The `select` function will only run if `data` changed, or if the reference to the `select` function itself + * changes. To optimize, memoize the function so its reference stays stable across calls. + * If the selector throws, the observer reports the error and can keep the last valid selection. + */ + select?: (data: TQueryData) => TData + /** + * If set to `true`, the query will suspend when `status === 'pending'` + * and throw errors when `status === 'error'`. + * @defaultValue false + */ + suspense?: boolean + /** + * If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. + * If the placeholder function throws, the observer reports the error with no data. The query state in the cache is unaffected. + */ + placeholderData?: + | NonFunctionGuard + | PlaceholderDataFunction< + NonFunctionGuard, + TError, + NonFunctionGuard, + TQueryKey + > + + /** @internal */ + _optimisticResults?: 'optimistic' | 'isRestoring' +} -type QueryObserverOptions< +/** + * The options of a `QueryObserver`, and of the hooks built on it like `useQuery`: the + * {@link QueryOptions} of the query, plus options that control the observer, such as `enabled`, + * `staleTime`, `refetchInterval`, `select`, and `placeholderData`. + * Pass a `queryFn` or use `defaultQueryFn` to select the client defaults. + */ +export interface QueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> = Shared.QueryObserverOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam -> +> extends WithRequired< + QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + 'queryFn' +> {} -type DefaultedQueryObserverOptions< +/** + * Makes the `TKey` properties of `TTarget` required and non-nullable. + */ +export type WithRequired = TTarget & { + [_ in TKey]: {} +} + +/** + * The {@link QueryObserverOptions} after `QueryClient#defaultQueryOptions` has applied the + * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. + */ +export type DefaultedQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> = Shared.DefaultedQueryObserverOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam +> = WithRequired< + QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + 'throwOnError' | 'refetchOnReconnect' | 'queryHash' > -type InfiniteQueryObserverOptions< +/** + * The options of an `InfiniteQueryObserver`: {@link QueryObserverOptions} whose query data is + * {@link InfiniteData}, plus the page param options. + */ +export interface InfiniteQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown, -> = Shared.InfiniteQueryObserverOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam > + extends + QueryObserverOptions< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey, + TPageParam + >, + InfiniteQueryPageParamsOptions {} -type DefaultedInfiniteQueryObserverOptions< +/** + * The {@link InfiniteQueryObserverOptions} after `QueryClient#defaultQueryOptions` has applied the + * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. + */ +export type DefaultedInfiniteQueryObserverOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown, -> = Shared.DefaultedInfiniteQueryObserverOptions< - QueryRuntime, +> = DefaultedQueryObserverOptions< TQueryFnData, TError, TData, + InfiniteData, TQueryKey, TPageParam -> +> & + InfiniteQueryPageParamsOptions -type QueryExecuteOptions< +/** + * The options of `queryClient.query`: the {@link QueryOptions} of the query, plus a `staleTime` + * that decides whether cached data is returned instead of fetching, and a `select` that only + * transforms the value the call resolves with. + */ +export interface QueryExecuteOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = never, -> = Shared.QueryExecuteOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam -> +> extends WithRequired< + QueryOptions, + 'queryKey' +> { + /** + * Not allowed here, since `initialPageParam` only applies to infinite queries. + */ + initialPageParam?: never + /** + * This option can be used to transform or select a part of the data returned by the query function. It affects + * the value this call resolves with, but does not affect what gets stored in the query cache. + */ + select?: (data: TQueryData) => TData + /** + * The time in milliseconds after data is considered stale. + * If the data is fresh it will be returned from the cache. + */ + staleTime?: StaleTimeFunction +} -type InfiniteQueryExecuteOptions< +type InfiniteQueryFetchPageOptions = Pick< + InfiniteQueryPageParamsOptions, + 'initialPageParam' | 'getNextPageParam' +> & { + /** + * The number of pages to fetch. Defaults to the number of cached pages, + * or one page if the cache has no pages. + */ + pages?: number +} + +/** + * The options of `queryClient.infiniteQuery`. Extends {@link QueryExecuteOptions} + * with `initialPageParam`, `getNextPageParam`, and the optional `pages` count. + */ +export type InfiniteQueryExecuteOptions< TQueryFnData = unknown, TError = DefaultError, TData = InfiniteData, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown, -> = Shared.InfiniteQueryExecuteOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> +> = Omit< + QueryExecuteOptions< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey, + TPageParam + >, + 'initialPageParam' +> & + InfiniteQueryFetchPageOptions + +/** + * Options shared by the `QueryClient` and observer methods that refetch queries, controlling + * whether a failed refetch makes the returned promise reject. + */ +export interface ResultOptions { + /** + * If set to `true`, the method throws if any of the underlying query refetch tasks fail. + * If set to `false`, failed refetches are swallowed and not surfaced to the caller. + * @defaultValue false + */ + throwOnError?: boolean +} + +/** + * Options of the methods that refetch queries, like `refetch` and `queryClient.refetchQueries`. + */ +export interface RefetchOptions extends ResultOptions { + /** + * If set to `true`, a currently running request will be cancelled before a new request is made + * + * If set to `false`, no refetch will be made if there is already a request running. + * @defaultValue true + */ + cancelRefetch?: boolean +} -type InvalidateQueryFilters = - Shared.InvalidateQueryFilters +/** + * The filters of `queryClient.invalidateQueries`: the {@link QueryFilters} that select the queries + * to invalidate, plus `refetchType` to choose which of them are refetched. + */ +export interface InvalidateQueryFilters< + TQueryKey extends QueryKey = QueryKey, +> extends QueryFilters { + /** + * Controls which of the matched (now-invalidated) queries are refetched in the background. + * + * - `'active'`: only queries with at least one active observer are refetched. + * - `'inactive'`: only queries with no active observer are refetched. + * - `'all'`: every matched query is refetched, active or not. + * - `'none'`: no query is refetched; matched queries are only marked as invalidated. + * @defaultValue 'active' + */ + refetchType?: QueryTypeFilter | 'none' +} -type RefetchQueryFilters = - Shared.RefetchQueryFilters +/** + * The filters of `queryClient.refetchQueries`, which select the queries to refetch. + */ +export interface RefetchQueryFilters< + TQueryKey extends QueryKey = QueryKey, +> extends QueryFilters {} -type MutationFunctionContext = Shared.MutationFunctionContext +/** + * Options of `queryClient.invalidateQueries`, applied to the refetch that follows the invalidation. + */ +export interface InvalidateOptions extends RefetchOptions {} +/** + * Options of `queryClient.resetQueries`, applied to the refetch of the active queries after the + * reset. + */ +export interface ResetOptions extends RefetchOptions {} -type MutationFunction< +/** + * Options of `fetchNextPage` on an infinite query result. + */ +export interface FetchNextPageOptions extends ResultOptions { + /** + * If set to `true`, calling `fetchNextPage` repeatedly will invoke `queryFn` every time, + * whether the previous invocation has resolved or not. Also, the result from previous invocations will be ignored. + * + * If set to `false`, calling `fetchNextPage` repeatedly won't have any effect until the first invocation has resolved. + * @defaultValue true + */ + cancelRefetch?: boolean +} + +/** + * Options of `fetchPreviousPage` on an infinite query result. + */ +export interface FetchPreviousPageOptions extends ResultOptions { + /** + * If set to `true`, calling `fetchPreviousPage` repeatedly will invoke `queryFn` every time, + * whether the previous invocation has resolved or not. Also, the result from previous invocations will be ignored. + * + * If set to `false`, calling `fetchPreviousPage` repeatedly won't have any effect until the first invocation has resolved. + * @defaultValue true + */ + cancelRefetch?: boolean +} + +/** @inline */ +export type QueryStatus = 'pending' | 'error' | 'success' +/** @inline */ +export type FetchStatus = 'fetching' | 'paused' | 'idle' + +/** + * The properties shared by every state of a query result, like `data`, `error`, `status`, the + * `is*` flags, and `refetch`. Each `QueryObserver*Result` narrows them for one state. + */ +export interface QueryObserverBaseResult< TData = unknown, - TVariables = unknown, -> = Shared.MutationFunction + TError = DefaultError, +> { + /** + * The last successfully resolved data for the query. + */ + data: TData | undefined + /** + * The timestamp for when the query most recently returned the `status` as `"success"`. + */ + dataUpdatedAt: number + /** + * The error object for the query, if an error was thrown. + * - Defaults to `null`. + */ + error: TError | null + /** + * The timestamp for when the query most recently returned the `status` as `"error"`. + */ + errorUpdatedAt: number + /** + * The failure count for the query. + * - Incremented every time the query fails. + * - Reset to `0` when the query succeeds. + */ + failureCount: number + /** + * The failure reason for the query retry. + * - Reset to `null` when the query succeeds. + */ + failureReason: TError | null + /** + * The sum of all errors. + */ + errorUpdateCount: number + /** + * A derived boolean from the `status` variable, provided for convenience. + * - `true` if the query has an error from a fetch that failed after its retries, or if `select` threw. + */ + isError: boolean + /** + * Will be `true` if the query has been fetched. + */ + isFetched: boolean + /** + * Will be `true` if the query has been fetched after the component mounted. + * - This property can be used to not show any previously cached data. + */ + isFetchedAfterMount: boolean + /** + * A derived boolean from the `fetchStatus` variable, provided for convenience. + * - `true` whenever the `queryFn` is executing, which includes initial `pending` as well as background refetch. + */ + isFetching: boolean + /** + * Is `true` whenever the first fetch for a query is in-flight. + * - Is the same as `isFetching && isPending`. + */ + isLoading: boolean + /** + * Will be `true` if the query has no cached data, no data from `placeholderData` and no error. + */ + isPending: boolean + /** + * Will be `true` if the query has an error and no data to display. + */ + isLoadingError: boolean + /** + * A derived boolean from the `fetchStatus` variable, provided for convenience. + * - The query wanted to fetch, but has been `paused`. + */ + isPaused: boolean + /** + * Will be `true` if the data shown is the placeholder data. + */ + isPlaceholderData: boolean + /** + * Will be `true` if the query has an error and still has data to display (for infinite queries, not after a failed page fetch). + */ + isRefetchError: boolean + /** + * Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`. + * - Is the same as `isFetching && !isPending`. + */ + isRefetching: boolean + /** + * Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. + */ + isStale: boolean + /** + * A derived boolean from the `status` variable, provided for convenience. + * - `true` if the query has cached data or data from `placeholderData`, and no error. + */ + isSuccess: boolean + /** + * `true` if this observer is enabled, `false` otherwise. + */ + isEnabled: boolean + /** + * A function to manually refetch the query. + */ + refetch: ( + options?: RefetchOptions, + ) => Promise> + /** + * The status of the query. + * - Will be: + * - `error` if the query has an error from a fetch that failed after its retries, or if `select` threw. + * - `success` if the query has cached data (even if `select` returns `undefined`) or data from `placeholderData`, and no error. + * - `pending` otherwise, since the query has no cached data, no data from `placeholderData` and no error. + */ + status: QueryStatus + /** + * The fetch status of the query. + * - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. + * - `paused`: The query wanted to fetch, but has been `paused`. + * - `idle`: The query is not fetching. + * - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. + */ + fetchStatus: FetchStatus +} -type MutationOptions< +/** + * A query result in the `pending` state: the query has no data yet. + */ +export interface QueryObserverPendingResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * `undefined`, since the query has no data yet. + */ + data: undefined + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `true`, since the query has no cached data, no data from `placeholderData` and no error. + */ + isPending: true + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. + */ + status: 'pending' +} + +/** + * A query result in the `pending` state while the first fetch is in flight, so `isLoading` is + * `true`. + */ +export interface QueryObserverLoadingResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * `undefined`, since the query has no data yet. + */ + data: undefined + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `true`, since the query has no cached data, no data from `placeholderData` and no error. + */ + isPending: true + /** + * `true`, since the first fetch is in flight. + */ + isLoading: true + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. + */ + status: 'pending' +} + +/** + * A query result in the `error` state with no data to display, since a fetch or `select` failed. + */ +export interface QueryObserverLoadingErrorResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * `undefined`, since there was no data to display when a fetch or `select` failed. + */ + data: undefined + /** + * The error the fetch or `select` failed with. + */ + error: TError + /** + * `true`, since the query is in the `error` state. + */ + isError: true + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `true`, since the query has an error and no data to display. + */ + isLoadingError: true + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'error'`, since a fetch failed after its retries or `select` threw. + */ + status: 'error' +} + +/** + * A query result in the `error` state that keeps the data from before a fetch or `select` failed. + */ +export interface QueryObserverRefetchErrorResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * The data from before the fetch or `select` failed, which is kept. + */ + data: TData + /** + * The error the fetch or `select` failed with. + */ + error: TError + /** + * `true`, since the query is in the `error` state. + */ + isError: true + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `true`, since the query has an error and still has data to display. + */ + isRefetchError: true + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'error'`, since a fetch failed after its retries or `select` threw. + */ + status: 'error' +} + +/** + * A query result in the `success` state with data from the cache. + */ +export interface QueryObserverSuccessResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * The last successfully resolved data for the query. + */ + data: TData + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `true`, since the query is in the `success` state. + */ + isSuccess: true + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'success'`, since the query has cached data and no error from a fetch or from + * `select`. + */ + status: 'success' +} + +/** + * A query result in the `success` state that shows `placeholderData` while the query has no data + * yet. + */ +export interface QueryObserverPlaceholderResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * The `placeholderData` shown while the query has no data yet. + */ + data: TData + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `true`, since the query is in the `success` state. + */ + isSuccess: true + /** + * `true`, since the data shown is the `placeholderData`. + */ + isPlaceholderData: true + /** + * `'success'`, since the query shows `placeholderData` and has no error from a fetch or + * from `select`. + */ + status: 'success' +} + +/** + * A query result that always has `data`: the success and refetch error states. + */ +export type DefinedQueryObserverResult< + TData = unknown, + TError = DefaultError, +> = + | QueryObserverRefetchErrorResult + | QueryObserverSuccessResult + +/** + * The result of a `QueryObserver`, and of the hooks built on it like `useQuery`. Narrow it by + * `status` or the `is*` flags to get the type of each state. + */ +export type QueryObserverResult = + | DefinedQueryObserverResult + | QueryObserverLoadingErrorResult + | QueryObserverLoadingResult + | QueryObserverPendingResult + | QueryObserverPlaceholderResult + +/** + * The properties shared by every state of an infinite query result: those of + * {@link QueryObserverBaseResult}, plus `fetchNextPage`, `fetchPreviousPage`, and the flags about + * them, like `hasNextPage` and `isFetchingNextPage`. + */ +export interface InfiniteQueryObserverBaseResult< + TData = unknown, + TError = DefaultError, +> extends QueryObserverBaseResult { + /** + * This function allows you to fetch the next "page" of results. + */ + fetchNextPage: ( + options?: FetchNextPageOptions, + ) => Promise> + /** + * This function allows you to fetch the previous "page" of results. + */ + fetchPreviousPage: ( + options?: FetchPreviousPageOptions, + ) => Promise> + /** + * Will be `true` if there is a next page to be fetched (known via the `getNextPageParam` option). + */ + hasNextPage: boolean + /** + * Will be `true` if there is a previous page to be fetched (known via the `getPreviousPageParam` option). + */ + hasPreviousPage: boolean + /** + * Will be `true` if the query failed while fetching the next page. + */ + isFetchNextPageError: boolean + /** + * Will be `true` while fetching the next page with `fetchNextPage`. + */ + isFetchingNextPage: boolean + /** + * Will be `true` if the query failed while fetching the previous page. + */ + isFetchPreviousPageError: boolean + /** + * Will be `true` while fetching the previous page with `fetchPreviousPage`. + */ + isFetchingPreviousPage: boolean +} + +/** + * An infinite query result in the `pending` state: the query has no data yet. + */ +export interface InfiniteQueryObserverPendingResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * `undefined`, since the query has no data yet. + */ + data: undefined + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `true`, since the query has no cached data, no data from `placeholderData` and no error. + */ + isPending: true + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `false`, since fetching the next page didn't fail. + */ + isFetchNextPageError: false + /** + * `false`, since fetching the previous page didn't fail. + */ + isFetchPreviousPageError: false + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. + */ + status: 'pending' +} + +/** + * An infinite query result in the `pending` state while the first fetch is in flight, so + * `isLoading` is `true`. + */ +export interface InfiniteQueryObserverLoadingResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * `undefined`, since the query has no data yet. + */ + data: undefined + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `true`, since the query has no cached data, no data from `placeholderData` and no error. + */ + isPending: true + /** + * `true`, since the first fetch is in flight. + */ + isLoading: true + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `false`, since fetching the next page didn't fail. + */ + isFetchNextPageError: false + /** + * `false`, since fetching the previous page didn't fail. + */ + isFetchPreviousPageError: false + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. + */ + status: 'pending' +} + +/** + * An infinite query result in the `error` state with no data to display, since a fetch or `select` failed. + */ +export interface InfiniteQueryObserverLoadingErrorResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * `undefined`, since there was no data to display when a fetch or `select` failed. + */ + data: undefined + /** + * The error the fetch or `select` failed with. + */ + error: TError + /** + * `true`, since the query is in the `error` state. + */ + isError: true + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `true`, since the query has an error and no data to display. + */ + isLoadingError: true + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `false`, since fetching the next page didn't fail. + */ + isFetchNextPageError: false + /** + * `false`, since fetching the previous page didn't fail. + */ + isFetchPreviousPageError: false + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'error'`, since a fetch failed after its retries or `select` threw. + */ + status: 'error' +} + +/** + * An infinite query result in the `error` state that keeps the data from before a fetch or `select` + * failed. + */ +export interface InfiniteQueryObserverRefetchErrorResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * The data from before the fetch or `select` failed, which is kept. + */ + data: TData + /** + * The error the fetch or `select` failed with. + */ + error: TError + /** + * `true`, since the query is in the `error` state. + */ + isError: true + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `true`, since the query has an error, still has data to display, and didn't fail fetching a page. + */ + isRefetchError: true + /** + * `false`, since the query isn't in the `success` state. + */ + isSuccess: false + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'error'`, since a fetch failed after its retries or `select` threw. + */ + status: 'error' +} + +/** + * An infinite query result in the `success` state with data from the cache. + */ +export interface InfiniteQueryObserverSuccessResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * The last successfully resolved data for the query. + */ + data: TData + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `false`, since fetching the next page didn't fail. + */ + isFetchNextPageError: false + /** + * `false`, since fetching the previous page didn't fail. + */ + isFetchPreviousPageError: false + /** + * `true`, since the query is in the `success` state. + */ + isSuccess: true + /** + * `false`, since the data shown isn't the `placeholderData`. + */ + isPlaceholderData: false + /** + * `'success'`, since the query has cached data and no error from a fetch or from + * `select`. + */ + status: 'success' +} + +/** + * An infinite query result in the `success` state that shows `placeholderData` while the query has + * no data yet. + */ +export interface InfiniteQueryObserverPlaceholderResult< + TData = unknown, + TError = DefaultError, +> extends InfiniteQueryObserverBaseResult { + /** + * The `placeholderData` shown while the query has no data yet. + */ + data: TData + /** + * `false`, since the query isn't in the `error` state. + */ + isError: false + /** + * `null`, since the query isn't in the `error` state. + */ + error: null + /** + * `false`, since the query has cached data, data from `placeholderData` or an error. + */ + isPending: false + /** + * `false`, since the first fetch isn't in flight. + */ + isLoading: false + /** + * `false`, since the query didn't fail while fetching for the first time. + */ + isLoadingError: false + /** + * `false`, since the query didn't fail while refetching. + */ + isRefetchError: false + /** + * `true`, since the query is in the `success` state. + */ + isSuccess: true + /** + * `true`, since the data shown is the `placeholderData`. + */ + isPlaceholderData: true + /** + * `false`, since fetching the next page didn't fail. + */ + isFetchNextPageError: false + /** + * `false`, since fetching the previous page didn't fail. + */ + isFetchPreviousPageError: false + /** + * `'success'`, since the query shows `placeholderData` and has no error from a fetch or + * from `select`. + */ + status: 'success' +} + +/** + * An infinite query result that always has `data`: the success and refetch error states. + */ +export type DefinedInfiniteQueryObserverResult< + TData = unknown, + TError = DefaultError, +> = + | InfiniteQueryObserverRefetchErrorResult + | InfiniteQueryObserverSuccessResult + +/** + * The result of an `InfiniteQueryObserver`, and of the hooks built on it like `useInfiniteQuery`. + * Narrow it by `status` or the `is*` flags to get the type of each state. + */ +export type InfiniteQueryObserverResult< + TData = unknown, + TError = DefaultError, +> = + | DefinedInfiniteQueryObserverResult + | InfiniteQueryObserverLoadingErrorResult + | InfiniteQueryObserverLoadingResult + | InfiniteQueryObserverPendingResult + | InfiniteQueryObserverPlaceholderResult + +/** + * The type of a mutation key — the serializable array used to identify and filter mutations. + * Defaults to `ReadonlyArray`; declare `mutationKey` on {@link Register} to narrow it repository-wide. + */ +export type MutationKey = Register extends { + mutationKey: infer TMutationKey +} + ? TMutationKey extends ReadonlyArray + ? TMutationKey + : TMutationKey extends Array + ? TMutationKey + : ReadonlyArray + : ReadonlyArray + +/** @inline */ +export type MutationStatus = 'idle' | 'pending' | 'success' | 'error' + +/** + * Groups mutations so they run one after another instead of in parallel. + * Mutations that share the same `id` form a queue: while one is running, the others wait in `isPaused: true` + * state and resume automatically when their turn comes. Mutations with no scope always run in parallel. + */ +export type MutationScope = { + /** + * The scope's identifier. Mutations with the same `id` run one after another. + */ + id: string +} + +/** + * The type of the `meta` object that can be attached to a mutation and read back from `mutationFn`, callbacks and + * cache-level handlers. Defaults to `Record`; declare `mutationMeta` on {@link Register} to narrow it. + */ +export type MutationMeta = Register extends { + mutationMeta: infer TMutationMeta +} + ? TMutationMeta extends Record + ? TMutationMeta + : Record + : Record + +/** + * The object passed to `mutationFn` and the mutation callbacks: the `QueryClient`, the mutation's + * `meta`, and its `mutationKey`. + */ +export type MutationFunctionContext = { + /** + * The `QueryClient` the mutation runs in. + */ + client: QueryClient + /** + * The `meta` of the mutation options. + */ + meta: MutationMeta | undefined + /** + * The `mutationKey` of the mutation options, if set. + */ + mutationKey?: MutationKey +} + +/** @inline */ +export type MutationFunction = ( + variables: TVariables, + context: MutationFunctionContext, +) => Promise + +/** + * The options of a mutation: its `mutationFn`, `mutationKey`, callbacks, retries, `scope`, and so + * on. + */ +export interface MutationOptions< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> = Shared.MutationOptions< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> +> { + /** + * The function that performs the asynchronous task this mutation runs. + * Required, unless a default mutation function has been set for the matching `mutationKey` via + * `queryClient.setMutationDefaults`. + * Receives the `variables` passed to `mutate`, and a {@link MutationFunctionContext} holding the + * `QueryClient`, the `mutationKey` and `meta`. + * Must return a promise that resolves the mutation's data. + */ + mutationFn?: MutationFunction + /** + * The key to use for this mutation. Optional, but required to inherit defaults registered with + * `queryClient.setMutationDefaults`, and to match this mutation with `useMutationState` or + * `queryClient.isMutating`. + */ + mutationKey?: MutationKey + /** + * This function fires before the mutation function runs, and receives the same variables. + * Useful for optimistic updates applied in the hope that the mutation succeeds. + * The value it returns is passed to `onSuccess`, `onError` and `onSettled` as `onMutateResult`, + * which is where an optimistic update is usually rolled back. + * If a promise is returned, it is awaited before the mutation function runs. + */ + onMutate?: ( + variables: TVariables, + context: MutationFunctionContext, + ) => Promise | TOnMutateResult + /** + * This function fires when the mutation succeeds, and is passed the mutation's result. + * If a promise is returned, it is awaited before `onSettled` runs. + */ + onSuccess?: ( + data: TData, + variables: TVariables, + onMutateResult: TOnMutateResult, + context: MutationFunctionContext, + ) => Promise | unknown + /** + * This function fires when the mutation encounters an error, and is passed the error. + * If a promise is returned, it is awaited before `onSettled` runs. + */ + onError?: ( + error: TError, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => Promise | unknown + /** + * This function fires when the mutation either succeeds or errors, and is passed either the data + * or the error. + * If a promise is returned, it is awaited before the mutation settles. + */ + onSettled?: ( + data: TData | undefined, + error: TError | null, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => Promise | unknown + /** + * If `false`, failed mutations will not retry by default. + * If `true`, failed mutations will retry infinitely. + * If set to an integer number, e.g. 3, failed mutations will retry until the failed mutation count meets that number. + * If set to a function `(failureCount, error) => boolean` failed mutations will retry until the function returns false. + * @defaultValue 0 + */ + retry?: RetryValue + /** + * The delay in milliseconds before a retry. Use a number for a fixed delay or a function that receives + * the failure count and error and returns the delay. The count starts at 0 for the first retry. + * + * By default, each retry waits a random duration from 80% to 100% of the base delay. + * The base delay starts at 1 second and doubles for each retry, up to 30 seconds. + */ + retryDelay?: RetryDelayValue + /** + * Controls whether a mutation is allowed to run based on the current network connectivity. + * @defaultValue 'online' + * @see [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. + */ + networkMode?: NetworkMode + /** + * The time in milliseconds that an unused/inactive mutation remains in memory before it is + * garbage collected. + * + * Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. + */ + gcTime?: number + /** @internal */ + _defaulted?: boolean + /** + * Additional payload to be stored on the mutation cache entry. + * Use it to pass information that can be read wherever the `mutation` is available, such as the + * `onError` and `onSuccess` callbacks of the `MutationCache`. + */ + meta?: MutationMeta + /** + * Controls whether this mutation runs alongside others or waits its turn. + * Mutations sharing the same `scope.id` run serially, in the order they were started. + * Without a scope, a mutation runs as soon as it is triggered. + */ + scope?: MutationScope +} -type MutationObserverOptions< +/** + * The options of a `MutationObserver`, and of the hooks built on it like `useMutation`: the + * {@link MutationOptions}, plus `throwOnError`. + */ +export interface MutationObserverOptions< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> = Shared.MutationObserverOptions< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> +> extends MutationOptions { + /** + * Whether errors should be thrown instead of setting the `error` property. + * If set to `true`, all errors will be thrown to the nearest error boundary. + * If set to a function, it will be passed the error and should return a boolean indicating whether to throw the + * error (`true`) or return it as state (`false`). + * @defaultValue false + */ + throwOnError?: boolean | ((error: TError) => boolean) +} -type MutateOptions< +/** + * The callbacks that can be passed to `mutate` for a single call. They run after the callbacks of + * the mutation options. + */ +export interface MutateOptions< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> = Shared.MutateOptions< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> +> { + /** + * Called when the mutation of this call succeeds, after the `onSuccess` of the mutation options. + */ + onSuccess?: ( + data: TData, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => void + /** + * Called when the mutation of this call fails, after the `onError` of the mutation options. + */ + onError?: ( + error: TError, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => void + /** + * Called when the mutation of this call succeeds or fails, after the `onSettled` of the mutation + * options. + */ + onSettled?: ( + data: TData | undefined, + error: TError | null, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => void +} -type MutateFunctionRest< +/** + * The parameters of {@link MutateFunction}: `variables`, optional when `TVariables` accepts + * `undefined`, and the {@link MutateOptions} for that call. + */ +export type MutateFunctionRest< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> = Shared.MutateFunctionRest< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> +> = undefined extends TVariables + ? [ + variables?: TVariables, + options?: MutateOptions, + ] + : [ + variables: TVariables, + options?: MutateOptions, + ] -type MutateFunction< +/** + * The `mutate` function of a `MutationObserver`: runs the mutation with the given variables and + * resolves with its data. + */ +export type MutateFunction< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> = Shared.MutateFunction< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> +> = ( + ...rest: MutateFunctionRest +) => Promise -type MutationObserverBaseResult< +/** + * The properties shared by every state of a mutation result, like `data`, `error`, `variables`, + * `status`, the `is*` flags, `mutate`, and `reset`. + */ +export interface MutationObserverBaseResult< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> = Shared.MutationObserverBaseResult< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> +> extends MutationState { + /** + * The last successfully resolved data for the mutation. + */ + data: TData | undefined + /** + * The variables object passed to the `mutationFn`. + */ + variables: TVariables | undefined + /** + * The error object for the mutation, if an error was encountered. + * - Defaults to `null`. + */ + error: TError | null + /** + * A boolean variable derived from `status`. + * - `true` if the last mutation attempt resulted in an error. + */ + isError: boolean + /** + * A boolean variable derived from `status`. + * - `true` if the mutation is in its initial state prior to executing. + */ + isIdle: boolean + /** + * A boolean variable derived from `status`. + * - `true` if the mutation is currently executing. + */ + isPending: boolean + /** + * A boolean variable derived from `status`. + * - `true` if the last mutation attempt was successful. + */ + isSuccess: boolean + /** + * The status of the mutation. + * - Will be: + * - `idle` initial status prior to the mutation function executing. + * - `pending` if the mutation is currently executing. + * - `error` if the last mutation attempt resulted in an error. + * - `success` if the last mutation attempt was successful. + */ + status: MutationStatus + /** + * The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options. + * @param variables - The variables object to pass to the `mutationFn`. + * @param options.onSuccess - This function will fire when the mutation is successful and will be passed the mutation's result. + * @param options.onError - This function will fire if the mutation encounters an error and will be passed the error. + * @param options.onSettled - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error. + * @remarks + * - If you make multiple requests, `onSuccess` will fire only after the latest call you've made. + * - All the callback functions (`onSuccess`, `onError`, `onSettled`) are void functions, and the returned value will be ignored. + */ + mutate: MutateFunction + /** + * A function to clean the mutation internal state (i.e., it resets the mutation to its initial state). + */ + reset: () => void +} -type MutationObserverIdleResult< +/** + * A mutation result in the `idle` state: the mutation hasn't run yet, or was reset. + */ +export interface MutationObserverIdleResult< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> = Shared.MutationObserverIdleResult< - QueryRuntime, +> extends MutationObserverBaseResult< TData, TError, TVariables, TOnMutateResult -> +> { + /** + * `undefined`, since the mutation hasn't run. + */ + data: undefined + /** + * `undefined`, since the mutation hasn't run. + */ + variables: undefined + /** + * `null`, since the mutation hasn't failed. + */ + error: null + /** + * `false`, since the mutation hasn't failed. + */ + isError: false + /** + * `true`, since the mutation hasn't run yet or was reset. + */ + isIdle: true + /** + * `false`, since the mutation isn't running. + */ + isPending: false + /** + * `false`, since the mutation hasn't succeeded. + */ + isSuccess: false + /** + * `'idle'`, since the mutation hasn't run yet or was reset. + */ + status: 'idle' +} -type MutationObserverLoadingResult< +/** + * A mutation result in the `pending` state while the mutation runs. + */ +export interface MutationObserverLoadingResult< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> = Shared.MutationObserverLoadingResult< - QueryRuntime, +> extends MutationObserverBaseResult< TData, TError, TVariables, TOnMutateResult -> +> { + /** + * `undefined`, since the mutation hasn't succeeded. + */ + data: undefined + /** + * The variables passed to `mutate` for this mutation. + */ + variables: TVariables + /** + * `null`, since the mutation hasn't failed. + */ + error: null + /** + * `false`, since the mutation hasn't failed. + */ + isError: false + /** + * `false`, since the mutation has run. + */ + isIdle: false + /** + * `true`, since the mutation is running. + */ + isPending: true + /** + * `false`, since the mutation hasn't succeeded. + */ + isSuccess: false + /** + * `'pending'`, since the mutation is running. + */ + status: 'pending' +} -type MutationObserverErrorResult< +/** + * A mutation result in the `error` state after the mutation failed. + */ +export interface MutationObserverErrorResult< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> = Shared.MutationObserverErrorResult< - QueryRuntime, +> extends MutationObserverBaseResult< TData, TError, TVariables, TOnMutateResult -> +> { + /** + * `undefined`, since the mutation hasn't succeeded. + */ + data: undefined + /** + * The error the mutation failed with. + */ + error: TError + /** + * The variables passed to `mutate` for this mutation. + */ + variables: TVariables + /** + * `true`, since the mutation failed. + */ + isError: true + /** + * `false`, since the mutation has run. + */ + isIdle: false + /** + * `false`, since the mutation isn't running. + */ + isPending: false + /** + * `false`, since the mutation hasn't succeeded. + */ + isSuccess: false + /** + * `'error'`, since the mutation failed. + */ + status: 'error' +} -type MutationObserverSuccessResult< +/** + * A mutation result in the `success` state after the mutation succeeded. + */ +export interface MutationObserverSuccessResult< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> = Shared.MutationObserverSuccessResult< - QueryRuntime, +> extends MutationObserverBaseResult< TData, TError, TVariables, TOnMutateResult -> +> { + /** + * The data the mutation resolved with. + */ + data: TData + /** + * `null`, since the mutation hasn't failed. + */ + error: null + /** + * The variables passed to `mutate` for this mutation. + */ + variables: TVariables + /** + * `false`, since the mutation hasn't failed. + */ + isError: false + /** + * `false`, since the mutation has run. + */ + isIdle: false + /** + * `false`, since the mutation isn't running. + */ + isPending: false + /** + * `true`, since the mutation succeeded. + */ + isSuccess: true + /** + * `'success'`, since the mutation succeeded. + */ + status: 'success' +} -type MutationObserverResult< +/** + * The result of a `MutationObserver`, and of the hooks built on it like `useMutation`. Narrow it by + * `status` or the `is*` flags to get the type of each state. + */ +export type MutationObserverResult< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> = Shared.MutationObserverResult< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> +> = + | MutationObserverIdleResult + | MutationObserverLoadingResult + | MutationObserverErrorResult + | MutationObserverSuccessResult -type QueryClientConfig = Shared.QueryClientConfig +/** + * The options of `new QueryClient()`: the `queryCache` and `mutationCache` to use, and the + * `defaultOptions` for its queries and mutations. + */ +export interface QueryClientConfig { + /** The query cache this client is connected to. A new `QueryCache` is created if not provided. */ + queryCache?: QueryCache + /** + * The mutation cache this client is connected to. A new `MutationCache` is created if not + * provided. + */ + mutationCache?: MutationCache + /** Default options for all queries and mutations created through this client. */ + defaultOptions?: DefaultOptions +} -type DefaultOptions = Shared.DefaultOptions< - QueryRuntime, - TError -> +/** + * The default options of a `QueryClient`, applied to every query (`queries`), mutation + * (`mutations`), `hydrate`, and `dehydrate` call unless overridden. + */ +export interface DefaultOptions { + /** Default options applied to every query, unless overridden per-query. */ + queries?: OmitKeyof< + QueryObserverOptionsBase, + 'suspense' | 'queryKey' + > + /** Default options applied to every mutation, unless overridden per-mutation. */ + mutations?: MutationObserverOptions + /** Default options used when hydrating queries and mutations; see {@link HydrateOptions}. */ + hydrate?: HydrateOptions['defaultOptions'] + /** Default options used when dehydrating the client's caches; see {@link DehydrateOptions}. */ + dehydrate?: DehydrateOptions +} + +/** + * Options for cancelling an in-flight fetch, e.g. via `query.cancel()`. + * They are carried on the {@link CancelledError} that the cancelled fetch rejects with. + */ +export interface CancelOptions { + /** + * If `true`, the query goes back to the state it had before the fetch started, instead of getting + * the cancellation error. + */ + revert?: boolean + /** + * If `true`, the cancellation error isn't surfaced, e.g. because another fetch replaces the + * cancelled one. + */ + silent?: boolean +} + +/** + * Options for writing data into the cache, e.g. via `queryClient.setQueryData()`. + * `updatedAt` overrides the timestamp the data is recorded with, which is what staleness is measured from; + * omit it to use the current time. + */ +export interface SetDataOptions { + /** + * The timestamp to record the data with, instead of the current time. Staleness is measured from + * it. + */ + updatedAt?: number +} -export type { - NonUndefinedGuard, - DistributiveOmit, - OmitKeyof, - Override, - Register, - DefaultError, - QueryKey, - 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, - QueryObserverResult, - InfiniteQueryObserverBaseResult, - InfiniteQueryObserverPendingResult, - InfiniteQueryObserverLoadingResult, - InfiniteQueryObserverLoadingErrorResult, - InfiniteQueryObserverRefetchErrorResult, - InfiniteQueryObserverSuccessResult, - InfiniteQueryObserverPlaceholderResult, - DefinedInfiniteQueryObserverResult, - InfiniteQueryObserverResult, - MutationKey, - MutationStatus, - MutationScope, - MutationMeta, - CancelOptions, - SetDataOptions, - NotifyEventType, - NotifyEvent, -} from '@tanstack/query-types/bindings' - -export type { - QueryFunction, - StaleTimeFunction, - QueryBooleanOption, - QueryPersister, - QueryFunctionContext, - PlaceholderDataFunction, - QueryOptions, - ThrowOnError, - QueryObserverOptionsBase, - QueryObserverOptions, - DefaultedQueryObserverOptions, - InfiniteQueryObserverOptions, - DefaultedInfiniteQueryObserverOptions, - QueryExecuteOptions, - InfiniteQueryExecuteOptions, - InvalidateQueryFilters, - RefetchQueryFilters, - MutationFunctionContext, - MutationFunction, - MutationOptions, - MutationObserverOptions, - MutateOptions, - MutateFunctionRest, - MutateFunction, - MutationObserverBaseResult, - MutationObserverIdleResult, - MutationObserverLoadingResult, - MutationObserverErrorResult, - MutationObserverSuccessResult, - MutationObserverResult, - QueryClientConfig, - DefaultOptions, +/** @inline */ +export type NotifyEventType = + | 'added' + | 'removed' + | 'updated' + | 'observerAdded' + | 'observerRemoved' + | 'observerResultsUpdated' + | 'observerOptionsUpdated' + +/** + * The base shape of the events that the query and mutation caches send to their listeners. + */ +export interface NotifyEvent { + /** + * The kind of event, e.g. `'added'`, `'removed'`, or `'updated'`. + */ + type: NotifyEventType } diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index 9cd373fa216..3181666bdb2 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -1,43 +1,114 @@ import { timeoutManager } from './timeoutManager' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - DefaultQueryFn, - SkipToken, - Updater, - DefaultQueryFn as defaultQueryFnType, - FetchSignal as fetchSignalType, - SkipToken as skipTokenType, -} from '@tanstack/query-types/bindings' import type { Mutation } from './mutation' import type { FetchOptions, Query } from './query' -import type { QueryRuntime } from './runtimeBinding' import type { CacheKeyConfig, DefaultError, EqualityFn, + FetchStatus, MutationKey, + MutationStatus, QueryFunction, QueryKey, QueryOptions, } from './types' -type QueryFilters = Shared.QueryFilters< - QueryRuntime, - TQueryKey -> +// TYPES + +type DropLast> = T extends readonly [ + ...infer R, + unknown, +] + ? readonly [...R] + : never + +type TuplePrefixes> = T extends readonly [] + ? readonly [] + : TuplePrefixes> | T + +/** + * Filters used to select queries, for example in `queryClient.getQueriesData` or `queryClient.invalidateQueries`. + * All provided filters must match; filters that are left unspecified are ignored. + */ +export interface QueryFilters { + /** + * Filter to active queries, inactive queries or all queries + * @defaultValue 'all' + */ + type?: QueryTypeFilter + /** + * Match query key exactly + */ + exact?: boolean + /** + * Include queries matching this predicate function + */ + predicate?: (query: Query) => boolean + /** + * Include queries matching this query key + */ + queryKey?: TQueryKey | TuplePrefixes + /** + * Include or exclude stale queries + */ + stale?: boolean + /** + * Include queries matching their fetchStatus + */ + fetchStatus?: FetchStatus +} -type MutationFilters< +/** + * Filters used to select mutations, for example in `mutationCache.findAll` or `queryClient.isMutating`. + * All provided filters must match; filters that are left unspecified are ignored. + */ +export interface MutationFilters< TData = unknown, TError = DefaultError, TVariables = unknown, TOnMutateResult = unknown, -> = Shared.MutationFilters< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> +> { + /** + * Match mutation key exactly + */ + exact?: boolean + /** + * Include mutations matching this predicate function + */ + predicate?: ( + mutation: Mutation, + ) => boolean + /** + * Include mutations matching this mutation key + */ + mutationKey?: TuplePrefixes + /** + * Filter by mutation status + */ + status?: MutationStatus +} + +/** + * Either a plain value of type `TOutput`, or a function that receives `TInput` and returns `TOutput`. + * Used for example by `setQueryData`-style updaters, which accept either the new data directly or a + * function that computes it from the previous data. See {@link functionalUpdate}. + * @example + * ```ts + * queryClient.setQueryData(['posts'], newPosts) + * + * // Or, using an updater function that receives the current data: + * queryClient.setQueryData(['posts'], (oldPosts) => + * oldPosts ? [...oldPosts, newPost] : oldPosts, + * ) + * ``` + */ +export type Updater = TOutput | ((input: TInput) => TOutput) + +/** + * Which queries a filter matches: all of them, only active ones (with enabled observers), or only + * inactive ones. + */ +export type QueryTypeFilter = 'all' | 'active' | 'inactive' // UTILS @@ -524,7 +595,7 @@ export function sleep(timeout: number): Promise { */ export function replaceData< TData, - TOptions extends QueryOptions, + TOptions extends Pick, >(prevData: TData | undefined, data: TData, options: TOptions): TData { if (typeof options.structuralSharing === 'function') { return options.structuralSharing(prevData, data) as TData @@ -602,18 +673,21 @@ export function addToArray( * }) * ``` */ -export const skipToken: skipTokenType = Symbol.for( - '@tanstack/query/skipToken', -) as skipTokenType +export const skipToken = Symbol() +/** + * The type of the {@link skipToken} sentinel value. + */ +export type SkipToken = typeof skipToken /** * Pass this as `queryFn` to use the query function configured on the client. * The defaults for the query key take precedence over the client's global query defaults. * If no query function is configured, a fetch fails with a `Missing queryFn` error. */ -export const defaultQueryFn: defaultQueryFnType = Symbol.for( - '@tanstack/query/defaultQueryFn', -) as defaultQueryFnType +export const defaultQueryFn = Symbol() + +/** The type of the {@link defaultQueryFn} sentinel value. */ +export type DefaultQueryFn = typeof defaultQueryFn /** * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from @@ -693,9 +767,15 @@ export function shouldThrowError) => boolean>( return !!throwOnError } -export const fetchSignal: fetchSignalType = Symbol.for( - '@tanstack/query/fetchSignal', -) as fetchSignalType +export const fetchSignal = Symbol() + +/** Internal view of a context that can expose its signal without consuming it. */ +export type FetchSignalContext = { + /** The public signal, whose getter can mark it consumed. */ + readonly signal: AbortSignal + /** The original fetch signal, absent on application-created contexts. */ + readonly [fetchSignal]?: AbortSignal +} /** * Adds a lazy `signal` getter to an object, such as a query function context. The first time @@ -740,13 +820,3 @@ export function addConsumeAwareSignal( return object as T & { signal: AbortSignal } } - -export type { - Updater, - QueryTypeFilter, - SkipToken, - DefaultQueryFn, - FetchSignalContext, -} from '@tanstack/query-types/bindings' - -export type { QueryFilters, MutationFilters } diff --git a/packages/query-core/tsconfig.json b/packages/query-core/tsconfig.json index bd0c9448b94..0cc454b2a77 100644 --- a/packages/query-core/tsconfig.json +++ b/packages/query-core/tsconfig.json @@ -4,10 +4,5 @@ "outDir": "./dist-ts", "rootDir": "." }, - "include": ["src", "*.config.ts", "*.config.js", "package.json"], - "references": [ - { - "path": "../query-types" - } - ] + "include": ["src", "*.config.ts", "*.config.js", "package.json"] } diff --git a/packages/query-core/tsconfig.legacy.json b/packages/query-core/tsconfig.legacy.json index 0525af804f1..84ebe1a984b 100644 --- a/packages/query-core/tsconfig.legacy.json +++ b/packages/query-core/tsconfig.legacy.json @@ -4,10 +4,5 @@ "outDir": "./dist-ts/legacy" }, "include": ["src"], - "exclude": ["src/__tests__"], - "references": [ - { - "path": "../query-types" - } - ] + "exclude": ["src/__tests__"] } diff --git a/packages/query-test-utils/package.json b/packages/query-test-utils/package.json index 1753a93efe8..c1e250169a3 100644 --- a/packages/query-test-utils/package.json +++ b/packages/query-test-utils/package.json @@ -25,7 +25,6 @@ }, "./package.json": "./package.json", "./polling": "./src/polling.ts", - "./cacheOperations": "./src/cacheOperations.ts", "./scope": "./src/scope.ts", "./projection": "./src/projection.ts" }, diff --git a/packages/query-test-utils/src/cacheOperations.ts b/packages/query-test-utils/src/cacheOperations.ts deleted file mode 100644 index aab73fe28d9..00000000000 --- a/packages/query-test-utils/src/cacheOperations.ts +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Selects this client's cache operations in the shared behavior and type tests. - * The pluggable adapter supplies its named exports through the same fixture. - * @param client - Client under test. - * @returns The client's cache operations. - */ -export function cacheOperations(client: TClient): TClient { - return client -} - -/** - * Reads the cache from clients with the standard instance method. - * @param client - Query client under test. - * @returns The client's configured mutation cache. - */ -export function getMutationCache(client: { - getMutationCache: () => TCache -}): TCache { - return client.getMutationCache() -} diff --git a/packages/query-test-utils/src/polling.ts b/packages/query-test-utils/src/polling.ts index 6270186dbb1..2ceadbc34ec 100644 --- a/packages/query-test-utils/src/polling.ts +++ b/packages/query-test-utils/src/polling.ts @@ -1,5 +1,5 @@ /** - * Supplies the interval directly to v6 and the integrated React adapter. + * Supplies the interval directly to the v6 query options. * The pluggable compatibility suite uses its own public factory here. * @param option - Interval setting from a shared test case. * @returns The supplied setting with its original type. diff --git a/packages/query-types/README.md b/packages/query-types/README.md deleted file mode 100644 index 50ad55fcaaa..00000000000 --- a/packages/query-types/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# @tanstack/query-types - -Shared TypeScript declarations for TanStack Query. Use type-only imports in code that models query state, cached data, results, and options. - -```ts -import type { QueryState } from '@tanstack/query-types' - -export function lastSuccessfulUpdate(state: QueryState) { - return state.dataUpdatedAt -} -``` - -The package root describes the public instance methods of the query client, caches, and observers. Each adapter also re-exports the query types with the concrete classes its callbacks receive. - -When publishing a callback or options object for use with a particular adapter, use its specialized types. Libraries that support multiple implementations can use the same declaration with each adapter's `QueryRuntime` type parameter. - -```ts -import type { QueryOptions } from '@tanstack/query-types/bindings' -import type { QueryRuntime } from '@tanstack/react-query-no-core' - -export const bookOptions: QueryOptions = { - queryKey: ['book'], - queryFn: async ({ client }) => client.getQueryData(['title']) ?? '', -} -``` - -Augment `Register` in `@tanstack/query-types` to share your application's error, key, or metadata types across installed adapters. diff --git a/packages/query-types/oxlint.config.ts b/packages/query-types/oxlint.config.ts deleted file mode 100644 index 396987b4462..00000000000 --- a/packages/query-types/oxlint.config.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { defineConfig } from 'oxlint' -import rootConfig from './root.oxlint.config.ts' - -export default defineConfig({ - extends: [rootConfig], - settings: rootConfig.settings, -}) diff --git a/packages/query-types/package.json b/packages/query-types/package.json deleted file mode 100644 index e02d3c1becf..00000000000 --- a/packages/query-types/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "name": "@tanstack/query-types", - "version": "5.108.4", - "description": "Shared TypeScript declarations for TanStack Query", - "author": "tannerlinsley", - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/TanStack/query.git", - "directory": "packages/query-types" - }, - "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: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", - "./bindings": { - "@tanstack/custom-condition": "./src/bindings.ts", - "types": "./build/bindings.d.ts", - "default": "./build/bindings.js" - } - }, - "sideEffects": false, - "files": [ - "build", - "src", - "!src/__tests__" - ], - "devDependencies": { - "typescript": "catalog:" - } -} diff --git a/packages/query-types/src/binding.ts b/packages/query-types/src/binding.ts deleted file mode 100644 index 8f590e05abf..00000000000 --- a/packages/query-types/src/binding.ts +++ /dev/null @@ -1,127 +0,0 @@ -import type { DefaultError, QueryKey } from './types' - -/** - * Type arguments and classes used by options and callbacks. Each runtime supplies - * its public classes using polymorphic `this` to read the current type arguments. - * For example, `QueryOf` selects `Query` after binding the data, error, and key. - */ -interface RuntimeBinding { - data: unknown - queryFnData: unknown - queryData: unknown - error: unknown - // A tuple keeps a bound key exact when this slot intersects with its input. - queryKey: ReadonlyArray - variables: unknown - onMutateResult: unknown - /** The client passed to query functions and mutations. */ - QueryClient: unknown - /** The query cache accepted in client options. */ - QueryCache: unknown - /** The mutation cache accepted in client options. */ - MutationCache: unknown - /** The query passed to predicates, option callbacks, and cache listeners. */ - Query: unknown - /** The mutation passed to predicates and cache listeners. */ - Mutation: unknown - /** The observer included in query cache notifications. */ - QueryObserver: unknown - /** The observer included in mutation cache notifications. */ - MutationObserver: unknown -} - -type QueryClientOf = TRuntime['QueryClient'] - -type QueryCacheOf = TRuntime['QueryCache'] - -type MutationCacheOf = - TRuntime['MutationCache'] - -type BoundQuery = TRuntime & { - queryFnData: TQueryFnData - error: TError - data: TData - queryKey: [TQueryKey] -} - -type QueryOf< - TRuntime extends RuntimeBinding, - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = BoundQuery['Query'] - -/** Allows an adapter to supply its own polling option while preserving the query type in callbacks. */ -type RefetchIntervalOf< - TRuntime extends RuntimeBinding, - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey, -> = TRuntime extends { refetchInterval: unknown } - ? BoundQuery< - TRuntime, - TQueryFnData, - TError, - TData, - TQueryKey - >['refetchInterval'] - : | number - | false - | (( - query: QueryOf, - ) => number | false | undefined) - -type MutationOf< - TRuntime extends RuntimeBinding, - TData = unknown, - TError = DefaultError, - TVariables = unknown, - TOnMutateResult = unknown, -> = (TRuntime & { - data: TData - error: TError - variables: TVariables - onMutateResult: TOnMutateResult -})['Mutation'] - -type QueryObserverOf< - TRuntime extends RuntimeBinding, - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = (TRuntime & { - queryFnData: TQueryFnData - error: TError - data: TData - queryData: TQueryData - queryKey: [TQueryKey] -})['QueryObserver'] - -type MutationObserverOf< - TRuntime extends RuntimeBinding, - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = (TRuntime & { - data: TData - error: TError - variables: TVariables - onMutateResult: TOnMutateResult -})['MutationObserver'] - -export type { - RuntimeBinding, - QueryClientOf, - QueryCacheOf, - MutationCacheOf, - QueryOf, - RefetchIntervalOf, - MutationOf, - QueryObserverOf, - MutationObserverOf, -} diff --git a/packages/query-types/src/bindings.ts b/packages/query-types/src/bindings.ts deleted file mode 100644 index 126a5983b2a..00000000000 --- a/packages/query-types/src/bindings.ts +++ /dev/null @@ -1,235 +0,0 @@ -export type { RuntimeBinding } from './binding' -export type { fetchSignal as FetchSignal } from './symbols' -export type { IsServerValue } from './environmentManager' -export type { FocusManagerListener, FocusManagerSetupFn } from './focusManager' -export type { - TransformerFn, - DehydrateOptions, - HydrateOptions, - DehydratedMutation, - DehydratedQuery, - DehydratedState, -} from './hydration' -export type { - InfiniteQueryObserverListener, - InfiniteObserverOptionsInput, - ReplaceReturnType, -} from './infiniteQueryObserver' -export type { - MutationConfig, - MutationState, - MutationFailedAction, - PendingAction, - MutationSuccessAction, - MutationErrorAction, - MutationPauseAction, - MutationContinueAction, - MutationAction, -} from './mutation' -export type { - MutationCacheConfig, - NotifyEventMutationAdded, - NotifyEventMutationRemoved, - NotifyEventMutationObserverAdded, - NotifyEventMutationObserverRemoved, - NotifyEventMutationObserverOptionsUpdated, - NotifyEventMutationUpdated, - MutationCacheNotifyEvent, - MutationCacheListener, -} from './mutationCache' -export type { MutationObserverListener } from './mutationObserver' -export type { - NotifyCallback, - NotifyFunction, - BatchNotifyFunction, - BatchCallsCallback, - ScheduleFunction, -} from './notifyManager' -export type { - OnlineManagerListener, - OnlineManagerSetupFn, -} from './onlineManager' -export type { - QueriesObserverListener, - CombineFn, - QueriesObserverResultReader, - CombineContext, - QueriesObserverOptions, - QueryObserverMatch, -} from './queriesObserver' -export type { - QueryConfig, - QueryState, - FetchContext, - QueryBehavior, - FetchDirection, - FetchMeta, - FetchOptions, - QueryFailedAction, - FetchAction, - QuerySuccessAction, - QueryErrorAction, - InvalidateAction, - QueryPauseAction, - QueryContinueAction, - SetStateAction, - QueryAction, -} from './query' -export type { - QueryCacheConfig, - NotifyEventQueryAdded, - NotifyEventQueryRemoved, - NotifyEventQueryUpdated, - NotifyEventQueryObserverAdded, - NotifyEventQueryObserverRemoved, - NotifyEventQueryObserverResultsUpdated, - NotifyEventQueryObserverOptionsUpdated, - QueryCacheNotifyEvent, - QueryCacheListener, - QueryStore, -} from './queryCache' -export type { - WithoutSkipToken, - QueryDefaults, - MutationDefaults, -} from './queryClient' -export type { - QueryObserverListener, - ObserverFetchOptions, - QueryObserverResultReader, - ProjectionFailure, - QueryObserverResultContext, - ObserverOptionsInput, -} from './queryObserver' -export type { - RetryerConfig, - Retryer, - RetryerStatus, - RetryValue, - ShouldRetryFunction, - RetryDelayValue, - RetryDelayFunction, -} from './retryer' -export type { - BaseStreamedQueryParams, - SimpleStreamedQueryParams, - ReducibleStreamedQueryParams, - StreamedQueryParams, -} from './streamedQuery' -export type { - TimeoutCallback, - ManagedTimerId, - TimeoutProvider, - SystemTimerId, -} from './timeoutManager' -export type { - NonUndefinedGuard, - DistributiveOmit, - OmitKeyof, - Override, - Register, - DefaultError, - QueryKey, - dataTagSymbol, - dataTagErrorSymbol, - UnsetMarker, - AnyDataTag, - DataTag, - QueryKeyWithDataTag, - InferDataFromTag, - InferErrorFromTag, - QueryFunction, - StaleTime, - StaleTimeFunction, - QueryBooleanOption, - QueryPersister, - QueryFunctionContext, - InitialDataFunction, - NonFunctionGuard, - PlaceholderDataFunction, - QueriesPlaceholderDataFunction, - EqualityFn, - CacheKeyHashFunction, - CacheKeyConfig, - GetPreviousPageParamFunction, - GetNextPageParamFunction, - InfiniteData, - QueryMeta, - NetworkMode, - NotifyOnChangeProps, - QueryOptions, - InitialPageParam, - InfiniteQueryPageParamsOptions, - ThrowOnError, - QueryObserverOptionsBase, - QueryObserverOptions, - WithRequired, - DefaultedQueryObserverOptions, - InfiniteQueryObserverOptions, - DefaultedInfiniteQueryObserverOptions, - QueryExecuteOptions, - InfiniteQueryFetchPageOptions, - InfiniteQueryExecuteOptions, - ResultOptions, - RefetchOptions, - InvalidateQueryFilters, - RefetchQueryFilters, - InvalidateOptions, - ResetOptions, - FetchNextPageOptions, - FetchPreviousPageOptions, - QueryStatus, - FetchStatus, - QueryObserverBaseResult, - QueryObserverPendingResult, - QueryObserverLoadingResult, - QueryObserverLoadingErrorResult, - QueryObserverRefetchErrorResult, - QueryObserverSuccessResult, - QueryObserverPlaceholderResult, - DefinedQueryObserverResult, - QueryObserverResult, - InfiniteQueryObserverBaseResult, - InfiniteQueryObserverPendingResult, - InfiniteQueryObserverLoadingResult, - InfiniteQueryObserverLoadingErrorResult, - InfiniteQueryObserverRefetchErrorResult, - InfiniteQueryObserverSuccessResult, - InfiniteQueryObserverPlaceholderResult, - DefinedInfiniteQueryObserverResult, - InfiniteQueryObserverResult, - MutationKey, - MutationStatus, - MutationScope, - MutationMeta, - MutationFunctionContext, - MutationFunction, - MutationOptions, - MutationObserverOptions, - MutateOptions, - MutateFunctionRest, - MutateFunction, - MutationObserverBaseResult, - MutationObserverIdleResult, - MutationObserverLoadingResult, - MutationObserverErrorResult, - MutationObserverSuccessResult, - MutationObserverResult, - QueryClientConfig, - DefaultOptions, - CancelOptions, - SetDataOptions, - NotifyEventType, - NotifyEvent, -} from './types' -export type { - DropLast, - TuplePrefixes, - QueryFilters, - MutationFilters, - Updater, - QueryTypeFilter, - SkipToken, - DefaultQueryFn, - FetchSignalContext, -} from './utils' diff --git a/packages/query-types/src/contracts.ts b/packages/query-types/src/contracts.ts deleted file mode 100644 index 862eb320e1e..00000000000 --- a/packages/query-types/src/contracts.ts +++ /dev/null @@ -1,692 +0,0 @@ -import type { RuntimeBinding } from './binding' -import type { FocusManagerListener, FocusManagerSetupFn } from './focusManager' -import type { - InfiniteQueryObserverListener, - ReplaceReturnType, - InfiniteObserverOptionsInput as SharedInfiniteObserverOptionsInput, -} from './infiniteQueryObserver' -import type { MutationCacheListener as SharedMutationCacheListener } from './mutationCache' -import type { MutationObserverListener as SharedMutationObserverListener } from './mutationObserver' -import type { - OnlineManagerListener, - OnlineManagerSetupFn, -} from './onlineManager' -import type { - QueriesObserverListener, - QueriesObserverOptions, - QueriesObserverResultReader, -} from './queriesObserver' -import type { QueryCacheListener as SharedQueryCacheListener } from './queryCache' -import type { WithoutSkipToken } from './queryClient' -import type { QueryObserverListener } from './queryObserver' -import type { - ManagedTimerId, - TimeoutCallback, - TimeoutProvider, -} from './timeoutManager' -import type { - CancelOptions, - DefaultError, - DefaultOptions, - DefaultedInfiniteQueryObserverOptions, - DefaultedQueryObserverOptions, - FetchNextPageOptions, - FetchOptions, - FetchPreviousPageOptions, - InferDataFromTag, - InferErrorFromTag, - InfiniteData, - InfiniteQueryExecuteOptions, - InfiniteQueryObserverResult, - InvalidateOptions, - InvalidateQueryFilters, - MutateOptions, - MutationAction, - MutationCacheConfig, - MutationCacheNotifyEvent, - MutationFilters, - MutationKey, - MutationMeta, - MutationObserverOptions, - MutationObserverResult, - MutationOptions, - MutationState, - ObserverOptionsInput, - OmitKeyof, - QueryCacheConfig, - QueryCacheNotifyEvent, - QueryExecuteOptions, - QueryFilters, - QueryKey, - QueryMeta, - QueryObserverOptionsBase, - QueryObserverResult, - QueryObserverResultReader, - QueryOptions, - QueryState, - RefetchOptions, - RefetchQueryFilters, - ResetOptions, - SetDataOptions, - StaleTime, - Updater, - WithRequired, -} from './index' - -/* oxlint-disable typescript/method-signature-style -- Match runtime class methods, including their parameter variance. */ - -interface Subscription { - subscribe(listener: TListener): () => void - hasListeners(): boolean -} -interface CacheEntry { - gcTime: number - destroy(): void -} -interface QueryClient { - mount(): void - unmount(): void - isFetching(filters?: Omit): number - isMutating< - TMutationFilters extends MutationFilters = MutationFilters< - any, - any - >, - >( - filters?: NoInfer>, - ): number - getQueryData< - TQueryFnData = unknown, - TTaggedQueryKey extends QueryKey = QueryKey, - TInferredQueryFnData = InferDataFromTag, - >( - queryKey: TTaggedQueryKey, - ): TInferredQueryFnData | undefined - getQueriesData< - TQueryFnData = unknown, - TQueryFilters extends QueryFilters = QueryFilters, - >( - filters: TQueryFilters, - ): Array<[QueryKey, TQueryFnData | undefined]> - setQueryData< - TQueryFnData = unknown, - TTaggedQueryKey extends QueryKey = QueryKey, - TInferredQueryFnData = InferDataFromTag, - >( - queryKey: TTaggedQueryKey, - updater: Updater< - InferDataFromTag, TTaggedQueryKey> | undefined, - NoInfer | undefined - >, - options?: SetDataOptions, - ): NoInfer | undefined - setQueriesData< - TQueryFnData, - TQueryFilters extends QueryFilters = QueryFilters, - >( - filters: TQueryFilters, - updater: Updater< - NoInfer | undefined, - NoInfer | undefined - >, - options?: SetDataOptions, - ): Array<[QueryKey, TQueryFnData | undefined]> - getQueryState< - TQueryFnData = unknown, - TError = DefaultError, - TTaggedQueryKey extends QueryKey = QueryKey, - TInferredQueryFnData = InferDataFromTag, - TInferredError = InferErrorFromTag, - >( - queryKey: TTaggedQueryKey, - ): QueryState | undefined - removeQueries( - filters?: QueryFilters, - ): void - resetQueries( - filters?: QueryFilters, - options?: ResetOptions, - ): Promise - cancelQueries( - filters?: QueryFilters, - cancelOptions?: CancelOptions, - ): Promise - invalidateQueries( - filters?: InvalidateQueryFilters, - options?: InvalidateOptions, - ): Promise - refetchQueries( - filters?: RefetchQueryFilters, - options?: RefetchOptions, - ): Promise - query< - TQueryFnData, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, - >( - options: WithoutSkipToken< - QueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - > - >, - ): Promise - query< - TQueryFnData, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, - >( - options: QueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - >, - ): Promise - infiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: WithoutSkipToken< - InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - > - >, - ): Promise< - Array extends Array> - ? InfiniteData - : TData - > - infiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - ): Promise< - | undefined - | (Array extends Array> - ? InfiniteData - : TData) - > - resumePausedMutations(): Promise - getQueryCache(): QueryCache - getMutationCache(): MutationCache - getDefaultOptions(): DefaultOptions - setDefaultOptions(options: DefaultOptions): void - setQueryDefaults< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - >( - queryKey: QueryKey, - options: Partial< - OmitKeyof< - QueryObserverOptionsBase, - 'queryKey' - > - >, - ): void - getQueryDefaults( - queryKey: QueryKey, - ): OmitKeyof, 'queryKey'> - setMutationDefaults< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, - >( - mutationKey: MutationKey, - options: OmitKeyof< - MutationObserverOptions, - 'mutationKey' - >, - ): void - getMutationDefaults( - mutationKey: MutationKey, - ): OmitKeyof, 'mutationKey'> - defaultQueryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, - >( - options: QueryObserverOptionsBase< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - >, - ): DefaultedQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - > - defaultMutationOptions>( - options?: T, - ): T - clear(): void -} - -interface QueryCache extends Subscription { - config: QueryCacheConfig - build< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - >( - client: QueryClient, - options: WithRequired< - QueryOptions, - 'queryKey' - >, - state?: QueryState, - ): Query - add(query: Query): void - remove(query: Query): void - clear(): void - get< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - >( - queryHash: string, - ): Query | undefined - getAll(): Array - find( - filters: WithRequired, - ): Query | undefined - findAll(filters?: QueryFilters): Array - notify(event: QueryCacheNotifyEvent): void - onFocus(): void - onOnline(): void -} - -interface MutationCache extends Subscription { - config: MutationCacheConfig - register>(create: (id: number) => T): T - add(mutation: Mutation): void - remove(mutation: Mutation): void - has(mutation: Mutation): boolean - canRun(mutation: Mutation): boolean - runNext(mutation: Mutation): Promise - clear(): void - getAll(): Array - find< - TData = unknown, - TError = DefaultError, - TVariables = any, - TOnMutateResult = unknown, - >( - filters: MutationFilters, - ): Mutation | undefined - findAll(filters?: MutationFilters): Array - notify(event: MutationCacheNotifyEvent): void - resumePausedMutations(): Promise -} - -interface Query< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> extends CacheEntry { - queryKey: TQueryKey - queryHash: string - options: QueryOptions - state: QueryState - observers: Array> - get meta(): QueryMeta | undefined - get queryType(): 'infinite' | undefined - get promise(): Promise | undefined - setOptions( - options?: QueryOptions, - ): void - setData( - newData: TData, - options?: SetDataOptions & { - manual: boolean - }, - ): TData - setState(state: Partial>): void - cancel(options?: CancelOptions): Promise - destroy(): void - get resetState(): QueryState - reset(): void - isActive(): boolean - isDisabled(): boolean - isFetched(): boolean - isStatic(): boolean - isStale(): boolean - isStaleByTime(staleTime?: StaleTime): boolean - onFocus(): void - onOnline(): void - addObserver(observer: QueryObserver): void - removeObserver(observer: QueryObserver): void - getObserversCount(): number - invalidate(): void - fetch( - options?: QueryOptions, - fetchOptions?: FetchOptions, - ): Promise -} - -interface Mutation< - TData = unknown, - TError = DefaultError, - TVariables = unknown, - TOnMutateResult = unknown, -> extends CacheEntry { - state: MutationState - options: MutationOptions - readonly mutationId: number - setOptions( - options: MutationOptions, - ): void - get meta(): MutationMeta | undefined - addObserver(observer: MutationObserver): void - removeObserver(observer: MutationObserver): void - continue(): Promise - execute(variables: TVariables): Promise -} - -interface QueryObserver< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> extends Subscription> { - options: ObserverOptionsInput< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - > - shouldFetchOnReconnect(): boolean - shouldFetchOnWindowFocus(): boolean - destroy(): void - setOptions( - options: ObserverOptionsInput< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >, - ): void - createResultReader( - options: DefaultedQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >, - ): QueryObserverResultReader> - getCurrentResult(): QueryObserverResult - trackResult( - result: QueryObserverResult, - onPropTracked?: (key: keyof QueryObserverResult) => void, - ): QueryObserverResult - trackProp(key: keyof QueryObserverResult): void - getCurrentQuery(): Query - refetch(options?: RefetchOptions): Promise> - fetchOptimistic( - options: ObserverOptionsInput< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >, - ): Promise> - updateResult(): void - onQueryUpdate(): void -} - -interface MutationObserver< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> extends Subscription< - MutationObserverListener -> { - options: MutationObserverOptions - setOptions( - options: MutationObserverOptions< - TData, - TError, - TVariables, - TOnMutateResult - >, - ): void - onMutationUpdate( - action: MutationAction, - ): void - getCurrentResult(): MutationObserverResult< - TData, - TError, - TVariables, - TOnMutateResult - > - reset(): void - mutate( - variables: TVariables, - options?: MutateOptions, - ): Promise -} - -type QueryCacheListener = SharedQueryCacheListener -type MutationCacheListener = SharedMutationCacheListener -type MutationObserverListener = - SharedMutationObserverListener< - DefaultRuntime, - TData, - TError, - TVariables, - TOnMutateResult - > - -/** Structural public class shapes used when importing types without a runtime. */ -interface DefaultRuntime extends RuntimeBinding { - QueryClient: QueryClient - QueryCache: QueryCache - MutationCache: MutationCache - Query: Query< - this['queryFnData'], - this['error'], - this['data'], - this['queryKey'][0] - > - Mutation: Mutation< - this['data'], - this['error'], - this['variables'], - this['onMutateResult'] - > - QueryObserver: QueryObserver< - this['queryFnData'], - this['error'], - this['data'], - this['queryData'], - this['queryKey'][0] - > - MutationObserver: MutationObserver< - this['data'], - this['error'], - this['variables'], - this['onMutateResult'] - > -} - -interface FocusManager extends Subscription { - setEventListener(setup: FocusManagerSetupFn): void - setFocused(focused?: boolean): void - onFocus(): void - isFocused(): boolean -} - -interface OnlineManager extends Subscription { - setEventListener(setup: OnlineManagerSetupFn): void - setOnline(online: boolean): void - isOnline(): boolean -} - -interface TimeoutManager { - setTimeoutProvider( - provider: TimeoutProvider, - ): void - setTimeout(callback: TimeoutCallback, delay: number): ManagedTimerId - clearTimeout(timeoutId: ManagedTimerId | undefined): void - setInterval(callback: TimeoutCallback, delay: number): ManagedTimerId - clearInterval(intervalId: ManagedTimerId | undefined): void -} - -interface QueriesObserver< - TCombinedResult = Array, -> extends Subscription { - destroy(): void - setQueries( - queries: Array, - options?: QueriesObserverOptions, - ): void - getCurrentResult(): Array - getQueries(): Array - getObservers(): Array - createResultReader( - queries: Array>, - options?: QueriesObserverOptions, - ): QueriesObserverResultReader -} - -interface InfiniteQueryObserver< - TQueryFnData = unknown, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> extends QueryObserver< - TQueryFnData, - TError, - TData, - InfiniteData, - TQueryKey -> { - subscribe: Subscription< - InfiniteQueryObserverListener - >['subscribe'] - getCurrentResult: ReplaceReturnType< - QueryObserver< - TQueryFnData, - TError, - TData, - InfiniteData, - TQueryKey - >['getCurrentResult'], - InfiniteQueryObserverResult - > - setOptions( - options: InfiniteObserverOptionsInput< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - ): void - createResultReader( - options: DefaultedInfiniteQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - ): QueryObserverResultReader> - fetchNextPage( - options?: FetchNextPageOptions, - ): Promise> - fetchPreviousPage( - options?: FetchPreviousPageOptions, - ): Promise> -} - -interface CancelledError extends Error { - revert?: boolean - silent?: boolean -} - -type InfiniteObserverOptionsInput< - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey, - TPageParam, -> = SharedInfiniteObserverOptionsInput< - DefaultRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> - -export type { - FocusManager, - OnlineManager, - TimeoutManager, - QueriesObserver, - InfiniteQueryObserver, - CancelledError, -} - -export type { - QueryClient, - QueryCache, - MutationCache, - Query, - Mutation, - QueryObserver, - MutationObserver, - DefaultRuntime, -} diff --git a/packages/query-types/src/environmentManager.ts b/packages/query-types/src/environmentManager.ts deleted file mode 100644 index e2d5f01ecbf..00000000000 --- a/packages/query-types/src/environmentManager.ts +++ /dev/null @@ -1,4 +0,0 @@ -/** - * A function that returns whether the code is running on the server. - */ -export type IsServerValue = () => boolean diff --git a/packages/query-types/src/focusManager.ts b/packages/query-types/src/focusManager.ts deleted file mode 100644 index 5b9171555f0..00000000000 --- a/packages/query-types/src/focusManager.ts +++ /dev/null @@ -1,7 +0,0 @@ -type FocusManagerListener = (focused: boolean) => void - -type FocusManagerSetupFn = ( - setFocused: (focused?: boolean) => void, -) => (() => void) | undefined - -export type { FocusManagerListener, FocusManagerSetupFn } diff --git a/packages/query-types/src/hydration.ts b/packages/query-types/src/hydration.ts deleted file mode 100644 index 55dbb5b7634..00000000000 --- a/packages/query-types/src/hydration.ts +++ /dev/null @@ -1,91 +0,0 @@ -import type { MutationOf, QueryOf, RuntimeBinding } from './binding' -import type { MutationState } from './mutation' -import type { QueryState } from './query' -import type { - DefaultError, - MutationKey, - MutationMeta, - MutationOptions, - MutationScope, - QueryKey, - QueryMeta, - QueryOptions, -} from './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: MutationOf) => boolean - /** Predicate to decide whether a given `Query` should be dehydrated. Defaults to `defaultShouldDehydrateQuery`. */ - shouldDehydrateQuery?: (query: QueryOf) => 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< - TRuntime, - unknown, - DefaultError, - unknown, - unknown - > - } -} - -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' -} - -/** - * 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 -} - -export type { TransformerFn, DehydratedMutation, DehydratedQuery } diff --git a/packages/query-types/src/index.ts b/packages/query-types/src/index.ts deleted file mode 100644 index 6fe9ce3013e..00000000000 --- a/packages/query-types/src/index.ts +++ /dev/null @@ -1,612 +0,0 @@ -import type { DefaultRuntime } from './contracts' -import type { - DehydrateOptions as SharedDehydrateOptions, - HydrateOptions as SharedHydrateOptions, -} from './hydration' -import type { - MutationCacheConfig as SharedMutationCacheConfig, - MutationCacheNotifyEvent as SharedMutationCacheNotifyEvent, -} from './mutationCache' -import type { - FetchContext as SharedFetchContext, - QueryBehavior as SharedQueryBehavior, -} from './query' -import type { - QueryCacheConfig as SharedQueryCacheConfig, - QueryCacheNotifyEvent as SharedQueryCacheNotifyEvent, - QueryStore as SharedQueryStore, -} from './queryCache' -import type { - ObserverOptionsInput as SharedObserverOptionsInput, - QueryObserverResultContext as SharedQueryObserverResultContext, -} from './queryObserver' -import type { - DefaultError, - InfiniteData, - QueryKey, - DefaultOptions as SharedDefaultOptions, - DefaultedInfiniteQueryObserverOptions as SharedDefaultedInfiniteQueryObserverOptions, - DefaultedQueryObserverOptions as SharedDefaultedQueryObserverOptions, - InfiniteQueryExecuteOptions as SharedInfiniteQueryExecuteOptions, - InfiniteQueryObserverOptions as SharedInfiniteQueryObserverOptions, - InvalidateQueryFilters as SharedInvalidateQueryFilters, - MutateFunction as SharedMutateFunction, - MutateFunctionRest as SharedMutateFunctionRest, - MutateOptions as SharedMutateOptions, - MutationFunction as SharedMutationFunction, - MutationFunctionContext as SharedMutationFunctionContext, - MutationObserverBaseResult as SharedMutationObserverBaseResult, - MutationObserverErrorResult as SharedMutationObserverErrorResult, - MutationObserverIdleResult as SharedMutationObserverIdleResult, - MutationObserverLoadingResult as SharedMutationObserverLoadingResult, - MutationObserverOptions as SharedMutationObserverOptions, - MutationObserverResult as SharedMutationObserverResult, - MutationObserverSuccessResult as SharedMutationObserverSuccessResult, - MutationOptions as SharedMutationOptions, - PlaceholderDataFunction as SharedPlaceholderDataFunction, - QueryBooleanOption as SharedQueryBooleanOption, - QueryClientConfig as SharedQueryClientConfig, - QueryExecuteOptions as SharedQueryExecuteOptions, - QueryFunction as SharedQueryFunction, - QueryFunctionContext as SharedQueryFunctionContext, - QueryObserverOptions as SharedQueryObserverOptions, - QueryObserverOptionsBase as SharedQueryObserverOptionsBase, - QueryOptions as SharedQueryOptions, - QueryPersister as SharedQueryPersister, - RefetchQueryFilters as SharedRefetchQueryFilters, - StaleTimeFunction as SharedStaleTimeFunction, - ThrowOnError as SharedThrowOnError, -} from './types' -import type { - MutationFilters as SharedMutationFilters, - QueryFilters as SharedQueryFilters, -} from './utils' - -export type { IsServerValue } from './environmentManager' -export type { DehydratedState } from './hydration' -export type { MutationState, MutationAction } from './mutation' -export type { - QueriesObserverResultReader, - QueriesObserverOptions, -} from './queriesObserver' -export type { - QueryState, - FetchDirection, - FetchMeta, - FetchOptions, - QueryAction, -} from './query' -export type { QueryObserverResultReader } from './queryObserver' -export type { Retryer, RetryValue, RetryDelayValue } from './retryer' -export type { - TimeoutCallback, - ManagedTimerId, - TimeoutProvider, -} from './timeoutManager' -export type { - NonUndefinedGuard, - DistributiveOmit, - OmitKeyof, - Override, - Register, - DefaultError, - QueryKey, - dataTagSymbol, - dataTagErrorSymbol, - 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, - QueryObserverResult, - InfiniteQueryObserverBaseResult, - InfiniteQueryObserverPendingResult, - InfiniteQueryObserverLoadingResult, - InfiniteQueryObserverLoadingErrorResult, - InfiniteQueryObserverRefetchErrorResult, - InfiniteQueryObserverSuccessResult, - InfiniteQueryObserverPlaceholderResult, - DefinedInfiniteQueryObserverResult, - InfiniteQueryObserverResult, - MutationKey, - MutationStatus, - MutationScope, - MutationMeta, - CancelOptions, - SetDataOptions, - NotifyEventType, - NotifyEvent, -} from './types' -export type { - Updater, - QueryTypeFilter, - SkipToken, - DefaultQueryFn, - FetchSignalContext, -} from './utils' -type DehydrateOptions = SharedDehydrateOptions -type HydrateOptions = SharedHydrateOptions -type MutationCacheConfig = SharedMutationCacheConfig -type MutationCacheNotifyEvent = SharedMutationCacheNotifyEvent -type FetchContext< - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey = QueryKey, -> = SharedFetchContext -type QueryBehavior< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = SharedQueryBehavior -type QueryCacheConfig = SharedQueryCacheConfig -type QueryCacheNotifyEvent = SharedQueryCacheNotifyEvent -type QueryStore = SharedQueryStore -type QueryObserverResultContext< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey extends QueryKey, -> = SharedQueryObserverResultContext< - DefaultRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey -> -type ObserverOptionsInput< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = SharedObserverOptionsInput< - DefaultRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey -> -type QueryFunction< - T = unknown, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = SharedQueryFunction -type StaleTimeFunction< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = SharedStaleTimeFunction< - DefaultRuntime, - TQueryFnData, - TError, - TData, - TQueryKey -> -type QueryBooleanOption< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = SharedQueryBooleanOption< - DefaultRuntime, - TQueryFnData, - TError, - TData, - TQueryKey -> -type QueryPersister< - T = unknown, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = SharedQueryPersister -type QueryFunctionContext< - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = SharedQueryFunctionContext -type PlaceholderDataFunction< - TQueryFnData = unknown, - TError = DefaultError, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = SharedPlaceholderDataFunction< - DefaultRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey -> -type QueryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = SharedQueryOptions< - DefaultRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> -type ThrowOnError< - TQueryFnData, - TError, - TQueryData, - TQueryKey extends QueryKey, -> = SharedThrowOnError< - DefaultRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey -> -type QueryObserverOptionsBase< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = SharedQueryObserverOptionsBase< - DefaultRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam -> -type QueryObserverOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = SharedQueryObserverOptions< - DefaultRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam -> -type DefaultedQueryObserverOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = SharedDefaultedQueryObserverOptions< - DefaultRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam -> -type InfiniteQueryObserverOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> = SharedInfiniteQueryObserverOptions< - DefaultRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> -type DefaultedInfiniteQueryObserverOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> = SharedDefaultedInfiniteQueryObserverOptions< - DefaultRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> -type QueryExecuteOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = SharedQueryExecuteOptions< - DefaultRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam -> -type InfiniteQueryExecuteOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> = SharedInfiniteQueryExecuteOptions< - DefaultRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> -type InvalidateQueryFilters = - SharedInvalidateQueryFilters -type RefetchQueryFilters = - SharedRefetchQueryFilters -type MutationFunctionContext = SharedMutationFunctionContext -type MutationFunction< - TData = unknown, - TVariables = unknown, -> = SharedMutationFunction -type MutationOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = SharedMutationOptions< - DefaultRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> -type MutationObserverOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = SharedMutationObserverOptions< - DefaultRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> -type MutateOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = SharedMutateOptions< - DefaultRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> -type MutateFunctionRest< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = SharedMutateFunctionRest< - DefaultRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> -type MutateFunction< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = SharedMutateFunction< - DefaultRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> -type MutationObserverBaseResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = SharedMutationObserverBaseResult< - DefaultRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> -type MutationObserverIdleResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = SharedMutationObserverIdleResult< - DefaultRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> -type MutationObserverLoadingResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = SharedMutationObserverLoadingResult< - DefaultRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> -type MutationObserverErrorResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = SharedMutationObserverErrorResult< - DefaultRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> -type MutationObserverSuccessResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = SharedMutationObserverSuccessResult< - DefaultRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> -type MutationObserverResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = SharedMutationObserverResult< - DefaultRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> -type QueryClientConfig = SharedQueryClientConfig -type DefaultOptions = SharedDefaultOptions< - DefaultRuntime, - TError -> -type QueryFilters = SharedQueryFilters< - DefaultRuntime, - TQueryKey -> -type MutationFilters< - TData = unknown, - TError = DefaultError, - TVariables = unknown, - TOnMutateResult = unknown, -> = SharedMutationFilters< - DefaultRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> -export type { QueryClient } from './contracts' -export type { QueryCache } from './contracts' -export type { MutationCache } from './contracts' -export type { Query } from './contracts' -export type { Mutation } from './contracts' -export type { QueryObserver } from './contracts' -export type { MutationObserver } from './contracts' -export type { - FocusManager, - OnlineManager, - TimeoutManager, - QueriesObserver, - InfiniteQueryObserver, - CancelledError, -} from './contracts' - -export type { - DehydrateOptions, - HydrateOptions, - MutationCacheConfig, - MutationCacheNotifyEvent, - FetchContext, - QueryBehavior, - QueryCacheConfig, - QueryCacheNotifyEvent, - QueryStore, - QueryObserverResultContext, - ObserverOptionsInput, - QueryFunction, - StaleTimeFunction, - QueryBooleanOption, - QueryPersister, - QueryFunctionContext, - PlaceholderDataFunction, - QueryOptions, - ThrowOnError, - QueryObserverOptionsBase, - QueryObserverOptions, - DefaultedQueryObserverOptions, - InfiniteQueryObserverOptions, - DefaultedInfiniteQueryObserverOptions, - QueryExecuteOptions, - InfiniteQueryExecuteOptions, - InvalidateQueryFilters, - RefetchQueryFilters, - MutationFunctionContext, - MutationFunction, - MutationOptions, - MutationObserverOptions, - MutateOptions, - MutateFunctionRest, - MutateFunction, - MutationObserverBaseResult, - MutationObserverIdleResult, - MutationObserverLoadingResult, - MutationObserverErrorResult, - MutationObserverSuccessResult, - MutationObserverResult, - QueryClientConfig, - DefaultOptions, - QueryFilters, - MutationFilters, -} diff --git a/packages/query-types/src/infiniteQueryObserver.ts b/packages/query-types/src/infiniteQueryObserver.ts deleted file mode 100644 index 00a10a13581..00000000000 --- a/packages/query-types/src/infiniteQueryObserver.ts +++ /dev/null @@ -1,47 +0,0 @@ -import type { RuntimeBinding } from './binding' -import type { - DefaultedInfiniteQueryObserverOptions, - InfiniteQueryObserverOptions, - InfiniteQueryObserverResult, - QueryKey, -} from './types' - -type InfiniteQueryObserverListener = ( - result: InfiniteQueryObserverResult, -) => void - -type InfiniteObserverOptionsInput< - TRuntime extends RuntimeBinding, - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey, - TPageParam, -> = - | InfiniteQueryObserverOptions< - TRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - > - | DefaultedInfiniteQueryObserverOptions< - TRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - > - -type ReplaceReturnType< - TFunction extends (...args: Array) => unknown, - TReturn, -> = (...args: Parameters) => TReturn - -export type { - InfiniteQueryObserverListener, - InfiniteObserverOptionsInput, - ReplaceReturnType, -} diff --git a/packages/query-types/src/mutation.ts b/packages/query-types/src/mutation.ts deleted file mode 100644 index bfa57e47dbc..00000000000 --- a/packages/query-types/src/mutation.ts +++ /dev/null @@ -1,120 +0,0 @@ -import type { MutationCacheOf, QueryClientOf, RuntimeBinding } from './binding' -import type { DefaultError, MutationOptions, MutationStatus } from './types' - -interface MutationConfig< - TRuntime extends RuntimeBinding, - TData, - TError, - TVariables, - TOnMutateResult, -> { - client: QueryClientOf - mutationId: number - mutationCache: MutationCacheOf - options: MutationOptions - state?: MutationState -} - -/** - * 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 MutationFailedAction { - type: 'failed' - failureCount: number - error: TError | null -} - -interface PendingAction { - type: 'pending' - isPaused: boolean - variables?: TVariables - context?: TOnMutateResult -} - -interface MutationSuccessAction { - type: 'success' - data: TData -} - -interface MutationErrorAction { - type: 'error' - error: TError -} - -interface MutationPauseAction { - type: 'pause' -} - -interface MutationContinueAction { - type: 'continue' -} - -/** - * The actions a mutation dispatches to update its state, e.g. when it starts, fails, pauses, or - * succeeds. - */ -export type MutationAction = - | MutationContinueAction - | MutationErrorAction - | MutationFailedAction - | PendingAction - | MutationPauseAction - | MutationSuccessAction - -export type { - MutationConfig, - MutationFailedAction, - PendingAction, - MutationSuccessAction, - MutationErrorAction, - MutationPauseAction, - MutationContinueAction, -} diff --git a/packages/query-types/src/mutationCache.ts b/packages/query-types/src/mutationCache.ts deleted file mode 100644 index 37369002369..00000000000 --- a/packages/query-types/src/mutationCache.ts +++ /dev/null @@ -1,130 +0,0 @@ -import type { MutationObserverOf, MutationOf, RuntimeBinding } from './binding' -import type { MutationAction } from './mutation' -import type { - CacheKeyConfig, - DefaultError, - MutationFunctionContext, - MutationKey, - NotifyEvent, -} from './types' - -/** - * 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: MutationOf, - context: MutationFunctionContext, - ) => Promise | unknown - /** Called when any mutation in the cache is successful. */ - onSuccess?: ( - data: unknown, - variables: unknown, - onMutateResult: unknown, - mutation: MutationOf, - context: MutationFunctionContext, - ) => Promise | unknown - /** Called before any mutation in the cache executes. */ - onMutate?: ( - variables: unknown, - mutation: MutationOf, - 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: MutationOf, - context: MutationFunctionContext, - ) => Promise | unknown -} - -interface NotifyEventMutationAdded< - TRuntime extends RuntimeBinding, -> extends NotifyEvent { - type: 'added' - mutation: MutationOf -} - -interface NotifyEventMutationRemoved< - TRuntime extends RuntimeBinding, -> extends NotifyEvent { - type: 'removed' - mutation: MutationOf -} - -interface NotifyEventMutationObserverAdded< - TRuntime extends RuntimeBinding, -> extends NotifyEvent { - type: 'observerAdded' - mutation: MutationOf - observer: MutationObserverOf -} - -interface NotifyEventMutationObserverRemoved< - TRuntime extends RuntimeBinding, -> extends NotifyEvent { - type: 'observerRemoved' - mutation: MutationOf - observer: MutationObserverOf -} - -interface NotifyEventMutationObserverOptionsUpdated< - TRuntime extends RuntimeBinding, -> extends NotifyEvent { - type: 'observerOptionsUpdated' - mutation?: MutationOf - observer: MutationObserverOf -} - -interface NotifyEventMutationUpdated< - TRuntime extends RuntimeBinding, -> extends NotifyEvent { - type: 'updated' - mutation: MutationOf - action: MutationAction -} - -/** - * 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 - -export type { - NotifyEventMutationAdded, - NotifyEventMutationRemoved, - NotifyEventMutationObserverAdded, - NotifyEventMutationObserverRemoved, - NotifyEventMutationObserverOptionsUpdated, - NotifyEventMutationUpdated, - MutationCacheListener, -} diff --git a/packages/query-types/src/mutationObserver.ts b/packages/query-types/src/mutationObserver.ts deleted file mode 100644 index 95da98d5c24..00000000000 --- a/packages/query-types/src/mutationObserver.ts +++ /dev/null @@ -1,20 +0,0 @@ -import type { RuntimeBinding } from './binding' -import type { MutationObserverResult } from './types' - -type MutationObserverListener< - TRuntime extends RuntimeBinding, - TData, - TError, - TVariables, - TOnMutateResult, -> = ( - result: MutationObserverResult< - TRuntime, - TData, - TError, - TVariables, - TOnMutateResult - >, -) => void - -export type { MutationObserverListener } diff --git a/packages/query-types/src/notifyManager.ts b/packages/query-types/src/notifyManager.ts deleted file mode 100644 index 173e937668f..00000000000 --- a/packages/query-types/src/notifyManager.ts +++ /dev/null @@ -1,17 +0,0 @@ -type NotifyCallback = () => void - -type NotifyFunction = (callback: () => void) => void - -type BatchNotifyFunction = (callback: () => void) => void - -type BatchCallsCallback> = (...args: T) => void - -type ScheduleFunction = (callback: () => void) => void - -export type { - NotifyCallback, - NotifyFunction, - BatchNotifyFunction, - BatchCallsCallback, - ScheduleFunction, -} diff --git a/packages/query-types/src/onlineManager.ts b/packages/query-types/src/onlineManager.ts deleted file mode 100644 index f1dfb1e2955..00000000000 --- a/packages/query-types/src/onlineManager.ts +++ /dev/null @@ -1,7 +0,0 @@ -type OnlineManagerListener = (online: boolean) => void - -type OnlineManagerSetupFn = ( - setOnline: OnlineManagerListener, -) => (() => void) | undefined - -export type { OnlineManagerListener, OnlineManagerSetupFn } diff --git a/packages/query-types/src/queriesObserver.ts b/packages/query-types/src/queriesObserver.ts deleted file mode 100644 index a3ea53af738..00000000000 --- a/packages/query-types/src/queriesObserver.ts +++ /dev/null @@ -1,57 +0,0 @@ -import type { QueryObserverOf, RuntimeBinding } from './binding' -import type { QueryObserverResultReader } from './queryObserver' -import type { - DefaultedQueryObserverOptions, - QueryObserverResult, -} from './types' - -type QueriesObserverListener = (result: Array) => void - -type CombineFn = ( - result: Array, -) => TCombinedResult - -/** A cached reader for multiple query results and their combined value. */ -export interface QueriesObserverResultReader< - TCombinedResult, -> extends QueryObserverResultReader> { - /** Track result properties and combine the results with this reader's options. */ - combineResult: (result: Array) => TCombinedResult -} - -type CombineContext = { - result?: Array - combine?: CombineFn - value?: TCombinedResult - queryHashes?: Array -} - -/** - * Options for a `QueriesObserver` that apply to all of its queries at once. - */ -export interface QueriesObserverOptions< - TCombinedResult = Array, -> { - /** - * A function that combines the array of `QueryObserverResult`s (one per - * observed query) into a single value. The combined value is memoized and - * only recomputed when one of the underlying results, the query hashes, or - * the `combine` function itself changes. - * - * Defaults to returning the array of `QueryObserverResult`s unchanged. - */ - combine?: CombineFn -} - -type QueryObserverMatch = { - defaultedQueryOptions: DefaultedQueryObserverOptions - observer: QueryObserverOf - reader?: QueryObserverResultReader -} - -export type { - QueriesObserverListener, - CombineFn, - CombineContext, - QueryObserverMatch, -} diff --git a/packages/query-types/src/query.ts b/packages/query-types/src/query.ts deleted file mode 100644 index 7e983dc670e..00000000000 --- a/packages/query-types/src/query.ts +++ /dev/null @@ -1,258 +0,0 @@ -import type { QueryClientOf, QueryOf, RuntimeBinding } from './binding' -import type { - DefaultError, - FetchStatus, - QueryKey, - QueryOptions, - QueryStatus, -} from './types' - -interface QueryConfig< - TRuntime extends RuntimeBinding, - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey = QueryKey, -> { - client: QueryClientOf - queryKey: TQueryKey - queryHash: string - options?: QueryOptions - defaultOptions?: QueryOptions< - TRuntime, - TQueryFnData, - TError, - TData, - TQueryKey - > - state?: QueryState -} - -/** - * The raw state stored on a `Query` instance. This is the underlying state - * that observer results (e.g. `QueryObserverResult`) are derived from. - */ -export interface QueryState { - /** - * The last successfully resolved data for the query. - */ - data: TData | undefined - /** - * The number of times the query has successfully resolved. - */ - dataUpdateCount: number - /** - * The timestamp for when the query most recently returned the `status` as `"success"`. - */ - dataUpdatedAt: number - /** - * The error object for the query, if the last attempt resulted in an error. - * - Defaults to `null`. - */ - error: TError | null - /** - * The sum of all errors, incremented every time the query resolves with an error. - */ - errorUpdateCount: number - /** - * The timestamp for when the query most recently returned the `status` as `"error"`. - */ - errorUpdatedAt: number - /** - * The failure count for the current fetch. - * - Incremented every time the fetch fails. - * - Reset to `0` when the fetch succeeds. - */ - fetchFailureCount: number - /** - * The reason the current fetch failed, as reported by the retryer. - * - Reset to `null` when the fetch succeeds. - */ - fetchFailureReason: TError | null - /** - * Metadata passed to the currently in-flight (or most recent) fetch, e.g. the - * `fetchMore` direction for infinite queries. - */ - fetchMeta: FetchMeta | null - /** - * Whether the query has been marked as invalidated via `invalidate()`. - * - Reset to `false` whenever the query resolves successfully. - */ - isInvalidated: boolean - /** - * The status of the query. - * - `pending` if there's no cached data and no attempt was finished yet. - * - `error` if the last attempt resulted in an error. - * - `success` if the query has data. - */ - status: QueryStatus - /** - * The fetch status of the query. - * - `fetching`: the `queryFn` is currently executing. - * - `paused`: a fetch wanted to run but has been paused (see network mode). - * - `idle`: the query is not fetching. - */ - fetchStatus: FetchStatus -} - -/** - * The context passed to a {@link QueryBehavior}'s `onFetch`, which can replace `fetchFn` to change - * how the query fetches (e.g. to fetch pages for an infinite query). - */ -export interface FetchContext< - TRuntime extends RuntimeBinding, - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey = QueryKey, -> { - /** - * The function that runs the fetch. By default it calls `queryFn`; `onFetch` can replace it. - */ - fetchFn: () => unknown | Promise - /** - * The options of this fetch. - */ - fetchOptions?: FetchOptions - /** - * The `AbortSignal` that aborts when the fetch is cancelled. - */ - signal: AbortSignal - /** - * The options of the query. - */ - options: QueryOptions - /** - * The `QueryClient` the query belongs to. - */ - client: QueryClientOf - /** - * The key of the query. - */ - queryKey: TQueryKey - /** - * The state of the query when the fetch starts. - */ - state: QueryState -} - -/** - * Customizes how a query fetches, e.g. the behavior that fetches the pages of an infinite query. - */ -export interface QueryBehavior< - TRuntime extends RuntimeBinding, - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> { - /** - * Called before each fetch of the query, e.g. to replace `fetchFn` in the context. - */ - onFetch: ( - context: FetchContext, - query: QueryOf, - ) => void -} - -/** - * The direction an infinite query fetches in: `'forward'` for the next page, `'backward'` for the - * previous one. - */ -export type FetchDirection = 'forward' | 'backward' - -/** - * Metadata for a fetch, e.g. the direction when an infinite query fetches more pages. - */ -export interface FetchMeta { - /** - * Set when an infinite query fetches another page, with the direction to fetch in. - */ - fetchMore?: { direction: FetchDirection } -} - -/** - * Options for a single fetch of a query. - */ -export interface FetchOptions { - /** - * If `true`, an in-flight fetch is cancelled before starting a new one, when the query already - * has data. Otherwise, the in-flight fetch is reused. - */ - cancelRefetch?: boolean - /** - * Metadata of the fetch, stored in the query's `fetchMeta` state. - */ - meta?: FetchMeta - /** - * A promise to use for the first attempt instead of calling `fetchFn`, e.g. a pending promise - * restored by `hydrate`. - */ - initialPromise?: Promise -} - -interface QueryFailedAction { - type: 'failed' - failureCount: number - error: TError -} - -interface FetchAction { - type: 'fetch' - meta?: FetchMeta -} - -interface QuerySuccessAction { - data: TData | undefined - type: 'success' - dataUpdatedAt?: number - manual?: boolean -} - -interface QueryErrorAction { - type: 'error' - error: TError -} - -interface InvalidateAction { - type: 'invalidate' -} - -interface QueryPauseAction { - type: 'pause' -} - -interface QueryContinueAction { - type: 'continue' -} - -interface SetStateAction { - type: 'setState' - state: Partial> -} - -/** - * The actions a query dispatches to update its state, e.g. when it starts fetching, fails, or - * succeeds. - */ -export type QueryAction = - | QueryContinueAction - | QueryErrorAction - | QueryFailedAction - | FetchAction - | InvalidateAction - | QueryPauseAction - | SetStateAction - | QuerySuccessAction - -export type { - QueryConfig, - QueryFailedAction, - FetchAction, - QuerySuccessAction, - QueryErrorAction, - InvalidateAction, - QueryPauseAction, - QueryContinueAction, - SetStateAction, -} diff --git a/packages/query-types/src/queryCache.ts b/packages/query-types/src/queryCache.ts deleted file mode 100644 index 772c1eea27b..00000000000 --- a/packages/query-types/src/queryCache.ts +++ /dev/null @@ -1,147 +0,0 @@ -import type { QueryObserverOf, QueryOf, RuntimeBinding } from './binding' -import type { QueryAction } from './query' -import type { - CacheKeyConfig, - DefaultError, - NotifyEvent, - QueryKey, -} from './types' - -/** - * Global callbacks that fire for every query handled by a `QueryCache`, regardless of which - * component or observer triggered it. Unlike `QueryClient`'s `defaultOptions`, which a query can - * override, these callbacks are always called. Unlike `MutationCacheConfig`'s callbacks, these - * are fire-and-forget: their return value is not awaited before the query settles. - */ -export interface QueryCacheConfig { - /** - * Configures query key comparison and hashing globally. - * `equalityFn` compares individual values during partial matching and defaults to strict equality. - * `hashFn` hashes query keys and defaults to `hashKey`. - */ - queryKey?: CacheKeyConfig - /** Called when any query in the cache encounters an error. */ - onError?: ( - error: DefaultError, - query: QueryOf, - ) => void - /** Called when any query in the cache is successful. */ - onSuccess?: ( - data: unknown, - query: QueryOf, - ) => void - /** Called when any query in the cache is settled, either successfully or with an error. */ - onSettled?: ( - data: unknown | undefined, - error: DefaultError | null, - query: QueryOf, - ) => void -} - -interface NotifyEventQueryAdded< - TRuntime extends RuntimeBinding, -> extends NotifyEvent { - type: 'added' - query: QueryOf -} - -interface NotifyEventQueryRemoved< - TRuntime extends RuntimeBinding, -> extends NotifyEvent { - type: 'removed' - query: QueryOf -} - -interface NotifyEventQueryUpdated< - TRuntime extends RuntimeBinding, -> extends NotifyEvent { - type: 'updated' - query: QueryOf - action: QueryAction -} - -interface NotifyEventQueryObserverAdded< - TRuntime extends RuntimeBinding, -> extends NotifyEvent { - type: 'observerAdded' - query: QueryOf - observer: QueryObserverOf -} - -interface NotifyEventQueryObserverRemoved< - TRuntime extends RuntimeBinding, -> extends NotifyEvent { - type: 'observerRemoved' - query: QueryOf - observer: QueryObserverOf -} - -interface NotifyEventQueryObserverResultsUpdated< - TRuntime extends RuntimeBinding, -> extends NotifyEvent { - type: 'observerResultsUpdated' - query: QueryOf -} - -interface NotifyEventQueryObserverOptionsUpdated< - TRuntime extends RuntimeBinding, -> extends NotifyEvent { - type: 'observerOptionsUpdated' - query: QueryOf - observer: QueryObserverOf -} - -/** - * The event passed to a `QueryCache` subscriber. Fired whenever a query is added or removed from - * the cache, its state is updated (e.g. via `query.setState` or `queryClient.removeQueries`), or - * one of its observers is added, removed, or has its results or options updated. - */ -export type QueryCacheNotifyEvent = - | NotifyEventQueryAdded - | NotifyEventQueryRemoved - | NotifyEventQueryUpdated - | NotifyEventQueryObserverAdded - | NotifyEventQueryObserverRemoved - | NotifyEventQueryObserverResultsUpdated - | NotifyEventQueryObserverOptionsUpdated - -type QueryCacheListener = ( - event: QueryCacheNotifyEvent, -) => void - -/** - * The store a `QueryCache` keeps its queries in, keyed by query hash. - */ -export interface QueryStore { - /** - * Returns whether a query with the given hash is stored. - */ - has: (queryHash: string) => boolean - /** - * Stores a query under its hash. - */ - set: (queryHash: string, query: QueryOf) => void - /** - * Returns the query with the given hash, if any. - */ - get: (queryHash: string) => QueryOf | undefined - /** - * Removes the query with the given hash. - */ - delete: (queryHash: string) => void - /** - * Returns an iterator over all stored queries. - */ - values: () => IterableIterator> -} - -export type { - NotifyEventQueryAdded, - NotifyEventQueryRemoved, - NotifyEventQueryUpdated, - NotifyEventQueryObserverAdded, - NotifyEventQueryObserverRemoved, - NotifyEventQueryObserverResultsUpdated, - NotifyEventQueryObserverOptionsUpdated, - QueryCacheListener, -} diff --git a/packages/query-types/src/queryClient.ts b/packages/query-types/src/queryClient.ts deleted file mode 100644 index 85738231202..00000000000 --- a/packages/query-types/src/queryClient.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { RuntimeBinding } from './binding' -import type { skipToken } from './symbols' -import type { - MutationKey, - MutationOptions, - OmitKeyof, - QueryKey, - QueryOptions, -} from './types' - -type WithoutSkipToken = Omit & { - queryFn?: Exclude -} - -interface QueryDefaults { - queryKey: QueryKey - defaultOptions: OmitKeyof, 'queryKey'> -} - -interface MutationDefaults { - mutationKey: MutationKey - defaultOptions: MutationOptions -} - -export type { WithoutSkipToken, QueryDefaults, MutationDefaults } diff --git a/packages/query-types/src/queryObserver.ts b/packages/query-types/src/queryObserver.ts deleted file mode 100644 index 74f76ffd7f3..00000000000 --- a/packages/query-types/src/queryObserver.ts +++ /dev/null @@ -1,122 +0,0 @@ -import type { QueryOf, RuntimeBinding } from './binding' -import type { FetchOptions, QueryState } from './query' -import type { - DefaultError, - DefaultedQueryObserverOptions, - PlaceholderValue, - QueryKey, - QueryObserverOptions, - QueryObserverResult, - QueryOptions, -} from './types' - -type QueryObserverListener = ( - result: QueryObserverResult, -) => void - -interface ObserverFetchOptions extends FetchOptions { - throwOnError?: boolean -} - -/** A cached view of an observer for one set of render options. */ -export interface QueryObserverResultReader { - /** Read the result, retaining its reference while all fields are unchanged. */ - getSnapshot: () => TResult - /** Apply this reader's options and reusable computation state after commit. */ - commit: () => void -} - -type ProjectionFailure = { - error: TError - errorUpdatedAt: number -} - -/** - * Selection and placeholder computation state shared by reads of the same result. - * @internal - */ -export interface QueryObserverResultContext< - TRuntime extends RuntimeBinding, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey extends QueryKey, -> { - /** The memo key and failure of the most recent selection. */ - selection?: { - key: { - input: TQueryData - select: (data: TQueryData) => TData - structuralSharing: QueryOptions< - TRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey - >['structuralSharing'] - } - failure?: ProjectionFailure - } - /** The last successful selection, used if selection fails. */ - selected?: { - data: TData - query?: QueryOf - } - /** The unselected placeholder or factory error. */ - placeholder?: { - key: { - placeholderData: - | PlaceholderValue - | undefined - structuralSharing: QueryOptions< - TRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey - >['structuralSharing'] - previousQuery: - | QueryOf - | undefined - previousState: QueryState | undefined - previousOptions: - | QueryOptions - | undefined - } - sourceQuery?: QueryOf - input: TQueryData | undefined - failure?: ProjectionFailure - } -} - -/** - * Options supplied to an observer by a caller or already resolved by the client. - * @internal - */ -export type ObserverOptionsInput< - TRuntime extends RuntimeBinding, - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = - | QueryObserverOptions< - TRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - > - | DefaultedQueryObserverOptions< - TRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - > - -export type { QueryObserverListener, ObserverFetchOptions, ProjectionFailure } diff --git a/packages/query-types/src/retryer.ts b/packages/query-types/src/retryer.ts deleted file mode 100644 index c156ad94458..00000000000 --- a/packages/query-types/src/retryer.ts +++ /dev/null @@ -1,76 +0,0 @@ -import type { CancelOptions, DefaultError, NetworkMode } from './types' - -interface RetryerConfig { - fn: () => TData | Promise - initialPromise?: Promise - onCancel?: (error: TError) => void - onFail?: (failureCount: number, error: TError) => void - onPause?: () => void - onContinue?: () => void - retry?: RetryValue - retryDelay?: RetryDelayValue - networkMode: NetworkMode | undefined - canRun: () => boolean -} - -/** - * Runs a function with retries, and can pause, continue, or cancel it. Queries and mutations use - * one for each fetch or execution. - */ -export interface Retryer { - /** - * The promise that resolves with the data, or rejects once retries are exhausted or it is - * cancelled. - */ - promise: Promise - /** - * Cancels the run, rejecting `promise` with a `CancelledError`. - */ - cancel: (cancelOptions?: CancelOptions) => void - /** - * Resumes a paused run, and returns `promise`. - */ - continue: () => Promise - /** - * Stops further retries. The current attempt still finishes. - */ - cancelRetry: () => void - /** - * Allows retries again after `cancelRetry`. - */ - continueRetry: () => void - /** - * Returns whether the run can start now, based on the network mode and `canRun`. - */ - canStart: () => boolean - /** - * Starts the run, or waits until it can start, and returns `promise`. - */ - start: () => Promise - /** - * Returns whether `promise` is still pending, resolved, or rejected. - */ - status: () => 'pending' | 'resolved' | 'rejected' -} - -type RetryerStatus = 'pending' | 'resolved' | 'rejected' - -/** @inline */ -export type RetryValue = boolean | number | ShouldRetryFunction - -/** @inline */ -export type ShouldRetryFunction = ( - failureCount: number, - error: TError, -) => boolean - -/** @inline */ -export type RetryDelayValue = number | RetryDelayFunction - -/** @inline */ -export type RetryDelayFunction = ( - failureCount: number, - error: TError, -) => number - -export type { RetryerConfig, RetryerStatus } diff --git a/packages/query-types/src/streamedQuery.ts b/packages/query-types/src/streamedQuery.ts deleted file mode 100644 index dbd269045ba..00000000000 --- a/packages/query-types/src/streamedQuery.ts +++ /dev/null @@ -1,62 +0,0 @@ -import type { RuntimeBinding } from './binding' -import type { QueryFunctionContext, QueryKey } from './types' - -type BaseStreamedQueryParams< - TRuntime extends RuntimeBinding, - TQueryFnData, - TQueryKey extends QueryKey, -> = { - /** Returns an `AsyncIterable` or a promise that resolves to one. */ - streamFn: ( - context: QueryFunctionContext, - ) => AsyncIterable | Promise> - /** - * Defines how refetches are handled. - * - `'reset'` (default): resets the query to its initial state before reading the stream. - * - `'append'`: appends new data to the existing data. - * - `'replace'`: writes all data to the cache once the stream ends. - */ - refetchMode?: 'append' | 'reset' | 'replace' -} - -type SimpleStreamedQueryParams< - TRuntime extends RuntimeBinding, - TQueryFnData, - TQueryKey extends QueryKey, -> = BaseStreamedQueryParams & { - reducer?: never - initialValue?: never -} - -type ReducibleStreamedQueryParams< - TRuntime extends RuntimeBinding, - TQueryFnData, - TData, - TQueryKey extends QueryKey, -> = BaseStreamedQueryParams & { - /** - * Combines the accumulated data with the next chunk. Provide `initialValue` with a custom reducer. - */ - reducer: (acc: TData, chunk: TQueryFnData) => TData - /** - * The starting value for the reducer when there is no cached data or when - * `refetchMode` is `'replace'` during a refetch. - */ - initialValue: TData -} - -type StreamedQueryParams< - TRuntime extends RuntimeBinding, - TQueryFnData, - TData, - TQueryKey extends QueryKey, -> = - | SimpleStreamedQueryParams - | ReducibleStreamedQueryParams - -export type { - BaseStreamedQueryParams, - SimpleStreamedQueryParams, - ReducibleStreamedQueryParams, - StreamedQueryParams, -} diff --git a/packages/query-types/src/symbols.ts b/packages/query-types/src/symbols.ts deleted file mode 100644 index 290b51bdc7c..00000000000 --- a/packages/query-types/src/symbols.ts +++ /dev/null @@ -1,26 +0,0 @@ -declare const dataTagSymbol: unique symbol -type dataTagSymbol = typeof dataTagSymbol - -declare const dataTagErrorSymbol: unique symbol -type dataTagErrorSymbol = typeof dataTagErrorSymbol - -declare const unsetMarker: unique symbol -type unsetMarker = typeof unsetMarker - -declare const skipToken: unique symbol -type skipToken = typeof skipToken - -declare const defaultQueryFn: unique symbol -type defaultQueryFn = typeof defaultQueryFn - -declare const fetchSignal: unique symbol -type fetchSignal = typeof fetchSignal - -export type { - dataTagSymbol, - dataTagErrorSymbol, - unsetMarker, - skipToken, - defaultQueryFn, - fetchSignal, -} diff --git a/packages/query-types/src/timeoutManager.ts b/packages/query-types/src/timeoutManager.ts deleted file mode 100644 index 96b1ed69ccc..00000000000 --- a/packages/query-types/src/timeoutManager.ts +++ /dev/null @@ -1,51 +0,0 @@ -/** - * {@link TimeoutManager} does not support passing arguments to the callback. - * - * `(_: void)` is the argument type inferred by TypeScript's default typings for - * `setTimeout(cb, number)`. - * If we don't accept a single void argument, then - * `new Promise(resolve => timeoutManager.setTimeout(resolve, N))` is a type error. - */ -export type TimeoutCallback = (_: void) => void - -/** - * Wrapping `setTimeout` is awkward from a typing perspective because platform - * typings may extend the return type of `setTimeout`. For example, NodeJS - * typings add `NodeJS.Timeout`; but a non-default `timeoutManager` may not be - * able to return such a type. - */ -export type ManagedTimerId = number | { [Symbol.toPrimitive]: () => number } - -/** - * Backend for timer functions. - * - * Timers are performance-sensitive: short-lived timers (delays under a few seconds) tend to be - * latency-sensitive, while long-lived ones may benefit more from coalescing — batching timers - * with similar deadlines together — which the default provider (backed by the platform's global - * `setTimeout`/`setInterval`) does not do. A custom provider can implement coalescing, and can - * also support delays longer than the ~24-day maximum of the global `setTimeout`. - */ -export type TimeoutProvider = - { - /** - * Schedules `callback` to run once after `delay` milliseconds, like the global `setTimeout`. - */ - readonly setTimeout: (callback: TimeoutCallback, delay: number) => TTimerId - /** - * Cancels a timeout scheduled with `setTimeout`. - */ - readonly clearTimeout: (timeoutId: TTimerId | undefined) => void - - /** - * Schedules `callback` to run every `delay` milliseconds, like the global `setInterval`. - */ - readonly setInterval: (callback: TimeoutCallback, delay: number) => TTimerId - /** - * Cancels an interval scheduled with `setInterval`. - */ - readonly clearInterval: (intervalId: TTimerId | undefined) => void - } - -type SystemTimerId = ReturnType - -export type { SystemTimerId } diff --git a/packages/query-types/src/types.ts b/packages/query-types/src/types.ts deleted file mode 100644 index 6e421e2d2b5..00000000000 --- a/packages/query-types/src/types.ts +++ /dev/null @@ -1,2585 +0,0 @@ -import type { - MutationCacheOf, - QueryCacheOf, - QueryClientOf, - QueryOf, - RefetchIntervalOf, - RuntimeBinding, -} from './binding' -import type { DehydrateOptions, HydrateOptions } from './hydration' -import type { MutationState } from './mutation' -import type { RetryDelayValue, RetryValue } from './retryer' -import type { - unsetMarker as UnsetMarker, - dataTagErrorSymbol, - dataTagSymbol, -} from './symbols' -import type { - DefaultQueryFn, - QueryFilters, - QueryTypeFilter, - SkipToken, -} from './utils' - -/** - * Excludes `undefined` from `T`. Used where a value must be defined, such as the data type that a - * defined `initialData` resolves to. - */ -export type NonUndefinedGuard = T extends undefined ? never : T - -/** - * Like `Omit`, but applied to each member of a union separately, so each member keeps its own keys. - */ -export type DistributiveOmit< - TObject, - TKey extends keyof TObject, -> = TObject extends any ? Omit : never - -/** - * Like `Omit`, but by default (`'strictly'`) `TKey` must be a key of `TObject`, so omitting a key - * that doesn't exist is a type error. Pass `'safely'` to allow other keys too. - */ -export type OmitKeyof< - TObject, - TKey extends (TStrictly extends 'safely' - ? | keyof TObject - | (string & Record) - | (number & Record) - | (symbol & Record) - : keyof TObject), - TStrictly extends 'strictly' | 'safely' = 'strictly', -> = Omit - -/** - * Replaces the types of the properties of `TTargetA` that also exist in `TTargetB` with their types - * in `TTargetB`. Properties that only exist in `TTargetB` are not added. - */ -export type Override = { - [AKey in keyof TTargetA]: AKey extends keyof TTargetB - ? TTargetB[AKey] - : TTargetA[AKey] -} - -/** - * The interface to augment via declaration merging to override Query's default types repository-wide. - * Each field it declares replaces the default of the matching type: `defaultError` for {@link DefaultError}, - * `queryKey` for {@link QueryKey}, `mutationKey` for {@link MutationKey}, `queryMeta` for {@link QueryMeta} and - * `mutationMeta` for {@link MutationMeta}. Leave a field out to keep that type's default. - * Augment the module you install — `@tanstack/react-query`, `@tanstack/vue-query`, - * `@tanstack/solid-query`, `@tanstack/svelte-query`, `@tanstack/preact-query`, - * `@tanstack/angular-query` or `@tanstack/lit-query`. Augmenting `@tanstack/query-core` - * works too and covers every adapter at once. - * @example - * ```ts - * // Use the module you installed — here, the React adapter. - * declare module '@tanstack/react-query' { - * interface Register { - * defaultError: AxiosError - * } - * } - * ``` - */ -export interface Register { - // defaultError: Error - // queryMeta: Record - // mutationMeta: Record - // queryKey: ReadonlyArray - // mutationKey: ReadonlyArray -} - -/** - * The error type used wherever an error is not given an explicit type parameter. - * Defaults to `Error`; declare `defaultError` on {@link Register} to change it everywhere at once. - */ -export type DefaultError = Register extends { - defaultError: infer TError -} - ? TError - : Error - -/** - * The type of a query key — the serializable array that identifies a query in the cache. - * Defaults to `ReadonlyArray`; declare `queryKey` on {@link Register} to narrow it repository-wide. - */ -export type QueryKey = Register extends { - queryKey: infer TQueryKey -} - ? TQueryKey extends ReadonlyArray - ? TQueryKey - : TQueryKey extends Array - ? TQueryKey - : ReadonlyArray - : ReadonlyArray - -export type { dataTagSymbol } from './symbols' - -export type { dataTagErrorSymbol } from './symbols' - -export type { unsetMarker as UnsetMarker } from './symbols' - -/** - * Matches any type that has been tagged with {@link DataTag}, whatever its data and error types. - */ -export type AnyDataTag = { - /** - * The data type the key was tagged with. - */ - [dataTagSymbol]: any - /** - * The error type the key was tagged with. - */ - [dataTagErrorSymbol]: any -} - -/** - * Tags `TType` (usually a query key) with a data type and an optional error type, so that APIs that - * receive it, like `queryClient.getQueryData`, can infer them. A type that is already tagged is - * returned as is. - */ -export type DataTag< - TType, - TValue, - TError = UnsetMarker, -> = TType extends AnyDataTag - ? TType - : TType & { - [dataTagSymbol]: TValue - [dataTagErrorSymbol]: TError - } - -/** - * An object whose `queryKey` is tagged with {@link DataTag}, like the options returned by - * `queryOptions`. - */ -export type QueryKeyWithDataTag< - TQueryKey extends QueryKey = QueryKey, - TQueryFnData = unknown, - TError = DefaultError, -> = { - /** - * The query key, tagged with the query's data and error types. - */ - queryKey: DataTag -} - -/** - * The data type tagged on a query key by {@link DataTag}, or `TQueryFnData` if the key is not - * tagged. - */ -export type InferDataFromTag = - TTaggedQueryKey extends DataTag - ? TaggedValue - : TQueryFnData - -/** - * The error type tagged on a query key by {@link DataTag}, or `TError` if the key is not tagged or - * was tagged without an error type. - */ -export type InferErrorFromTag = - TTaggedQueryKey extends DataTag - ? TaggedError extends UnsetMarker - ? TError - : TaggedError - : TError - -/** @inline */ -export type QueryFunction< - TRuntime extends RuntimeBinding, - T = unknown, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = ( - context: QueryFunctionContext, -) => T | Promise - -/** @inline */ -export type StaleTime = number | 'static' - -/** @inline */ -export type StaleTimeFunction< - TRuntime extends RuntimeBinding, - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = - | StaleTime - | (( - query: QueryOf, - ) => StaleTime) - -/** @inline */ -export type QueryBooleanOption< - TRuntime extends RuntimeBinding, - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = - | boolean - | (( - query: QueryOf, - ) => boolean) - -/** @inline */ -export type QueryPersister< - TRuntime extends RuntimeBinding, - T = unknown, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = [TPageParam] extends [never] - ? ( - queryFn: QueryFunction, - context: QueryFunctionContext, - query: QueryOf, - ) => T | Promise - : ( - queryFn: QueryFunction, - context: QueryFunctionContext, - query: QueryOf, - ) => T | Promise - -/** - * The object passed to `queryFn`: the `QueryClient`, the `queryKey`, an `AbortSignal` that aborts - * when the query is cancelled, the query's `meta`, and for infinite queries the `pageParam` of the - * page being fetched. - */ -export type QueryFunctionContext< - TRuntime extends RuntimeBinding, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = [TPageParam] extends [never] - ? { - client: QueryClientOf - queryKey: TQueryKey - signal: AbortSignal - meta: QueryMeta | undefined - pageParam?: unknown - } - : { - client: QueryClientOf - queryKey: TQueryKey - signal: AbortSignal - pageParam: TPageParam - meta: QueryMeta | undefined - } - -/** @inline */ -export type InitialDataFunction = () => T | undefined - -// oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes every function-like value, including constructors, from the value branch -type NonFunctionGuard = T extends Function ? never : T - -/** @inline */ -export type PlaceholderDataFunction< - TRuntime extends RuntimeBinding, - TQueryFnData = unknown, - TError = DefaultError, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = ( - previousData: TQueryData | undefined, - previousQuery: - | QueryOf - | undefined, -) => TQueryData | undefined - -/** - * The `placeholderData` function of a query in `useQueries` and its counterparts. Unlike - * {@link PlaceholderDataFunction}, it receives no previous data or query, because the number of - * queries can differ between renders. - */ -export type QueriesPlaceholderDataFunction = ( - previousData: undefined, - previousQuery: undefined, -) => TQueryData | undefined - -/** @inline */ -export type EqualityFn = (a: unknown, b: unknown) => boolean - -/** @inline */ -export type CacheKeyHashFunction< - TCacheKey extends ReadonlyArray = ReadonlyArray, -> = (cacheKey: TCacheKey) => string - -/** Configures the comparison and hashing of query or mutation keys for a cache. */ -export interface CacheKeyConfig< - TCacheKey extends ReadonlyArray = ReadonlyArray, -> { - /** - * Function used to compare values while partially matching keys. - * Defaults to strict equality. - */ - equalityFn?: EqualityFn - /** - * Function used to hash keys globally. - */ - hashFn?: CacheKeyHashFunction -} - -/** @inline */ -export type GetPreviousPageParamFunction = ( - firstPage: TQueryFnData, - allPages: Array, - firstPageParam: TPageParam, - allPageParams: Array, -) => TPageParam | undefined | null - -/** @inline */ -export type GetNextPageParamFunction = ( - lastPage: TQueryFnData, - allPages: Array, - lastPageParam: TPageParam, - allPageParams: Array, -) => TPageParam | undefined | null - -/** - * The data shape of an infinite query: every page fetched so far, plus the page param each one was fetched with. - * `pages` and `pageParams` are index-aligned — `pageParams[i]` is the param that produced `pages[i]`. - */ -export interface InfiniteData { - /** - * The data of every page fetched so far, in order. - */ - pages: Array - /** - * The page param each page was fetched with, aligned by index with `pages`. - */ - pageParams: Array -} - -/** - * The type of the `meta` object that can be attached to a query and read back from `queryFn`, callbacks and - * cache-level handlers. Defaults to `Record`; declare `queryMeta` on {@link Register} to narrow it. - */ -export type QueryMeta = Register extends { - queryMeta: infer TQueryMeta -} - ? TQueryMeta extends Record - ? TQueryMeta - : Record - : Record - -/** @inline */ -export type NetworkMode = 'online' | 'always' | 'offlineFirst' - -/** @inline */ -export type NotifyOnChangeProps = 'all' | 'none' - -/** - * The options of a query itself — its `queryKey`, `queryFn`, retries, `gcTime`, `initialData`, - * `meta`, and so on — shared by observers and the `QueryClient` methods that fetch queries. - */ -export interface QueryOptions< - TRuntime extends RuntimeBinding, - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> { - /** - * If `false`, failed queries will not retry by default. - * If `true`, failed queries will retry infinitely. - * If set to an integer number, e.g. 3, failed queries will retry until the failed query count meets that number. - * If set to a function `(failureCount, error) => boolean` failed queries will retry until the function returns false. - * - * Defaults to `3` on the client and `0` on the server. - */ - retry?: RetryValue - /** - * The delay in milliseconds before a retry. Use a number for a fixed delay or a function that receives - * the failure count and error and returns the delay. The count starts at 0 for the first retry. - * - * A function like `attempt => Math.min(1000 * 2 ** attempt, 30000)` applies exponential - * backoff. - * - * A function like `attempt => attempt * 1000` applies linear backoff. - * - * By default, each retry waits a random duration from 80% to 100% of the base delay. - * The base delay starts at 1 second and doubles for each retry, up to 30 seconds. - */ - retryDelay?: RetryDelayValue - /** - * Controls whether a query is allowed to run based on the current network connectivity. - * @defaultValue 'online' - * @see [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. - */ - networkMode?: NetworkMode - /** - * The time in milliseconds that unused/inactive cache data remains in memory. - * When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. - * When different garbage collection times are specified, the longest one will be used. - * Setting it to `Infinity` will disable garbage collection. - * - * Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. - * - * Note: the maximum allowed time is about 24 days, imposed by `setTimeout`'s 32-bit signed integer delay — see - * `timeoutManager.setTimeoutProvider` for a workaround. - */ - gcTime?: number - /** - * The function that the query will use to request data. - * Pass `defaultQueryFn` to use the function configured in the client's query defaults. - * Pass `skipToken` to disable a query without a function where supported. - * Receives a {@link QueryFunctionContext}. - * Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. - */ - queryFn?: - | QueryFunction - | SkipToken - | DefaultQueryFn - /** - * This option can be used to persist the result of a query to an external storage, bypassing the need to actually - * call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. - */ - persister?: QueryPersister< - TRuntime, - TQueryFnData, - NoInfer, - TPageParam - > - /** - * The cache key. If omitted, the query cache computes it from `queryKey` - * using its configured `hashFn` or the default hash function. - */ - queryHash?: string - /** - * The query key to use for this query. - * - * The query key will be hashed into a stable hash. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) - * for more information. - * - * The query will automatically update when this key changes (as long as `enabled` is not set to `false`). - */ - queryKey?: TQueryKey - /** - * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been - * created or cached yet). - * If set to a function, the function will be called **once** during the shared/root query initialization, and be - * expected to synchronously return the initial data. - * Initial data is considered stale by default unless a `staleTime` has been set. - * `initialData` **is persisted** to the cache. - */ - initialData?: TData | InitialDataFunction - /** - * If set, this value will be used as the time (in milliseconds) of when the `initialData` itself was last updated. - */ - initialDataUpdatedAt?: number | (() => number | undefined) - /** - * Set this to `false` to disable structural sharing between query results. - * Set this to a function which accepts the old and new data and returns resolved data of the same type to implement custom structural sharing logic. - * @defaultValue true - */ - structuralSharing?: - | boolean - | ((oldData: unknown | undefined, newData: unknown) => unknown) - /** @internal */ - _defaulted?: boolean - /** @internal */ - _type?: 'infinite' - /** - * Additional payload to be stored on each query. - * Use this property to pass information that can be used in other places. - */ - meta?: QueryMeta - /** - * Maximum number of pages to store in the data of an infinite query. - */ - maxPages?: number -} - -/** - * Holds the `initialPageParam` option that every infinite query requires. - */ -export interface InitialPageParam { - /** - * The page param to start from when an infinite query has no pages yet. - * It is passed to `queryFn` as `pageParam` for the first page; every page after that gets the - * value returned by `getNextPageParam` or `getPreviousPageParam`. - * It only applies while the query has no pages: once a first page exists, refetching starts from - * that page's own param instead. - */ - initialPageParam: TPageParam -} - -/** - * The page param options of an infinite query: `initialPageParam`, and the `getNextPageParam` and - * `getPreviousPageParam` functions that compute the params of the pages around it. - */ -export interface InfiniteQueryPageParamsOptions< - TQueryFnData = unknown, - TPageParam = unknown, -> extends InitialPageParam { - /** - * This function can be set to automatically get the previous cursor for infinite queries. - * The result will also be used to determine the value of `hasPreviousPage`. - */ - getPreviousPageParam?: GetPreviousPageParamFunction - /** - * This function can be set to automatically get the next cursor for infinite queries. - * The result will also be used to determine the value of `hasNextPage`. - */ - getNextPageParam: GetNextPageParamFunction -} - -/** @inline */ -export type ThrowOnError< - TRuntime extends RuntimeBinding, - TQueryFnData, - TError, - TQueryData, - TQueryKey extends QueryKey, -> = - | boolean - | (( - error: TError, - query: QueryOf, - ) => boolean) - -/** A raw placeholder value or the callback that supplies it for a query. */ -export type PlaceholderValue< - TRuntime extends RuntimeBinding, - TQueryData, - TError, - TQueryKey extends QueryKey, -> = - | NonFunctionGuard - | PlaceholderDataFunction< - TRuntime, - NonFunctionGuard, - TError, - NonFunctionGuard, - TQueryKey - > - -// An adapter can pair an option with its optional runtime implementation. -type ProjectionOption = - TRuntime extends Record - ? readonly [feature: TImplementation, value: TValue] - : TValue - -/** - * Shared options for default resolution and resolved observer state. - * @internal - */ -export interface QueryObserverOptionsBase< - TRuntime extends RuntimeBinding, - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> extends WithRequired< - QueryOptions< - TRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey, - TPageParam - >, - 'queryKey' -> { - /** - * Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. - * To refetch the query, use the `refetch` method returned from the `useQuery` instance. - * Accepts a boolean or function that returns a boolean. - * @defaultValue true - */ - enabled?: QueryBooleanOption< - TRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey - > - /** - * The time in milliseconds after data is considered stale. - * If set to `Infinity`, the data will never be considered stale. - * If set to `'static'`, the data will never be considered stale. - * If set to a function, the function will be executed with the query to compute a `staleTime`. - * @defaultValue 0 - */ - staleTime?: StaleTimeFunction< - TRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey - > - /** - * If set to a number, the query will continuously refetch at this frequency in milliseconds. - * If set to a function, the function will be executed with the latest data and query to compute a frequency - * @defaultValue false - */ - refetchInterval?: RefetchIntervalOf< - TRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey - > - /** - * If set to `true`, the query will continue to refetch while their tab/window is in the background. - * @defaultValue false - */ - refetchIntervalInBackground?: boolean - /** - * If set to `true`, the query will refetch on window focus if the data is stale. - * If set to `false`, the query will not refetch on window focus. - * If set to `'always'`, the query will always refetch on window focus (except when `staleTime: 'static'` is used). - * If set to a function, the function will be executed with the latest data and query to compute the value. - * @defaultValue true - */ - refetchOnWindowFocus?: - | boolean - | 'always' - | (( - query: QueryOf, - ) => boolean | 'always') - /** - * If set to `true`, the query will refetch on reconnect if the data is stale. - * If set to `false`, the query will not refetch on reconnect. - * If set to `'always'`, the query will always refetch on reconnect (except when `staleTime: 'static'` is used). - * If set to a function, the function will be executed with the latest data and query to compute the value. - * - * Defaults to `true` unless `networkMode` is `'always'`. - */ - refetchOnReconnect?: - | boolean - | 'always' - | (( - query: QueryOf, - ) => boolean | 'always') - /** - * If set to `true`, the query will refetch on mount if the data is stale. - * If set to `false`, will disable additional instances of a query to trigger background refetch. - * If set to `'always'`, the query will always refetch on mount (except when `staleTime: 'static'` is used). - * If set to a function, the function will be executed with the latest data and query to compute the value - * @defaultValue true - */ - refetchOnMount?: - | boolean - | 'always' - | (( - query: QueryOf, - ) => boolean | 'always') - /** - * If set to `false`, the query will not be retried on mount if it contains an error. - * If set to a function, the function will be executed with the query to compute the value. - * @defaultValue true - */ - retryOnMount?: QueryBooleanOption< - TRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey - > - /** - * Controls when changes to the query result notify this observer's listeners. - * Use `'all'` to notify on every result change. - * Use `'none'` to suppress notifications while the query remains subscribed and can fetch. - * If `throwOnError` is set, changes to `error` still notify listeners. - * - * By default, adapters that track property reads notify listeners when a tracked property changes. - * If no properties are tracked, every result change notifies listeners. - */ - notifyOnChangeProps?: NotifyOnChangeProps - /** - * Whether errors should be thrown instead of setting the `error` property. - * If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. - * If set to `false` and `suspense` is `false`, errors are returned as state. - * If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`). - * @defaultValue false - */ - throwOnError?: ThrowOnError< - TRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey - > - /** - * This option can be used to transform or select a part of the data returned by the query function. It affects - * the returned `data` value, but does not affect what gets stored in the query cache. - * The `select` function will only run if `data` changed, or if the reference to the `select` function itself - * changes. To optimize, memoize the function so its reference stays stable across calls. - * If the selector throws, the observer reports the error and can keep the last valid selection. - */ - select?: ProjectionOption< - TRuntime, - 'selectFeature', - (data: TQueryData) => TData - > - /** - * If set to `true`, the query will suspend when `status === 'pending'` - * and throw errors when `status === 'error'`. - * @defaultValue false - */ - suspense?: boolean - /** - * If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. - * If the placeholder function throws, the observer reports the error with no data. The query state in the cache is unaffected. - */ - placeholderData?: ProjectionOption< - TRuntime, - 'placeholderFeature', - PlaceholderValue - > - - /** @internal */ - _optimisticResults?: 'optimistic' | 'isRestoring' -} - -/** - * The options of a `QueryObserver`, and of the hooks built on it like `useQuery`: the - * {@link QueryOptions} of the query, plus options that control the observer, such as `enabled`, - * `staleTime`, `refetchInterval`, `select`, and `placeholderData`. - * Pass a `queryFn` or use `defaultQueryFn` to select the client defaults. - */ -export interface QueryObserverOptions< - TRuntime extends RuntimeBinding, - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> extends WithRequired< - QueryObserverOptionsBase< - TRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - >, - 'queryFn' -> {} - -/** - * Makes the `TKey` properties of `TTarget` required and non-nullable. - */ -export type WithRequired = TTarget & { - [_ in TKey]: {} -} - -/** - * The {@link QueryObserverOptions} after `QueryClient#defaultQueryOptions` has applied the - * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. - */ -export type DefaultedQueryObserverOptions< - TRuntime extends RuntimeBinding, - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = WithRequired< - QueryObserverOptionsBase< - TRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - >, - 'throwOnError' | 'refetchOnReconnect' | 'queryHash' -> - -/** - * The options of an `InfiniteQueryObserver`: {@link QueryObserverOptions} whose query data is - * {@link InfiniteData}, plus the page param options. - */ -export interface InfiniteQueryObserverOptions< - TRuntime extends RuntimeBinding, - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> - extends - QueryObserverOptions< - TRuntime, - TQueryFnData, - TError, - TData, - InfiniteData, - TQueryKey, - TPageParam - >, - InfiniteQueryPageParamsOptions {} - -/** - * The {@link InfiniteQueryObserverOptions} after `QueryClient#defaultQueryOptions` has applied the - * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. - */ -export type DefaultedInfiniteQueryObserverOptions< - TRuntime extends RuntimeBinding, - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> = DefaultedQueryObserverOptions< - TRuntime, - TQueryFnData, - TError, - TData, - InfiniteData, - TQueryKey, - TPageParam -> & - InfiniteQueryPageParamsOptions - -/** - * The options of `queryClient.query`: the {@link QueryOptions} of the query, plus a `staleTime` - * that decides whether cached data is returned instead of fetching, and a `select` that only - * transforms the value the call resolves with. - */ -export interface QueryExecuteOptions< - TRuntime extends RuntimeBinding, - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> extends WithRequired< - QueryOptions< - TRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey, - TPageParam - >, - 'queryKey' -> { - /** - * Not allowed here, since `initialPageParam` only applies to infinite queries. - */ - initialPageParam?: never - /** - * This option can be used to transform or select a part of the data returned by the query function. It affects - * the value this call resolves with, but does not affect what gets stored in the query cache. - */ - select?: ProjectionOption< - TRuntime, - 'selectFeature', - (data: TQueryData) => TData - > - /** - * The time in milliseconds after data is considered stale. - * If the data is fresh it will be returned from the cache. - */ - staleTime?: StaleTimeFunction< - TRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey - > -} - -type InfiniteQueryFetchPageOptions = Pick< - InfiniteQueryPageParamsOptions, - 'initialPageParam' | 'getNextPageParam' -> & { - /** - * The number of pages to fetch. Defaults to the number of cached pages, - * or one page if the cache has no pages. - */ - pages?: number -} - -/** - * The options of `queryClient.infiniteQuery`. Extends {@link QueryExecuteOptions} - * with `initialPageParam`, `getNextPageParam`, and the optional `pages` count. - */ -export type InfiniteQueryExecuteOptions< - TRuntime extends RuntimeBinding, - TQueryFnData = unknown, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> = Omit< - QueryExecuteOptions< - TRuntime, - TQueryFnData, - TError, - TData, - InfiniteData, - TQueryKey, - TPageParam - >, - 'initialPageParam' -> & - InfiniteQueryFetchPageOptions - -/** - * Options shared by the `QueryClient` and observer methods that refetch queries, controlling - * whether a failed refetch makes the returned promise reject. - */ -export interface ResultOptions { - /** - * If set to `true`, the method throws if any of the underlying query refetch tasks fail. - * If set to `false`, failed refetches are swallowed and not surfaced to the caller. - * @defaultValue false - */ - throwOnError?: boolean -} - -/** - * Options of the methods that refetch queries, like `refetch` and `queryClient.refetchQueries`. - */ -export interface RefetchOptions extends ResultOptions { - /** - * If set to `true`, a currently running request will be cancelled before a new request is made - * - * If set to `false`, no refetch will be made if there is already a request running. - * @defaultValue true - */ - cancelRefetch?: boolean -} - -/** - * The filters of `queryClient.invalidateQueries`: the {@link QueryFilters} that select the queries - * to invalidate, plus `refetchType` to choose which of them are refetched. - */ -export interface InvalidateQueryFilters< - TRuntime extends RuntimeBinding, - TQueryKey extends QueryKey = QueryKey, -> extends QueryFilters { - /** - * Controls which of the matched (now-invalidated) queries are refetched in the background. - * - * - `'active'`: only queries with at least one active observer are refetched. - * - `'inactive'`: only queries with no active observer are refetched. - * - `'all'`: every matched query is refetched, active or not. - * - `'none'`: no query is refetched; matched queries are only marked as invalidated. - * @defaultValue 'active' - */ - refetchType?: QueryTypeFilter | 'none' -} - -/** - * The filters of `queryClient.refetchQueries`, which select the queries to refetch. - */ -export interface RefetchQueryFilters< - TRuntime extends RuntimeBinding, - TQueryKey extends QueryKey = QueryKey, -> extends QueryFilters {} - -/** - * Options of `queryClient.invalidateQueries`, applied to the refetch that follows the invalidation. - */ -export interface InvalidateOptions extends RefetchOptions {} - -/** - * Options of `queryClient.resetQueries`, applied to the refetch of the active queries after the - * reset. - */ -export interface ResetOptions extends RefetchOptions {} - -/** - * Options of `fetchNextPage` on an infinite query result. - */ -export interface FetchNextPageOptions extends ResultOptions { - /** - * If set to `true`, calling `fetchNextPage` repeatedly will invoke `queryFn` every time, - * whether the previous invocation has resolved or not. Also, the result from previous invocations will be ignored. - * - * If set to `false`, calling `fetchNextPage` repeatedly won't have any effect until the first invocation has resolved. - * @defaultValue true - */ - cancelRefetch?: boolean -} - -/** - * Options of `fetchPreviousPage` on an infinite query result. - */ -export interface FetchPreviousPageOptions extends ResultOptions { - /** - * If set to `true`, calling `fetchPreviousPage` repeatedly will invoke `queryFn` every time, - * whether the previous invocation has resolved or not. Also, the result from previous invocations will be ignored. - * - * If set to `false`, calling `fetchPreviousPage` repeatedly won't have any effect until the first invocation has resolved. - * @defaultValue true - */ - cancelRefetch?: boolean -} - -/** @inline */ -export type QueryStatus = 'pending' | 'error' | 'success' - -/** @inline */ -export type FetchStatus = 'fetching' | 'paused' | 'idle' - -/** - * The properties shared by every state of a query result, like `data`, `error`, `status`, the - * `is*` flags, and `refetch`. Each `QueryObserver*Result` narrows them for one state. - */ -export interface QueryObserverBaseResult< - TData = unknown, - TError = DefaultError, -> { - /** - * The last successfully resolved data for the query. - */ - data: TData | undefined - /** - * The timestamp for when the query most recently returned the `status` as `"success"`. - */ - dataUpdatedAt: number - /** - * The error object for the query, if an error was thrown. - * - Defaults to `null`. - */ - error: TError | null - /** - * The timestamp for when the query most recently returned the `status` as `"error"`. - */ - errorUpdatedAt: number - /** - * The failure count for the query. - * - Incremented every time the query fails. - * - Reset to `0` when the query succeeds. - */ - failureCount: number - /** - * The failure reason for the query retry. - * - Reset to `null` when the query succeeds. - */ - failureReason: TError | null - /** - * The sum of all errors. - */ - errorUpdateCount: number - /** - * A derived boolean from the `status` variable, provided for convenience. - * - `true` if the query has an error from a fetch that failed after its retries, or if `select` threw. - */ - isError: boolean - /** - * Will be `true` if the query has been fetched. - */ - isFetched: boolean - /** - * Will be `true` if the query has been fetched after the component mounted. - * - This property can be used to not show any previously cached data. - */ - isFetchedAfterMount: boolean - /** - * A derived boolean from the `fetchStatus` variable, provided for convenience. - * - `true` whenever the `queryFn` is executing, which includes initial `pending` as well as background refetch. - */ - isFetching: boolean - /** - * Is `true` whenever the first fetch for a query is in-flight. - * - Is the same as `isFetching && isPending`. - */ - isLoading: boolean - /** - * Will be `true` if the query has no cached data, no data from `placeholderData` and no error. - */ - isPending: boolean - /** - * Will be `true` if the query has an error and no data to display. - */ - isLoadingError: boolean - /** - * A derived boolean from the `fetchStatus` variable, provided for convenience. - * - The query wanted to fetch, but has been `paused`. - */ - isPaused: boolean - /** - * Will be `true` if the data shown is the placeholder data. - */ - isPlaceholderData: boolean - /** - * Will be `true` if the query has an error and still has data to display (for infinite queries, not after a failed page fetch). - */ - isRefetchError: boolean - /** - * Is `true` whenever a background refetch is in-flight, which _does not_ include initial `pending`. - * - Is the same as `isFetching && !isPending`. - */ - isRefetching: boolean - /** - * Will be `true` if the data in the cache is invalidated or if the data is older than the given `staleTime`. - */ - isStale: boolean - /** - * A derived boolean from the `status` variable, provided for convenience. - * - `true` if the query has cached data or data from `placeholderData`, and no error. - */ - isSuccess: boolean - /** - * `true` if this observer is enabled, `false` otherwise. - */ - isEnabled: boolean - /** - * A function to manually refetch the query. - */ - refetch: ( - options?: RefetchOptions, - ) => Promise> - /** - * The status of the query. - * - Will be: - * - `error` if the query has an error from a fetch that failed after its retries, or if `select` threw. - * - `success` if the query has cached data (even if `select` returns `undefined`) or data from `placeholderData`, and no error. - * - `pending` otherwise, since the query has no cached data, no data from `placeholderData` and no error. - */ - status: QueryStatus - /** - * The fetch status of the query. - * - `fetching`: Is `true` whenever the queryFn is executing, which includes initial `pending` as well as background refetch. - * - `paused`: The query wanted to fetch, but has been `paused`. - * - `idle`: The query is not fetching. - * - See [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. - */ - fetchStatus: FetchStatus -} - -/** - * A query result in the `pending` state: the query has no data yet. - */ -export interface QueryObserverPendingResult< - TData = unknown, - TError = DefaultError, -> extends QueryObserverBaseResult { - /** - * `undefined`, since the query has no data yet. - */ - data: undefined - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `true`, since the query has no cached data, no data from `placeholderData` and no error. - */ - isPending: true - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. - */ - status: 'pending' -} - -/** - * A query result in the `pending` state while the first fetch is in flight, so `isLoading` is - * `true`. - */ -export interface QueryObserverLoadingResult< - TData = unknown, - TError = DefaultError, -> extends QueryObserverBaseResult { - /** - * `undefined`, since the query has no data yet. - */ - data: undefined - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `true`, since the query has no cached data, no data from `placeholderData` and no error. - */ - isPending: true - /** - * `true`, since the first fetch is in flight. - */ - isLoading: true - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. - */ - status: 'pending' -} - -/** - * A query result in the `error` state with no data to display, since a fetch or `select` failed. - */ -export interface QueryObserverLoadingErrorResult< - TData = unknown, - TError = DefaultError, -> extends QueryObserverBaseResult { - /** - * `undefined`, since there was no data to display when a fetch or `select` failed. - */ - data: undefined - /** - * The error the fetch or `select` failed with. - */ - error: TError - /** - * `true`, since the query is in the `error` state. - */ - isError: true - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `true`, since the query has an error and no data to display. - */ - isLoadingError: true - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'error'`, since a fetch failed after its retries or `select` threw. - */ - status: 'error' -} - -/** - * A query result in the `error` state that keeps the data from before a fetch or `select` failed. - */ -export interface QueryObserverRefetchErrorResult< - TData = unknown, - TError = DefaultError, -> extends QueryObserverBaseResult { - /** - * The data from before the fetch or `select` failed, which is kept. - */ - data: TData - /** - * The error the fetch or `select` failed with. - */ - error: TError - /** - * `true`, since the query is in the `error` state. - */ - isError: true - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `true`, since the query has an error and still has data to display. - */ - isRefetchError: true - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'error'`, since a fetch failed after its retries or `select` threw. - */ - status: 'error' -} - -/** - * A query result in the `success` state with data from the cache. - */ -export interface QueryObserverSuccessResult< - TData = unknown, - TError = DefaultError, -> extends QueryObserverBaseResult { - /** - * The last successfully resolved data for the query. - */ - data: TData - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `true`, since the query is in the `success` state. - */ - isSuccess: true - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'success'`, since the query has cached data and no error from a fetch or from - * `select`. - */ - status: 'success' -} - -/** - * A query result in the `success` state that shows `placeholderData` while the query has no data - * yet. - */ -export interface QueryObserverPlaceholderResult< - TData = unknown, - TError = DefaultError, -> extends QueryObserverBaseResult { - /** - * The `placeholderData` shown while the query has no data yet. - */ - data: TData - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `true`, since the query is in the `success` state. - */ - isSuccess: true - /** - * `true`, since the data shown is the `placeholderData`. - */ - isPlaceholderData: true - /** - * `'success'`, since the query shows `placeholderData` and has no error from a fetch or - * from `select`. - */ - status: 'success' -} - -/** - * A query result that always has `data`: the success and refetch error states. - */ -export type DefinedQueryObserverResult< - TData = unknown, - TError = DefaultError, -> = - | QueryObserverRefetchErrorResult - | QueryObserverSuccessResult - -/** - * The result of a `QueryObserver`, and of the hooks built on it like `useQuery`. Narrow it by - * `status` or the `is*` flags to get the type of each state. - */ -export type QueryObserverResult = - | DefinedQueryObserverResult - | QueryObserverLoadingErrorResult - | QueryObserverLoadingResult - | QueryObserverPendingResult - | QueryObserverPlaceholderResult - -/** - * The properties shared by every state of an infinite query result: those of - * {@link QueryObserverBaseResult}, plus `fetchNextPage`, `fetchPreviousPage`, and the flags about - * them, like `hasNextPage` and `isFetchingNextPage`. - */ -export interface InfiniteQueryObserverBaseResult< - TData = unknown, - TError = DefaultError, -> extends QueryObserverBaseResult { - /** - * This function allows you to fetch the next "page" of results. - */ - fetchNextPage: ( - options?: FetchNextPageOptions, - ) => Promise> - /** - * This function allows you to fetch the previous "page" of results. - */ - fetchPreviousPage: ( - options?: FetchPreviousPageOptions, - ) => Promise> - /** - * Will be `true` if there is a next page to be fetched (known via the `getNextPageParam` option). - */ - hasNextPage: boolean - /** - * Will be `true` if there is a previous page to be fetched (known via the `getPreviousPageParam` option). - */ - hasPreviousPage: boolean - /** - * Will be `true` if the query failed while fetching the next page. - */ - isFetchNextPageError: boolean - /** - * Will be `true` while fetching the next page with `fetchNextPage`. - */ - isFetchingNextPage: boolean - /** - * Will be `true` if the query failed while fetching the previous page. - */ - isFetchPreviousPageError: boolean - /** - * Will be `true` while fetching the previous page with `fetchPreviousPage`. - */ - isFetchingPreviousPage: boolean -} - -/** - * An infinite query result in the `pending` state: the query has no data yet. - */ -export interface InfiniteQueryObserverPendingResult< - TData = unknown, - TError = DefaultError, -> extends InfiniteQueryObserverBaseResult { - /** - * `undefined`, since the query has no data yet. - */ - data: undefined - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `true`, since the query has no cached data, no data from `placeholderData` and no error. - */ - isPending: true - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `false`, since fetching the next page didn't fail. - */ - isFetchNextPageError: false - /** - * `false`, since fetching the previous page didn't fail. - */ - isFetchPreviousPageError: false - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. - */ - status: 'pending' -} - -/** - * An infinite query result in the `pending` state while the first fetch is in flight, so - * `isLoading` is `true`. - */ -export interface InfiniteQueryObserverLoadingResult< - TData = unknown, - TError = DefaultError, -> extends InfiniteQueryObserverBaseResult { - /** - * `undefined`, since the query has no data yet. - */ - data: undefined - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `true`, since the query has no cached data, no data from `placeholderData` and no error. - */ - isPending: true - /** - * `true`, since the first fetch is in flight. - */ - isLoading: true - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `false`, since fetching the next page didn't fail. - */ - isFetchNextPageError: false - /** - * `false`, since fetching the previous page didn't fail. - */ - isFetchPreviousPageError: false - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'pending'`, since the query has no cached data, no data from `placeholderData` and no error. - */ - status: 'pending' -} - -/** - * An infinite query result in the `error` state with no data to display, since a fetch or `select` failed. - */ -export interface InfiniteQueryObserverLoadingErrorResult< - TData = unknown, - TError = DefaultError, -> extends InfiniteQueryObserverBaseResult { - /** - * `undefined`, since there was no data to display when a fetch or `select` failed. - */ - data: undefined - /** - * The error the fetch or `select` failed with. - */ - error: TError - /** - * `true`, since the query is in the `error` state. - */ - isError: true - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `true`, since the query has an error and no data to display. - */ - isLoadingError: true - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `false`, since fetching the next page didn't fail. - */ - isFetchNextPageError: false - /** - * `false`, since fetching the previous page didn't fail. - */ - isFetchPreviousPageError: false - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'error'`, since a fetch failed after its retries or `select` threw. - */ - status: 'error' -} - -/** - * An infinite query result in the `error` state that keeps the data from before a fetch or `select` - * failed. - */ -export interface InfiniteQueryObserverRefetchErrorResult< - TData = unknown, - TError = DefaultError, -> extends InfiniteQueryObserverBaseResult { - /** - * The data from before the fetch or `select` failed, which is kept. - */ - data: TData - /** - * The error the fetch or `select` failed with. - */ - error: TError - /** - * `true`, since the query is in the `error` state. - */ - isError: true - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `true`, since the query has an error, still has data to display, and didn't fail fetching a page. - */ - isRefetchError: true - /** - * `false`, since the query isn't in the `success` state. - */ - isSuccess: false - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'error'`, since a fetch failed after its retries or `select` threw. - */ - status: 'error' -} - -/** - * An infinite query result in the `success` state with data from the cache. - */ -export interface InfiniteQueryObserverSuccessResult< - TData = unknown, - TError = DefaultError, -> extends InfiniteQueryObserverBaseResult { - /** - * The last successfully resolved data for the query. - */ - data: TData - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `false`, since fetching the next page didn't fail. - */ - isFetchNextPageError: false - /** - * `false`, since fetching the previous page didn't fail. - */ - isFetchPreviousPageError: false - /** - * `true`, since the query is in the `success` state. - */ - isSuccess: true - /** - * `false`, since the data shown isn't the `placeholderData`. - */ - isPlaceholderData: false - /** - * `'success'`, since the query has cached data and no error from a fetch or from - * `select`. - */ - status: 'success' -} - -/** - * An infinite query result in the `success` state that shows `placeholderData` while the query has - * no data yet. - */ -export interface InfiniteQueryObserverPlaceholderResult< - TData = unknown, - TError = DefaultError, -> extends InfiniteQueryObserverBaseResult { - /** - * The `placeholderData` shown while the query has no data yet. - */ - data: TData - /** - * `false`, since the query isn't in the `error` state. - */ - isError: false - /** - * `null`, since the query isn't in the `error` state. - */ - error: null - /** - * `false`, since the query has cached data, data from `placeholderData` or an error. - */ - isPending: false - /** - * `false`, since the first fetch isn't in flight. - */ - isLoading: false - /** - * `false`, since the query didn't fail while fetching for the first time. - */ - isLoadingError: false - /** - * `false`, since the query didn't fail while refetching. - */ - isRefetchError: false - /** - * `true`, since the query is in the `success` state. - */ - isSuccess: true - /** - * `true`, since the data shown is the `placeholderData`. - */ - isPlaceholderData: true - /** - * `false`, since fetching the next page didn't fail. - */ - isFetchNextPageError: false - /** - * `false`, since fetching the previous page didn't fail. - */ - isFetchPreviousPageError: false - /** - * `'success'`, since the query shows `placeholderData` and has no error from a fetch or - * from `select`. - */ - status: 'success' -} - -/** - * An infinite query result that always has `data`: the success and refetch error states. - */ -export type DefinedInfiniteQueryObserverResult< - TData = unknown, - TError = DefaultError, -> = - | InfiniteQueryObserverRefetchErrorResult - | InfiniteQueryObserverSuccessResult - -/** - * The result of an `InfiniteQueryObserver`, and of the hooks built on it like `useInfiniteQuery`. - * Narrow it by `status` or the `is*` flags to get the type of each state. - */ -export type InfiniteQueryObserverResult< - TData = unknown, - TError = DefaultError, -> = - | DefinedInfiniteQueryObserverResult - | InfiniteQueryObserverLoadingErrorResult - | InfiniteQueryObserverLoadingResult - | InfiniteQueryObserverPendingResult - | InfiniteQueryObserverPlaceholderResult - -/** - * The type of a mutation key — the serializable array used to identify and filter mutations. - * Defaults to `ReadonlyArray`; declare `mutationKey` on {@link Register} to narrow it repository-wide. - */ -export type MutationKey = Register extends { - mutationKey: infer TMutationKey -} - ? TMutationKey extends ReadonlyArray - ? TMutationKey - : TMutationKey extends Array - ? TMutationKey - : ReadonlyArray - : ReadonlyArray - -/** @inline */ -export type MutationStatus = 'idle' | 'pending' | 'success' | 'error' - -/** - * Groups mutations so they run one after another instead of in parallel. - * Mutations that share the same `id` form a queue: while one is running, the others wait in `isPaused: true` - * state and resume automatically when their turn comes. Mutations with no scope always run in parallel. - */ -export type MutationScope = { - /** - * The scope's identifier. Mutations with the same `id` run one after another. - */ - id: string -} - -/** - * The type of the `meta` object that can be attached to a mutation and read back from `mutationFn`, callbacks and - * cache-level handlers. Defaults to `Record`; declare `mutationMeta` on {@link Register} to narrow it. - */ -export type MutationMeta = Register extends { - mutationMeta: infer TMutationMeta -} - ? TMutationMeta extends Record - ? TMutationMeta - : Record - : Record - -/** - * The object passed to `mutationFn` and the mutation callbacks: the `QueryClient`, the mutation's - * `meta`, and its `mutationKey`. - */ -export type MutationFunctionContext = { - /** - * The `QueryClient` the mutation runs in. - */ - client: QueryClientOf - /** - * The `meta` of the mutation options. - */ - meta: MutationMeta | undefined - /** - * The `mutationKey` of the mutation options, if set. - */ - mutationKey?: MutationKey -} - -/** @inline */ -export type MutationFunction< - TRuntime extends RuntimeBinding, - TData = unknown, - TVariables = unknown, -> = ( - variables: TVariables, - context: MutationFunctionContext, -) => Promise - -/** - * The options of a mutation: its `mutationFn`, `mutationKey`, callbacks, retries, `scope`, and so - * on. - */ -export interface MutationOptions< - TRuntime extends RuntimeBinding, - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> { - /** - * The function that performs the asynchronous task this mutation runs. - * Required, unless a default mutation function has been set for the matching `mutationKey` via - * `queryClient.setMutationDefaults`. - * Receives the `variables` passed to `mutate`, and a {@link MutationFunctionContext} holding the - * `QueryClient`, the `mutationKey` and `meta`. - * Must return a promise that resolves the mutation's data. - */ - mutationFn?: MutationFunction - /** - * The key to use for this mutation. Optional, but required to inherit defaults registered with - * `queryClient.setMutationDefaults`, and to match this mutation with `useMutationState` or - * `queryClient.isMutating`. - */ - mutationKey?: MutationKey - /** - * This function fires before the mutation function runs, and receives the same variables. - * Useful for optimistic updates applied in the hope that the mutation succeeds. - * The value it returns is passed to `onSuccess`, `onError` and `onSettled` as `onMutateResult`, - * which is where an optimistic update is usually rolled back. - * If a promise is returned, it is awaited before the mutation function runs. - */ - onMutate?: ( - variables: TVariables, - context: MutationFunctionContext, - ) => Promise | TOnMutateResult - /** - * This function fires when the mutation succeeds, and is passed the mutation's result. - * If a promise is returned, it is awaited before `onSettled` runs. - */ - onSuccess?: ( - data: TData, - variables: TVariables, - onMutateResult: TOnMutateResult, - context: MutationFunctionContext, - ) => Promise | unknown - /** - * This function fires when the mutation encounters an error, and is passed the error. - * If a promise is returned, it is awaited before `onSettled` runs. - */ - onError?: ( - error: TError, - variables: TVariables, - onMutateResult: TOnMutateResult | undefined, - context: MutationFunctionContext, - ) => Promise | unknown - /** - * This function fires when the mutation either succeeds or errors, and is passed either the data - * or the error. - * If a promise is returned, it is awaited before the mutation settles. - */ - onSettled?: ( - data: TData | undefined, - error: TError | null, - variables: TVariables, - onMutateResult: TOnMutateResult | undefined, - context: MutationFunctionContext, - ) => Promise | unknown - /** - * If `false`, failed mutations will not retry by default. - * If `true`, failed mutations will retry infinitely. - * If set to an integer number, e.g. 3, failed mutations will retry until the failed mutation count meets that number. - * If set to a function `(failureCount, error) => boolean` failed mutations will retry until the function returns false. - * @defaultValue 0 - */ - retry?: RetryValue - /** - * The delay in milliseconds before a retry. Use a number for a fixed delay or a function that receives - * the failure count and error and returns the delay. The count starts at 0 for the first retry. - * - * By default, each retry waits a random duration from 80% to 100% of the base delay. - * The base delay starts at 1 second and doubles for each retry, up to 30 seconds. - */ - retryDelay?: RetryDelayValue - /** - * Controls whether a mutation is allowed to run based on the current network connectivity. - * @defaultValue 'online' - * @see [Network Mode](https://tanstack.com/query/latest/docs/framework/react/guides/network-mode) for more information. - */ - networkMode?: NetworkMode - /** - * The time in milliseconds that an unused/inactive mutation remains in memory before it is - * garbage collected. - * - * Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. - */ - gcTime?: number - /** @internal */ - _defaulted?: boolean - /** - * Additional payload to be stored on the mutation cache entry. - * Use it to pass information that can be read wherever the `mutation` is available, such as the - * `onError` and `onSuccess` callbacks of the `MutationCache`. - */ - meta?: MutationMeta - /** - * Controls whether this mutation runs alongside others or waits its turn. - * Mutations sharing the same `scope.id` run serially, in the order they were started. - * Without a scope, a mutation runs as soon as it is triggered. - */ - scope?: TRuntime extends { mutationScope: infer TScope } - ? TScope - : MutationScope -} - -/** - * The options of a `MutationObserver`, and of the hooks built on it like `useMutation`: the - * {@link MutationOptions}, plus `throwOnError`. - */ -export interface MutationObserverOptions< - TRuntime extends RuntimeBinding, - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> extends MutationOptions< - TRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> { - /** - * Whether errors should be thrown instead of setting the `error` property. - * If set to `true`, all errors will be thrown to the nearest error boundary. - * If set to a function, it will be passed the error and should return a boolean indicating whether to throw the - * error (`true`) or return it as state (`false`). - * @defaultValue false - */ - throwOnError?: boolean | ((error: TError) => boolean) -} - -/** - * The callbacks that can be passed to `mutate` for a single call. They run after the callbacks of - * the mutation options. - */ -export interface MutateOptions< - TRuntime extends RuntimeBinding, - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> { - /** - * Called when the mutation of this call succeeds, after the `onSuccess` of the mutation options. - */ - onSuccess?: ( - data: TData, - variables: TVariables, - onMutateResult: TOnMutateResult | undefined, - context: MutationFunctionContext, - ) => void - /** - * Called when the mutation of this call fails, after the `onError` of the mutation options. - */ - onError?: ( - error: TError, - variables: TVariables, - onMutateResult: TOnMutateResult | undefined, - context: MutationFunctionContext, - ) => void - /** - * Called when the mutation of this call succeeds or fails, after the `onSettled` of the mutation - * options. - */ - onSettled?: ( - data: TData | undefined, - error: TError | null, - variables: TVariables, - onMutateResult: TOnMutateResult | undefined, - context: MutationFunctionContext, - ) => void -} - -/** - * The parameters of {@link MutateFunction}: `variables`, optional when `TVariables` accepts - * `undefined`, and the {@link MutateOptions} for that call. - */ -export type MutateFunctionRest< - TRuntime extends RuntimeBinding, - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = undefined extends TVariables - ? [ - variables?: TVariables, - options?: MutateOptions< - TRuntime, - TData, - TError, - TVariables, - TOnMutateResult - >, - ] - : [ - variables: TVariables, - options?: MutateOptions< - TRuntime, - TData, - TError, - TVariables, - TOnMutateResult - >, - ] - -/** - * The `mutate` function of a `MutationObserver`: runs the mutation with the given variables and - * resolves with its data. - */ -export type MutateFunction< - TRuntime extends RuntimeBinding, - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = ( - ...rest: MutateFunctionRest< - TRuntime, - TData, - TError, - TVariables, - TOnMutateResult - > -) => Promise - -/** - * The properties shared by every state of a mutation result, like `data`, `error`, `variables`, - * `status`, the `is*` flags, `mutate`, and `reset`. - */ -export interface MutationObserverBaseResult< - TRuntime extends RuntimeBinding, - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> extends MutationState { - /** - * The last successfully resolved data for the mutation. - */ - data: TData | undefined - /** - * The variables object passed to the `mutationFn`. - */ - variables: TVariables | undefined - /** - * The error object for the mutation, if an error was encountered. - * - Defaults to `null`. - */ - error: TError | null - /** - * A boolean variable derived from `status`. - * - `true` if the last mutation attempt resulted in an error. - */ - isError: boolean - /** - * A boolean variable derived from `status`. - * - `true` if the mutation is in its initial state prior to executing. - */ - isIdle: boolean - /** - * A boolean variable derived from `status`. - * - `true` if the mutation is currently executing. - */ - isPending: boolean - /** - * A boolean variable derived from `status`. - * - `true` if the last mutation attempt was successful. - */ - isSuccess: boolean - /** - * The status of the mutation. - * - Will be: - * - `idle` initial status prior to the mutation function executing. - * - `pending` if the mutation is currently executing. - * - `error` if the last mutation attempt resulted in an error. - * - `success` if the last mutation attempt was successful. - */ - status: MutationStatus - /** - * The mutation function you can call with variables to trigger the mutation and optionally hooks on additional callback options. - * @param variables - The variables object to pass to the `mutationFn`. - * @param options.onSuccess - This function will fire when the mutation is successful and will be passed the mutation's result. - * @param options.onError - This function will fire if the mutation encounters an error and will be passed the error. - * @param options.onSettled - This function will fire when the mutation is either successfully fetched or encounters an error and be passed either the data or error. - * @remarks - * - If you make multiple requests, `onSuccess` will fire only after the latest call you've made. - * - All the callback functions (`onSuccess`, `onError`, `onSettled`) are void functions, and the returned value will be ignored. - */ - mutate: MutateFunction - /** - * A function to clean the mutation internal state (i.e., it resets the mutation to its initial state). - */ - reset: () => void -} - -/** - * A mutation result in the `idle` state: the mutation hasn't run yet, or was reset. - */ -export interface MutationObserverIdleResult< - TRuntime extends RuntimeBinding, - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> extends MutationObserverBaseResult< - TRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> { - /** - * `undefined`, since the mutation hasn't run. - */ - data: undefined - /** - * `undefined`, since the mutation hasn't run. - */ - variables: undefined - /** - * `null`, since the mutation hasn't failed. - */ - error: null - /** - * `false`, since the mutation hasn't failed. - */ - isError: false - /** - * `true`, since the mutation hasn't run yet or was reset. - */ - isIdle: true - /** - * `false`, since the mutation isn't running. - */ - isPending: false - /** - * `false`, since the mutation hasn't succeeded. - */ - isSuccess: false - /** - * `'idle'`, since the mutation hasn't run yet or was reset. - */ - status: 'idle' -} - -/** - * A mutation result in the `pending` state while the mutation runs. - */ -export interface MutationObserverLoadingResult< - TRuntime extends RuntimeBinding, - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> extends MutationObserverBaseResult< - TRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> { - /** - * `undefined`, since the mutation hasn't succeeded. - */ - data: undefined - /** - * The variables passed to `mutate` for this mutation. - */ - variables: TVariables - /** - * `null`, since the mutation hasn't failed. - */ - error: null - /** - * `false`, since the mutation hasn't failed. - */ - isError: false - /** - * `false`, since the mutation has run. - */ - isIdle: false - /** - * `true`, since the mutation is running. - */ - isPending: true - /** - * `false`, since the mutation hasn't succeeded. - */ - isSuccess: false - /** - * `'pending'`, since the mutation is running. - */ - status: 'pending' -} - -/** - * A mutation result in the `error` state after the mutation failed. - */ -export interface MutationObserverErrorResult< - TRuntime extends RuntimeBinding, - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> extends MutationObserverBaseResult< - TRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> { - /** - * `undefined`, since the mutation hasn't succeeded. - */ - data: undefined - /** - * The error the mutation failed with. - */ - error: TError - /** - * The variables passed to `mutate` for this mutation. - */ - variables: TVariables - /** - * `true`, since the mutation failed. - */ - isError: true - /** - * `false`, since the mutation has run. - */ - isIdle: false - /** - * `false`, since the mutation isn't running. - */ - isPending: false - /** - * `false`, since the mutation hasn't succeeded. - */ - isSuccess: false - /** - * `'error'`, since the mutation failed. - */ - status: 'error' -} - -/** - * A mutation result in the `success` state after the mutation succeeded. - */ -export interface MutationObserverSuccessResult< - TRuntime extends RuntimeBinding, - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> extends MutationObserverBaseResult< - TRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> { - /** - * The data the mutation resolved with. - */ - data: TData - /** - * `null`, since the mutation hasn't failed. - */ - error: null - /** - * The variables passed to `mutate` for this mutation. - */ - variables: TVariables - /** - * `false`, since the mutation hasn't failed. - */ - isError: false - /** - * `false`, since the mutation has run. - */ - isIdle: false - /** - * `false`, since the mutation isn't running. - */ - isPending: false - /** - * `true`, since the mutation succeeded. - */ - isSuccess: true - /** - * `'success'`, since the mutation succeeded. - */ - status: 'success' -} - -/** - * The result of a `MutationObserver`, and of the hooks built on it like `useMutation`. Narrow it by - * `status` or the `is*` flags to get the type of each state. - */ -export type MutationObserverResult< - TRuntime extends RuntimeBinding, - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = - | MutationObserverIdleResult< - TRuntime, - TData, - TError, - TVariables, - TOnMutateResult - > - | MutationObserverLoadingResult< - TRuntime, - TData, - TError, - TVariables, - TOnMutateResult - > - | MutationObserverErrorResult< - TRuntime, - TData, - TError, - TVariables, - TOnMutateResult - > - | MutationObserverSuccessResult< - TRuntime, - TData, - TError, - TVariables, - TOnMutateResult - > - -/** - * The options of `new QueryClient()`: the `queryCache` and `mutationCache` to use, and the - * `defaultOptions` for its queries and mutations. - */ -export interface QueryClientConfig { - /** The query cache this client is connected to. A new `QueryCache` is created if not provided. */ - queryCache?: QueryCacheOf - /** - * The mutation cache this client is connected to. A new `MutationCache` is created if not - * provided. - */ - mutationCache?: MutationCacheOf - /** Default options for all queries and mutations created through this client. */ - defaultOptions?: DefaultOptions -} - -/** - * The default options of a `QueryClient`, applied to every query (`queries`), mutation - * (`mutations`), `hydrate`, and `dehydrate` call unless overridden. - */ -export interface DefaultOptions< - TRuntime extends RuntimeBinding, - TError = DefaultError, -> { - /** Default options applied to every query, unless overridden per-query. */ - queries?: OmitKeyof< - QueryObserverOptionsBase, - 'suspense' | 'queryKey' - > - /** Default options applied to every mutation, unless overridden per-mutation. */ - mutations?: MutationObserverOptions< - TRuntime, - unknown, - TError, - unknown, - unknown - > - /** Default options used when hydrating queries and mutations; see {@link HydrateOptions}. */ - hydrate?: HydrateOptions['defaultOptions'] - /** Default options used when dehydrating the client's caches; see {@link DehydrateOptions}. */ - dehydrate?: DehydrateOptions -} - -/** - * Options for cancelling an in-flight fetch, e.g. via `query.cancel()`. - * They are carried on the {@link CancelledError} that the cancelled fetch rejects with. - */ -export interface CancelOptions { - /** - * If `true`, the query goes back to the state it had before the fetch started, instead of getting - * the cancellation error. - */ - revert?: boolean - /** - * If `true`, the cancellation error isn't surfaced, e.g. because another fetch replaces the - * cancelled one. - */ - silent?: boolean -} - -/** - * Options for writing data into the cache, e.g. via `queryClient.setQueryData()`. - * `updatedAt` overrides the timestamp the data is recorded with, which is what staleness is measured from; - * omit it to use the current time. - */ -export interface SetDataOptions { - /** - * The timestamp to record the data with, instead of the current time. Staleness is measured from - * it. - */ - updatedAt?: number -} - -/** @inline */ -export type NotifyEventType = - | 'added' - | 'removed' - | 'updated' - | 'observerAdded' - | 'observerRemoved' - | 'observerResultsUpdated' - | 'observerOptionsUpdated' - -/** - * The base shape of the events that the query and mutation caches send to their listeners. - */ -export interface NotifyEvent { - /** - * The kind of event, e.g. `'added'`, `'removed'`, or `'updated'`. - */ - type: NotifyEventType -} - -export type { NonFunctionGuard, InfiniteQueryFetchPageOptions } diff --git a/packages/query-types/src/utils.ts b/packages/query-types/src/utils.ts deleted file mode 100644 index 5cacaf58b86..00000000000 --- a/packages/query-types/src/utils.ts +++ /dev/null @@ -1,120 +0,0 @@ -import type { MutationOf, QueryOf, RuntimeBinding } from './binding' -import type { fetchSignal } from './symbols' -import type { - DefaultError, - FetchStatus, - MutationKey, - MutationStatus, - QueryKey, -} from './types' - -type DropLast> = T extends readonly [ - ...infer R, - unknown, -] - ? readonly [...R] - : never - -type TuplePrefixes> = T extends readonly [] - ? readonly [] - : TuplePrefixes> | T - -/** - * Filters used to select queries, for example in `queryClient.getQueriesData` or `queryClient.invalidateQueries`. - * All provided filters must match; filters that are left unspecified are ignored. - */ -export interface QueryFilters< - TRuntime extends RuntimeBinding, - TQueryKey extends QueryKey = QueryKey, -> { - /** - * Filter to active queries, inactive queries or all queries - * @defaultValue 'all' - */ - type?: QueryTypeFilter - /** - * Match query key exactly - */ - exact?: boolean - /** - * Include queries matching this predicate function - */ - predicate?: (query: QueryOf) => boolean - /** - * Include queries matching this query key - */ - queryKey?: TQueryKey | TuplePrefixes - /** - * Include or exclude stale queries - */ - stale?: boolean - /** - * Include queries matching their fetchStatus - */ - fetchStatus?: FetchStatus -} - -/** - * Filters used to select mutations, for example in `mutationCache.findAll` or `queryClient.isMutating`. - * All provided filters must match; filters that are left unspecified are ignored. - */ -export interface MutationFilters< - TRuntime extends RuntimeBinding, - TData = unknown, - TError = DefaultError, - TVariables = unknown, - TOnMutateResult = unknown, -> { - /** - * Match mutation key exactly - */ - exact?: boolean - /** - * Include mutations matching this predicate function - */ - predicate?: ( - mutation: MutationOf, - ) => boolean - /** - * Include mutations matching this mutation key - */ - mutationKey?: TuplePrefixes - /** - * Filter by mutation status - */ - status?: MutationStatus -} - -/** - * Either a plain value of type `TOutput`, or a function that receives `TInput` and returns `TOutput`. - * Used for example by `setQueryData`-style updaters, which accept either the new data directly or a - * function that computes it from the previous data. See {@link functionalUpdate}. - * @example - * ```ts - * queryClient.setQueryData(['posts'], newPosts) - * - * // Or, using an updater function that receives the current data: - * queryClient.setQueryData(['posts'], (oldPosts) => - * oldPosts ? [...oldPosts, newPost] : oldPosts, - * ) - * ``` - */ -export type Updater = TOutput | ((input: TInput) => TOutput) - -/** - * Which queries a filter matches: all of them, only active ones (with enabled observers), or only - * inactive ones. - */ -export type QueryTypeFilter = 'all' | 'active' | 'inactive' - -export type { skipToken as SkipToken } from './symbols' - -export type { defaultQueryFn as DefaultQueryFn } from './symbols' - -/** Internal view of a context that exposes its signal without consuming it. */ -interface FetchSignalContext { - readonly signal: AbortSignal - readonly [fetchSignal]?: AbortSignal -} - -export type { DropLast, TuplePrefixes, FetchSignalContext } diff --git a/packages/query-types/tsconfig.json b/packages/query-types/tsconfig.json deleted file mode 100644 index 0cc454b2a77..00000000000 --- a/packages/query-types/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "compilerOptions": { - "outDir": "./dist-ts", - "rootDir": "." - }, - "include": ["src", "*.config.ts", "*.config.js", "package.json"] -} diff --git a/packages/query-types/tsconfig.legacy.json b/packages/query-types/tsconfig.legacy.json deleted file mode 100644 index 84ebe1a984b..00000000000 --- a/packages/query-types/tsconfig.legacy.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "outDir": "./dist-ts/legacy" - }, - "include": ["src"], - "exclude": ["src/__tests__"] -} diff --git a/packages/query-types/tsdown.config.ts b/packages/query-types/tsdown.config.ts deleted file mode 100644 index 8f94eb145bc..00000000000 --- a/packages/query-types/tsdown.config.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { defineConfig } from 'tsdown' -import { getTsdownConfig } from './root.tsdown.config.js' - -export default defineConfig( - getTsdownConfig({ entry: ['src/index.ts', 'src/bindings.ts'] }), -) diff --git a/packages/react-query-no-core-pluggable/README.md b/packages/react-query-no-core-pluggable/README.md deleted file mode 100644 index 133cfdd24e2..00000000000 --- a/packages/react-query-no-core-pluggable/README.md +++ /dev/null @@ -1,88 +0,0 @@ -# @tanstack/react-query-no-core-pluggable - -An experimental ESM React Query adapter for React 19. Create a regular `QueryClient` to use queries, infinite queries and mutations. Import optional features where you use them. - -```tsx -import { - QueryClient, - QueryClientProvider, - refetchInterval, - useQuery, -} from '@tanstack/react-query-no-core-pluggable' - -const client = new QueryClient() - -function Orders() { - const { data } = useQuery({ - queryKey: ['orders'], - queryFn: fetchOrders, - refetchInterval: refetchInterval(3000), - }) - return

    {data?.length} orders

    -} - -export function App() { - return ( - - - - ) -} -``` - -`useQuery`, `useInfiniteQuery`, `useSuspenseQuery` and `useSuspenseInfiniteQuery` accept the same helper, as do query defaults. Pass a callback to compute the next interval from the cached query. Return `false` or `undefined` to stop polling. - -```ts -useQuery({ - queryKey: ['job', jobId], - queryFn: () => fetchJob(jobId), - refetchInterval: (query) => - query.state.data?.status === 'complete' ? false : refetchInterval(3000), -}) -``` - -Polling runs while an enabled observer has subscribers and the window is focused. Set `refetchIntervalInBackground: true` to keep polling in the background. Each observer manages its own timer, including when several observers share a client default. - -## Selecting and keeping data - -`select` maps the cached value for one observer. `placeholderData` supplies a temporary value for a pending query. Wrap a typed selector in `select(getTitle)`, or use the tuple form to infer an inline callback's argument from the query. For example, this hook keeps displaying the previous post title while the next post loads. - -```tsx -import { - keepPreviousData, - placeholderData, - select, - useQuery, -} from '@tanstack/react-query-no-core-pluggable' - -function usePostTitle(id: number) { - return useQuery({ - queryKey: ['post', id], - queryFn: () => fetchPost(id), // Promise<{ title: string }> - select: [select, (post) => post.title], - placeholderData: placeholderData(keepPreviousData), - }) -} -``` - -## Mutations and cache operations - -`useMutation`, `useMutationState`, and `useIsMutating` acquire the client's mutation cache automatically. To inspect or subscribe to it directly, replace `client.getMutationCache()` with the named export `getMutationCache(client)`. The first call creates a default cache for that client. If you supplied `new QueryClient({ mutationCache })`, the helper returns that same cache. An app that uses only `useQuery` can omit the mutation cache implementation from its bundle. - -Integrations that subscribe to both caches need the same migration. For example, a persistence integration for this adapter can subscribe to `client.getQueryCache()` and `getMutationCache(client)`. The stock `@tanstack/query-persist-client-core` subscription expects the v6 client instance method. - -Pass `scope: serialScope('orders')` to `useMutation` to run mutations with that ID one at a time within a cache. Multiple calls to `serialScope('orders')` share the queue. The scope ID survives dehydration and hydration. - -Imperative infinite queries and bulk cache operations are named exports. Pass the client as the first argument. - -```ts -import { - infiniteQuery, - invalidateQueries, -} from '@tanstack/react-query-no-core-pluggable' - -await infiniteQuery(client, orderPageOptions) -await invalidateQueries(client, { queryKey: ['orders'] }) -``` - -The other bulk operations are `getQueriesData`, `setQueriesData`, `removeQueries`, `resetQueries`, `cancelQueries`, and `refetchQueries`. Single-query access such as `client.getQueryData(key)` stays on the client. All three option helpers (`queryOptions`, `infiniteQueryOptions`, and `mutationOptions`) return their argument unchanged and share one JavaScript implementation. diff --git a/packages/react-query-no-core-pluggable/root.oxlint.config.ts b/packages/react-query-no-core-pluggable/root.oxlint.config.ts deleted file mode 120000 index 56565c65534..00000000000 --- a/packages/react-query-no-core-pluggable/root.oxlint.config.ts +++ /dev/null @@ -1 +0,0 @@ -../../oxlint.config.ts \ No newline at end of file diff --git a/packages/react-query-no-core-pluggable/root.tsdown.config.js b/packages/react-query-no-core-pluggable/root.tsdown.config.js deleted file mode 120000 index a997d5d337c..00000000000 --- a/packages/react-query-no-core-pluggable/root.tsdown.config.js +++ /dev/null @@ -1 +0,0 @@ -../../scripts/getTsdownConfig.js \ No newline at end of file diff --git a/packages/react-query-no-core-pluggable/src/QueryErrorResetBoundary.tsx b/packages/react-query-no-core-pluggable/src/QueryErrorResetBoundary.tsx deleted file mode 100644 index 8c7dad91cb0..00000000000 --- a/packages/react-query-no-core-pluggable/src/QueryErrorResetBoundary.tsx +++ /dev/null @@ -1,169 +0,0 @@ -'use client' -import * as React from 'react' - -// CONTEXT - -/** - * Resets any query errors within the boundary, so queries know they can try again. - */ -export type QueryErrorResetFunction = () => void - -/** - * Returns whether the boundary has been reset and not yet cleared. - */ -export type QueryErrorIsResetFunction = () => boolean - -/** - * Clears the reset state, so queries know not to try again until the boundary is reset again. - */ -export type QueryErrorClearResetFunction = () => void - -/** - * The value a `QueryErrorResetBoundary` shares through context, used to reset query errors within - * it and to check whether a reset was requested. - */ -export interface QueryErrorResetBoundaryValue { - /** - * Clears the reset state, so queries know not to try again until the boundary is reset again. - */ - clearReset: QueryErrorClearResetFunction - /** - * Returns whether the boundary has been reset and not yet cleared. - */ - isReset: QueryErrorIsResetFunction - /** - * Resets any query errors within the boundary, so queries know they can try again. - */ - reset: QueryErrorResetFunction -} - -/** - * Creates the value shared through the boundary's context, which tracks whether a reset was - * requested. - * @returns The `clearReset`, `isReset`, and `reset` functions of the boundary. - */ -function createValue(): QueryErrorResetBoundaryValue { - let isReset = false - return { - /** - * Clears the reset state, so queries know not to try again until the boundary is reset again. - */ - clearReset: () => { - isReset = false - }, - /** - * Resets any query errors within the boundary, so queries know they can try again. - */ - reset: () => { - isReset = true - }, - /** - * Returns whether the boundary has been reset and not yet cleared. - * @returns `true` if the boundary has been reset and not yet cleared. - */ - isReset: () => { - return isReset - }, - } -} - -const QueryErrorResetBoundaryContext = React.createContext(createValue()) - -// HOOK - -/** - * This hook will reset any query errors within the closest `QueryErrorResetBoundary`. If there is no boundary - * defined it will reset them globally. - * @returns The boundary's {@link QueryErrorResetBoundaryValue}. - * @example - * ```tsx - * import { ErrorBoundary } from 'react-error-boundary' - * import { useQueryErrorResetBoundary } from '@tanstack/react-query-no-core-pluggable' - * - * function App({ children }: { children: React.ReactNode }) { - * const { reset } = useQueryErrorResetBoundary() - * - * return ( - * ( - *
    - * There was an error! - * - *
    - * )} - * > - * {children} - *
    - * ) - * } - * ``` - */ -export const useQueryErrorResetBoundary = () => - React.useContext(QueryErrorResetBoundaryContext) - -// COMPONENT - -/** - * A render-prop function usable as `children` on `QueryErrorResetBoundary`. - * @param value - The boundary's {@link QueryErrorResetBoundaryValue}. - * @returns The children to render. - */ -export type QueryErrorResetBoundaryFunction = ( - value: QueryErrorResetBoundaryValue, -) => React.ReactNode - -/** - * The props accepted by `QueryErrorResetBoundary`. - */ -export interface QueryErrorResetBoundaryProps { - /** - * Either a plain node, or a function that receives the boundary's {@link QueryErrorResetBoundaryValue} and - * returns a node. - */ - children: QueryErrorResetBoundaryFunction | React.ReactNode -} - -/** - * When using `suspense` or `throwOnError` in your queries, you need a way to let queries know that you want to - * try again when re-rendering after some error occurred. With the `QueryErrorResetBoundary` component you can - * reset any query errors within the boundaries of the component. - * @param props - The `children` to render. - * @returns The `children`, rendered as-is, or called with the boundary's {@link QueryErrorResetBoundaryValue} - * if `children` is a function. - * @example - * ```tsx - * import { ErrorBoundary } from 'react-error-boundary' - * import { QueryErrorResetBoundary } from '@tanstack/react-query-no-core-pluggable' - * - * function App() { - * return ( - * - * {({ reset }) => ( - * ( - *
    - * There was an error! - * - *
    - * )} - * > - * - *
    - * )} - *
    - * ) - * } - * ``` - */ -export const QueryErrorResetBoundary = ({ - children, -}: QueryErrorResetBoundaryProps) => { - const [value] = React.useState(() => createValue()) - return ( - - {typeof children === 'function' ? children(value) : children} - - ) -} diff --git a/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts b/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts deleted file mode 100644 index 198111f07dd..00000000000 --- a/packages/react-query-no-core-pluggable/src/infiniteQueryOptions.ts +++ /dev/null @@ -1,304 +0,0 @@ -import { identity } from './runtime/identity' -import type { - DefaultError, - InfiniteData, - InitialDataFunction, - NonUndefinedGuard, - OmitKeyof, - QueryKey, - QueryKeyWithDataTag, - SkipToken, -} from '@tanstack/query-types/bindings' -import type { UseInfiniteQueryOptions } from './types' - -/** - * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is omitted, may be - * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is - * `pending`. - * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. - * @template TError - The type of errors your `queryFn` may throw. - * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, - * the shape of all fetched pages plus their page params. - * @template TQueryKey - The type of your `queryKey`. - * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. - */ -export type UndefinedInitialDataInfiniteOptions< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> = UseInfiniteQueryOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> & { - /** - * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been - * created or cached yet). If set to a function, the function will be called **once** during the shared/root - * query initialization, and be expected to synchronously return the initial data. Initial data is - * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the - * cache. - */ - initialData?: - | undefined - | NonUndefinedGuard> - | InitialDataFunction< - NonUndefinedGuard> - > -} - -/** - * The options accepted by the `infiniteQueryOptions` overload selected when `queryFn` is not `skipToken` and - * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` — same as - * {@link UndefinedInitialDataInfiniteOptions}, but `queryFn` may not be `skipToken`. - * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. - * @template TError - The type of errors your `queryFn` may throw. - * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, - * the shape of all fetched pages plus their page params. - * @template TQueryKey - The type of your `queryKey`. - * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. - */ -export type UnusedSkipTokenInfiniteOptions< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> = OmitKeyof< - UseInfiniteQueryOptions, - 'queryFn' -> & { - queryFn: Exclude< - UseInfiniteQueryOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >['queryFn'], - SkipToken - > -} - -/** - * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is known to be - * defined — `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). - * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. - * @template TError - The type of errors your `queryFn` may throw. - * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, - * the shape of all fetched pages plus their page params. - * @template TQueryKey - The type of your `queryKey`. - * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. - */ -export type DefinedInitialDataInfiniteOptions< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> = UseInfiniteQueryOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> & { - /** - * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been - * created or cached yet). If set to a function, the function will be called **once** during the shared/root - * query initialization, and be expected to synchronously return the initial data. Initial data is - * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the - * cache. - */ - initialData: - | NonUndefinedGuard> - | (() => NonUndefinedGuard>) -} - -type InfiniteQueryOptionsFn = { - /** - * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `infiniteQuery(client, options)`. - * `options.queryKey` is required and is the query key to generate options for. - * - * This overload is selected when `initialData` is known to be defined. - * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` known to be defined. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or - * automatically as the user scrolls. - * @see {@link useInfiniteQuery} to run an infinite query with these options. - * @example - * ```tsx - * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' - * - * export const projectsOptions = infiniteQueryOptions({ - * queryKey: ['projects'], - * queryFn: ({ pageParam }) => fetchProjects(pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * initialData: { pages: [], pageParams: [] }, - * }) - * - * function Projects() { - * // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the - * // list stays visible alongside the error. - * const { data, isError, error } = useInfiniteQuery(projectsOptions) - * - * return ( - *
    - * {isError ? Error: {error.message} : null} - *
      - * {data.pages.map((page) => page.projects.map((p) =>
    • {p.name}
    • ))} - *
    - *
    - * ) - * } - * ``` - */ - < - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: DefinedInitialDataInfiniteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - ): DefinedInitialDataInfiniteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - > & - QueryKeyWithDataTag, TError> - - /** - * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `infiniteQuery(client, options)`. - * `options.queryKey` is required and is the query key to generate options for. - * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @remarks See {@link useInfiniteQuery} for examples that fetch further pages, from a button click or - * automatically as the user scrolls. - * @see {@link useInfiniteQuery} to run an infinite query with these options. - * @example - * A parameterized factory, so the same options object can be reused per `postId`: - * ```tsx - * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' - * - * export const commentsOptions = (postId: string) => - * infiniteQueryOptions({ - * queryKey: ['post', postId, 'comments'], - * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * }) - * - * function Comments({ postId }: { postId: string }) { - * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return ( - *
      - * {data.pages.map((page) => page.comments.map((c) =>
    • {c.text}
    • ))} - *
    - * ) - * } - * ``` - */ - < - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: UnusedSkipTokenInfiniteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - ): UnusedSkipTokenInfiniteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - > & - QueryKeyWithDataTag, TError> - - /** - * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `infiniteQuery(client, options)`. - * `options.queryKey` is required and is the query key to generate options for. - * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @remarks See {@link useInfiniteQuery} for examples that fetch further pages (from a button click or - * automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set. - * @see {@link useInfiniteQuery} to run an infinite query with these options. - * @example - * A parameterized factory, so the same options object can be reused per `postId`: - * ```tsx - * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' - * - * export const commentsOptions = (postId: string) => - * infiniteQueryOptions({ - * queryKey: ['post', postId, 'comments'], - * queryFn: ({ pageParam }) => fetchComments(postId, pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * }) - * - * function Comments({ postId }: { postId: string }) { - * const { data, isPending, isError, error } = useInfiniteQuery(commentsOptions(postId)) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return ( - *
      - * {data.pages.map((page) => page.comments.map((c) =>
    • {c.text}
    • ))} - *
    - * ) - * } - * ``` - */ - < - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: UndefinedInitialDataInfiniteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - ): UndefinedInitialDataInfiniteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - > & - QueryKeyWithDataTag, TError> -} - -/** Preserves infinite query options and tags their key with the inferred pages and error types. */ -export const infiniteQueryOptions: InfiniteQueryOptionsFn = identity diff --git a/packages/react-query-no-core-pluggable/src/mutationOptions.ts b/packages/react-query-no-core-pluggable/src/mutationOptions.ts deleted file mode 100644 index 904ed253fc8..00000000000 --- a/packages/react-query-no-core-pluggable/src/mutationOptions.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { identity } from './runtime/identity' -import type { DefaultError, WithRequired } from '@tanstack/query-types/bindings' -import type { UseMutationOptions } from './types' - -type MutationOptionsFn = { - /** - * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. A - * `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with - * `useMutationState`. - * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, with a - * required `mutationKey`. - * @returns The same options object, unchanged. - * @see {@link useMutation} to run the mutation these options describe. - * @example - * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator: - * ```tsx - * import { mutationOptions, useMutationState } from '@tanstack/react-query-no-core-pluggable' - * - * const createPostOptions = mutationOptions({ - * mutationKey: ['posts', 'create'], - * mutationFn: createPost, - * }) - * - * function SavingIndicator() { - * const isCreatingPost = useMutationState({ - * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' }, - * }).length > 0 - * - * return isCreatingPost ? Saving… : null - * } - * ``` - */ - < - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, - >( - options: WithRequired< - UseMutationOptions, - 'mutationKey' - >, - ): WithRequired< - UseMutationOptions, - 'mutationKey' - > - - /** - * You can generally pass everything to `mutationOptions` that you can also pass to `useMutation`. No - * `mutationKey` is required on this overload — use this when you don't need to target the mutation via a - * `mutationKey` filter later (e.g. with `useMutationState`); it can still be observed through other filters, - * such as `status`. - * @param options - The mutation options to use, identical to what you'd pass to `useMutation`, without a - * `mutationKey`. - * @returns The same options object, unchanged. - * @remarks See the other overload's example for looking a mutation up via `useMutationState`. - * @see {@link useMutation} to run the mutation these options describe. - * @example - * ```tsx - * import { mutationOptions, useMutation } from '@tanstack/react-query-no-core-pluggable' - * - * export const createPostOptions = mutationOptions({ - * mutationFn: createPost, - * }) - * - * function CreatePost() { - * const mutation = useMutation(createPostOptions) - * return - * } - * ``` - */ - < - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, - >( - options: Omit< - UseMutationOptions, - 'mutationKey' - >, - ): Omit< - UseMutationOptions, - 'mutationKey' - > -} - -/** Preserves mutation option types when reusing the same options in multiple places. */ -export const mutationOptions: MutationOptionsFn = identity diff --git a/packages/react-query-no-core-pluggable/src/queryOptions.ts b/packages/react-query-no-core-pluggable/src/queryOptions.ts deleted file mode 100644 index c3b557c51f6..00000000000 --- a/packages/react-query-no-core-pluggable/src/queryOptions.ts +++ /dev/null @@ -1,249 +0,0 @@ -import { identity } from './runtime/identity' -import type { - DefaultError, - DefaultQueryFn, - InitialDataFunction, - NonUndefinedGuard, - OmitKeyof, - QueryKey, - QueryKeyWithDataTag, - SkipToken, -} from '@tanstack/query-types/bindings' -import type { QueryFunction } from './runtime/types' -import type { UseQueryOptions } from './types' - -/** - * The options accepted by the `queryOptions` overload selected when `initialData` is omitted, may be - * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is - * `pending`. - * @template TQueryFnData - The type your `queryFn` resolves to. - * @template TError - The type of errors your `queryFn` may throw. - * @template TData - The type `data` ends up as after `select` runs. - * @template TQueryKey - The type of your `queryKey`. - */ -export type UndefinedInitialDataOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = UseQueryOptions & { - /** - * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been - * created or cached yet). If set to a function, the function will be called **once** during the shared/root - * query initialization, and be expected to synchronously return the initial data. Initial data is - * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the - * cache. - */ - initialData?: - | undefined - | InitialDataFunction> - | NonUndefinedGuard -} - -/** - * The options accepted by the `queryOptions` overload selected when `queryFn` is not `skipToken` and - * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` — same as - * {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`. - * @template TQueryFnData - The type your `queryFn` resolves to. - * @template TError - The type of errors your `queryFn` may throw. - * @template TData - The type `data` ends up as after `select` runs. - * @template TQueryKey - The type of your `queryKey`. - */ -export type UnusedSkipTokenOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = OmitKeyof< - UseQueryOptions, - 'queryFn' -> & { - queryFn: Exclude< - UseQueryOptions['queryFn'], - SkipToken - > -} - -/** - * The options accepted by the `queryOptions` overload selected when `initialData` is known to be defined — - * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). - * @template TQueryFnData - The type your `queryFn` resolves to. - * @template TError - The type of errors your `queryFn` may throw. - * @template TData - The type `data` ends up as after `select` runs. - * @template TQueryKey - The type of your `queryKey`. - */ -export type DefinedInitialDataOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = Omit, 'queryFn'> & { - /** - * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been - * created or cached yet). If set to a function, the function will be called **once** during the shared/root - * query initialization, and be expected to synchronously return the initial data. Initial data is - * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the - * cache. - */ - initialData: - | NonUndefinedGuard - | (() => NonUndefinedGuard) - queryFn: QueryFunction | DefaultQueryFn -} - -type QueryOptionsFn = { - /** - * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can - * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and - * is the query key to generate options for. - * - * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never - * `undefined` (unless a `select` changes `TData` to include `undefined`). - * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @see {@link useQuery} to run a query with these options. - * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. - * @example - * ```tsx - * import { queryOptions, useQuery } from '@tanstack/react-query-no-core-pluggable' - * - * export const postsOptions = queryOptions({ - * queryKey: ['posts'], - * queryFn: fetchPosts, - * initialData: [], - * }) - * - * function Posts() { - * // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, - * // so the list stays visible alongside the error. - * const { data, isError, error } = useQuery(postsOptions) - * - * return ( - *
    - * {isError ? Error: {error.message} : null} - *
      - * {data.map((post) =>
    • {post.title}
    • )} - *
    - *
    - * ) - * } - * ``` - */ - < - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - >( - options: DefinedInitialDataOptions, - ): DefinedInitialDataOptions & - QueryKeyWithDataTag - - /** - * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can - * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and - * is the query key to generate options for. - * @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `useQuery`. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @see {@link useQuery} to run a query with these options. - * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. - * @example - * A parameterized factory, so the same options object can be reused per `id`: - * ```tsx - * import { queryOptions, useQuery } from '@tanstack/react-query-no-core-pluggable' - * - * export const postOptions = (id: string) => - * queryOptions({ - * queryKey: ['post', id], - * queryFn: () => fetchPost(id), - * }) - * - * function Post({ id }: { id: string }) { - * const { data, isPending, isError, error } = useQuery(postOptions(id)) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return

    {data.title}

    - * } - * ``` - */ - < - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - >( - options: UnusedSkipTokenOptions, - ): UnusedSkipTokenOptions & - QueryKeyWithDataTag - - /** - * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can - * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and - * is the query key to generate options for. - * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. - * @returns The same options object, typed so that `queryKey` carries the inferred data type. - * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below. - * @see {@link useQuery} to run a query with these options. - * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. - * @example - * A parameterized factory, so the same options object can be reused per `id`: - * ```tsx - * import { queryOptions, useQuery } from '@tanstack/react-query-no-core-pluggable' - * - * export const postOptions = (id: string) => - * queryOptions({ - * queryKey: ['post', id], - * queryFn: () => fetchPost(id), - * }) - * - * function Post({ id }: { id: string }) { - * const { data, isPending, isError, error } = useQuery(postOptions(id)) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return

    {data.title}

    - * } - * ``` - * @example - * A factory that disables the query, type safe, until `postId` is set: - * ```tsx - * import { queryOptions, skipToken, useQuery } from '@tanstack/react-query-no-core-pluggable' - * - * export const postOptions = (postId: number | undefined) => - * queryOptions({ - * queryKey: ['post', postId], - * queryFn: postId != null ? () => fetchPost(postId) : skipToken, - * }) - * - * function Post({ postId }: { postId: number | undefined }) { - * const { data, isLoading, isError, error } = useQuery(postOptions(postId)) - * - * if (postId == null) return 'Select a post' - * if (isLoading) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return

    {data?.title}

    - * } - * ``` - */ - < - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - >( - options: UndefinedInitialDataOptions< - TQueryFnData, - TError, - TData, - TQueryKey - >, - ): UndefinedInitialDataOptions & - QueryKeyWithDataTag -} - -/** Preserves query options and tags their key with the inferred data and error types. */ -export const queryOptions: QueryOptionsFn = identity diff --git a/packages/react-query-no-core-pluggable/src/runtime/environmentManager.ts b/packages/react-query-no-core-pluggable/src/runtime/environmentManager.ts deleted file mode 100644 index 576fc540f60..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/environmentManager.ts +++ /dev/null @@ -1,41 +0,0 @@ -import type { IsServerValue } from '@tanstack/query-types/bindings' - -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/react-query-no-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 - }, -} - -export type { IsServerValue } from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core-pluggable/src/runtime/focusManager.ts b/packages/react-query-no-core-pluggable/src/runtime/focusManager.ts deleted file mode 100644 index 40ea98cff79..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/focusManager.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { Subscribable } from './subscribable' -import type { - FocusManagerListener as Listener, - FocusManagerSetupFn as SetupFn, -} from '@tanstack/query-types/bindings' - -/** - * 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/react-query-no-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/react-query-no-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 = /* #__PURE__ */ new FocusManager() diff --git a/packages/react-query-no-core-pluggable/src/runtime/notifyManager.ts b/packages/react-query-no-core-pluggable/src/runtime/notifyManager.ts deleted file mode 100644 index d60c0155755..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/notifyManager.ts +++ /dev/null @@ -1,126 +0,0 @@ -import type { - BatchCallsCallback, - NotifyCallback, - NotifyFunction, - ScheduleFunction, -} from '@tanstack/query-types/bindings' - -/** - * 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/react-query-no-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/react-query-no-core-pluggable/src/runtime/onlineManager.ts b/packages/react-query-no-core-pluggable/src/runtime/onlineManager.ts deleted file mode 100644 index aaa6b7ec96f..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/onlineManager.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { Subscribable } from './subscribable' -import type { - OnlineManagerListener as Listener, - OnlineManagerSetupFn as SetupFn, -} from '@tanstack/query-types/bindings' - -/** - * 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/react-query-no-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/react-query-no-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/react-query-no-core-pluggable/src/runtime/queryCache.ts b/packages/react-query-no-core-pluggable/src/runtime/queryCache.ts deleted file mode 100644 index 09179c347f3..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/queryCache.ts +++ /dev/null @@ -1,301 +0,0 @@ -import { notifyManager } from './notifyManager' -import { Query } from './query' -import { Subscribable } from './subscribable' -import { hashKeyByOptions, matchQuery } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { QueryState } from './query' -import type { QueryClient } from './queryClient' -import type { QueryRuntime } from './runtimeBinding' -import type { - DefaultError, - QueryKey, - QueryOptions, - WithRequired, -} from './types' -import type { QueryFilters } from './utils' - -/** {@inheritDoc Shared.QueryCacheConfig} */ -export type QueryCacheConfig = Shared.QueryCacheConfig - -/** {@inheritDoc Shared.QueryCacheNotifyEvent} */ -export type QueryCacheNotifyEvent = Shared.QueryCacheNotifyEvent - -type QueryCacheListener = Shared.QueryCacheListener - -/** {@inheritDoc Shared.QueryStore} */ -export type QueryStore = Shared.QueryStore - -// CLASS - -/** - * The `QueryCache` is the storage mechanism for TanStack Query. It stores all the data, meta - * information, and state of the queries it contains. - * - * Normally, you will not interact with the `QueryCache` directly and instead use a `QueryClient` - * for a specific cache. You can subscribe to it (inherited from `Subscribable`) to be informed of - * safe/known updates to the cache, such as queries being added, removed, or updated — updates made - * outside of the cache's own tracked mechanisms (e.g. mutating a query's state object directly) do - * not notify subscribers. - * @example - * ```ts - * const unsubscribe = queryCache.subscribe((event) => { - * console.log(event.type, event.query) - * }) - * ``` - */ -export class QueryCache extends Subscribable { - #queries: QueryStore - - constructor(public config: QueryCacheConfig = {}) { - super() - this.#queries = new Map() - } - - /** - * Returns the existing `Query` instance for the given options' `queryKey`/`queryHash`, or - * builds and adds a new one to the cache if none exists yet. Used by framework adapters and - * plugins (e.g. broadcast/persistence) that need to get-or-create a `Query` directly, bypassing - * the reactive `QueryObserver` machinery. - * @param client - The client the query belongs to, used to default its options. - * @param options - The query options, including the `queryKey`. A new query is created with the - * options defaulted by {@link QueryClient#defaultQueryOptions}. - * @param state - The initial state of a newly created query, e.g. when hydrating. Ignored if the - * query already exists. - * @returns The existing or newly created query. - * @example - * ```ts - * const queryCache = queryClient.getQueryCache() - * - * const query = queryCache.build(queryClient, { - * queryKey: ['posts'], - * queryFn: fetchPosts, - * }) - * ``` - */ - build< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - >( - client: QueryClient, - options: WithRequired< - QueryOptions, - 'queryKey' - >, - state?: QueryState, - ): Query { - const queryKey = options.queryKey - const queryHash = - options.queryHash ?? hashKeyByOptions(queryKey, this.config.queryKey) - let query = this.get(queryHash) - - if (!query) { - query = new Query({ - client, - queryKey, - queryHash, - options: client.defaultQueryOptions(options), - state, - defaultOptions: client.getQueryDefaults(queryKey), - }) - this.add(query) - } - - return query - } - - /** - * Adds a query to the cache. - * @internal - * @param query - The query to add. If a query with the same hash is already cached, nothing - * happens. - */ - add(query: Query): void { - if (!this.#queries.has(query.queryHash)) { - this.#queries.set(query.queryHash, query) - - this.notify({ - type: 'added', - query, - }) - } - } - - /** - * Destroys the given `Query` and removes it from the cache, notifying subscribers with a - * `'removed'` event. A no-op if the query is no longer the one currently stored under its hash - * (e.g. it was already replaced). Used by plugins (e.g. the broadcast client) that mirror - * removals across `QueryCache` instances. - * @param query - The query to remove. - * @example - * ```ts - * const queryCache = queryClient.getQueryCache() - * const query = queryCache.find({ queryKey: ['posts'] }) - * - * if (query) { - * queryCache.remove(query) - * } - * ``` - */ - remove(query: Query): void { - const queryInMap = this.#queries.get(query.queryHash) - - if (queryInMap === query) { - query.destroy() - this.#queries.delete(query.queryHash) - this.notify({ type: 'removed', query }) - } - } - - /** - * Removes all queries from the cache. - * @example - * ```ts - * const queryCache = queryClient.getQueryCache() - * - * queryCache.clear() - * ``` - */ - clear(): void { - notifyManager.batch(() => { - this.getAll().forEach((query) => { - this.remove(query) - }) - }) - } - - /** - * Returns the `Query` instance stored under the given `queryHash`, or `undefined` if none - * exists. Unlike {@link QueryCache#find}, this looks up by the already-computed hash rather - * than by `QueryFilters`. Used by plugins (e.g. broadcast/hydration) that already have a hash - * to look up directly. - * @param queryHash - The hash of the query to look up. - * @returns The query stored under the hash, or `undefined`. - * @example - * ```ts - * const queryCache = queryClient.getQueryCache() - * const queryHash = hashKey(['posts']) - * - * const query = queryCache.get(queryHash) - * ``` - */ - get< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - >( - queryHash: string, - ): Query | undefined { - return this.#queries.get(queryHash) as - | Query - | undefined - } - - /** - * Returns all queries within the cache. - * @returns Every query in the cache. - * @example - * ```ts - * const queryCache = queryClient.getQueryCache() - * - * const queries = queryCache.getAll() - * ``` - */ - getAll(): Array { - return [...this.#queries.values()] - } - - /** - * A slightly more advanced method that can be used to get an existing query instance from the - * cache. This instance not only contains all the state for the query, but all of the instances, - * and underlying guts of the query as well. If the query 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 query in rare scenarios (e.g. looking at `query.state.dataUpdatedAt` to - * decide whether a query is fresh enough to be used as an initial value). - * @param filters - The filters to match, including the required `queryKey`. `exact` defaults to - * `true`. - * @returns The first matching query, or `undefined`. - * @see {@link QueryCache#findAll} - * @example - * ```ts - * const queryCache = queryClient.getQueryCache() - * - * const query = queryCache.find({ queryKey: ['posts'] }) - * ``` - */ - find( - filters: WithRequired, - ): Query | undefined { - const defaultedFilters = { exact: true, ...filters } - - return this.getAll().find((query) => - matchQuery(defaultedFilters, query, this.config.queryKey), - ) as Query | undefined - } - - /** - * An even more advanced method that can be used to get existing query instances from the cache - * that partially match a query key. If no queries match, an empty array is returned. - * - * This is not typically needed for most applications, but can come in handy when needing more - * information about queries in rare scenarios. - * @param filters - The filters to match. Without filters, every query is returned. - * @returns The matching queries. - * @see {@link QueryCache#find} - * @example - * ```ts - * const queryCache = queryClient.getQueryCache() - * - * const queries = queryCache.findAll({ queryKey: ['posts'] }) - * ``` - */ - findAll(filters: QueryFilters = {}): Array { - const queries = this.getAll() - return Object.keys(filters).length > 0 - ? queries.filter((query) => - matchQuery(filters, query, this.config.queryKey), - ) - : queries - } - - /** - * Notifies every cache listener of an event, in one batch. - * @internal - * @param event - The event passed to every listener. - */ - notify(event: QueryCacheNotifyEvent): void { - notifyManager.batch(() => { - this.listeners.forEach((listener) => { - listener(event) - }) - }) - } - - /** - * Calls {@link Query#onFocus} on every cached query, in one batch. - * @internal - */ - onFocus(): void { - notifyManager.batch(() => { - this.getAll().forEach((query) => { - query.onFocus() - }) - }) - } - - /** - * Calls {@link Query#onOnline} on every cached query, in one batch. - * @internal - */ - onOnline(): void { - notifyManager.batch(() => { - this.getAll().forEach((query) => { - query.onOnline() - }) - }) - } -} diff --git a/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts b/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts deleted file mode 100644 index a5f8ac6f7ce..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/queryClient.ts +++ /dev/null @@ -1,722 +0,0 @@ -import { focusManager } from './focusManager' -import { onlineManager } from './onlineManager' -import { QueryCache } from './queryCache' -import { - defaultQueryFn, - functionalUpdate, - hashKeyByOptions, - partialMatchKey, - resolveQueryValue, - skipToken, -} from './utils' -import type { WithoutSkipToken } from '@tanstack/query-types/bindings' -import type { MutationCache } from './mutationCache' -import type { QueryState } from './query' -import type { - CacheKeyConfig, - DefaultError, - DefaultOptions, - DefaultedQueryObserverOptions, - InferDataFromTag, - InferErrorFromTag, - MutationKey, - MutationObserverOptions, - MutationOptions, - OmitKeyof, - QueryClientConfig, - QueryExecuteOptions, - QueryKey, - QueryObserverOptionsBase, - QueryOptions, - SetDataOptions, -} from './types' -import type { MutationFilters, QueryFilters, Updater } from './utils' - -type QueryDefaults = OmitKeyof, 'queryKey'> -type MutationDefaults = MutationOptions - -class KeyDefaults< - TKey extends ReadonlyArray, - TOptions extends object, -> { - #entries = new Map() - - set(key: TKey, options: TOptions, config?: CacheKeyConfig): void { - this.#entries.set(hashKeyByOptions(key, config), { key, options }) - } - - get(key: TKey, config?: CacheKeyConfig): Partial { - const result: Partial = {} - for (const entry of this.#entries.values()) { - if (partialMatchKey(key, entry.key, config?.equalityFn)) { - Object.assign(result, entry.options) - } - } - return result - } -} - -/** @internal */ -export const mutationCacheKey = Symbol.for( - '@tanstack/react-query-no-core-pluggable/mutationCache', -) - -/** - * Stores the query cache and default options for this client's queries and mutations. - * Pass a custom mutation cache in the constructor or let mutation hooks and - * `getMutationCache(client)` create one on first use. - * @example - * ```ts - * const queryClient = new QueryClient({ - * defaultOptions: { - * queries: { - * staleTime: Infinity, - * }, - * }, - * }) - * - * await queryClient.query({ queryKey: ['posts'], queryFn: fetchPosts }) - * ``` - */ -export class QueryClient { - /** @internal */ - [mutationCacheKey]?: MutationCache - #queryCache: QueryCache - #defaultOptions: DefaultOptions - #queryDefaults = new KeyDefaults() - #mutationDefaults = new KeyDefaults() - #mountCount: number - #unsubscribeFocus?: () => void - #unsubscribeOnline?: () => void - - constructor(config: QueryClientConfig = {}) { - this.#queryCache = config.queryCache || new QueryCache() - this[mutationCacheKey] = config.mutationCache - this.#defaultOptions = config.defaultOptions || {} - this.#mountCount = 0 - } - - /** - * Called by a framework adapter's `QueryClientProvider`-equivalent when it mounts, to start - * listening for focus/online events and resume paused mutations. Ref-counted via an internal - * mount count, so nested or multiple providers sharing the same `QueryClient` don't tear down - * the shared listeners until the last one unmounts. - */ - mount(): void { - this.#mountCount++ - if (this.#mountCount !== 1) return - - this.#unsubscribeFocus = focusManager.subscribe(async (focused) => { - if (focused) { - await this.resumePausedMutations() - this.#queryCache.onFocus() - } - }) - this.#unsubscribeOnline = onlineManager.subscribe(async (online) => { - if (online) { - await this.resumePausedMutations() - this.#queryCache.onOnline() - } - }) - } - - /** - * The inverse of {@link QueryClient#mount} — called by a framework adapter's - * `QueryClientProvider`-equivalent when it unmounts. Only tears down the focus/online - * listeners once the mount count returns to `0`. - */ - unmount(): void { - this.#mountCount-- - if (this.#mountCount !== 0) return - - this.#unsubscribeFocus?.() - this.#unsubscribeFocus = undefined - - this.#unsubscribeOnline?.() - this.#unsubscribeOnline = undefined - } - - /** - * Returns the number of queries in the cache that are currently fetching, optionally - * matching a set of filters. This includes background-fetching, loading new pages, and - * loading more infinite query results. - * @param filters - Narrows down which fetching queries are counted. Without filters, every - * fetching query is counted. - * @returns The number of matching queries whose `fetchStatus` is `'fetching'`. - * @example - * ```ts - * if (queryClient.isFetching()) { - * console.log('At least one query is fetching!') - * } - * ``` - */ - isFetching(filters?: Omit): number { - return this.#queryCache.findAll({ ...filters, fetchStatus: 'fetching' }) - .length - } - - /** - * Returns the number of mutations in the cache that are currently pending, optionally - * matching a set of filters. - * @param filters - Narrows down which pending mutations are counted. Without filters, every - * pending mutation is counted. - * @returns The number of matching mutations whose `status` is `'pending'`. - * @example - * ```ts - * if (queryClient.isMutating()) { - * console.log('At least one mutation is pending!') - * } - * ``` - */ - isMutating< - TMutationFilters extends MutationFilters = MutationFilters< - any, - any - >, - >(filters?: NoInfer>): number { - return ( - this[mutationCacheKey]?.findAll({ ...filters, status: 'pending' }) - .length ?? 0 - ) - } - - /** - * Imperative (non-reactive) way to retrieve data for a QueryKey. - * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates. - * - * Hint: Do not use this function inside a component, because it won't receive updates. - * Use `useQuery` to create a `QueryObserver` that subscribes to changes. - * @param queryKey - The query key of the query to read. - * @returns The cached data for the query, or `undefined` if no query with this key has been observed yet. - * @see {@link getQueriesData} - */ - getQueryData< - TQueryFnData = unknown, - TTaggedQueryKey extends QueryKey = QueryKey, - TInferredQueryFnData = InferDataFromTag, - >(queryKey: TTaggedQueryKey): TInferredQueryFnData | undefined { - const options = this.defaultQueryOptions({ queryKey }) - - return this.#queryCache.get(options.queryHash)?.state - .data - } - - /** - * Synchronous way to immediately update a query's cached data. If the updater (or the value - * passed) resolves to `undefined`, the cache is left untouched and no query is created; - * otherwise, if the query does not exist yet, it will be created. To update multiple queries - * at once by partially matching query keys, import `setQueriesData`. - * - * Updates must be performed immutably: do not mutate `oldData`, or data previously retrieved - * via {@link QueryClient#getQueryData}, in place. - * @param queryKey - The query key to set data for. - * @param updater - Either the new data, or a function that receives the 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 The data that was written, or `undefined` if the updater returned `undefined` — in that case - * the write is skipped and the cache is left unchanged. - * @example - * ```ts - * queryClient.setQueryData(['posts'], newPosts) - * - * // Or, using an updater function that receives the current data: - * queryClient.setQueryData(['posts'], (oldPosts) => [...oldPosts, newPost]) - * ``` - */ - setQueryData< - TQueryFnData = unknown, - TTaggedQueryKey extends QueryKey = QueryKey, - TInferredQueryFnData = InferDataFromTag, - >( - queryKey: TTaggedQueryKey, - updater: Updater< - InferDataFromTag, TTaggedQueryKey> | undefined, - NoInfer | undefined - >, - options?: SetDataOptions, - ): NoInfer | undefined { - const defaultedOptions = this.defaultQueryOptions< - any, - any, - unknown, - any, - QueryKey - >({ queryKey }) - - const query = this.#queryCache.get< - InferDataFromTag, TTaggedQueryKey> - >(defaultedOptions.queryHash) - const prevData = query?.state.data - const data = functionalUpdate(updater, prevData) - - if (data === undefined) { - return undefined - } - - return this.#queryCache - .build(this, defaultedOptions) - .setData(data, { ...options, manual: true }) - } - - /** - * Imperative (non-reactive) way to retrieve an existing query's state. If the query does not - * exist, `undefined` is returned. - * @param queryKey - The query key of the query to read. - * @returns The query's state, or `undefined` if no query with this key exists. - * @example - * ```ts - * const state = queryClient.getQueryState(['posts']) - * console.log(state?.dataUpdatedAt) - * ``` - */ - getQueryState< - TQueryFnData = unknown, - TError = DefaultError, - TTaggedQueryKey extends QueryKey = QueryKey, - TInferredQueryFnData = InferDataFromTag, - TInferredError = InferErrorFromTag, - >( - queryKey: TTaggedQueryKey, - ): QueryState | undefined { - const options = this.defaultQueryOptions({ queryKey }) - return this.#queryCache.get( - options.queryHash, - )?.state - } - - /** - * Asynchronous method to fetch and cache a query, resolving with the data or throwing with - * the error. - * - * If the query already exists in the cache and its data is not stale (per the given - * `staleTime`), the cached data is returned without fetching. Otherwise, the query is fetched - * and the promise resolves once the fetch settles. If a `select` function is provided, it is - * applied to the data in both cases (cached or freshly fetched) before it is returned. - * - * Unlike a reactive observer, retries are disabled by default here (`retry: false`) unless - * explicitly configured, since there is no component to catch a thrown error and retry through - * re-render. - * - * The accepted options are `QueryObserverOptions` minus the fields that only make sense for a - * reactive observer — `enabled`, `refetchInterval`, `refetchIntervalInBackground`, - * `refetchOnWindowFocus`, `refetchOnReconnect`, `refetchOnMount`, `retryOnMount`, - * `notifyOnChangeProps`, `throwOnError`, `suspense`, and `placeholderData` are not part of this - * method's options. - * Shared query options can contain `skipToken` as their `queryFn`. If the supplied options contain - * the token, the call skips fetching and resolves with existing data regardless of freshness. - * It applies `select` when data exists and resolves to `undefined` on a cache miss. - * Use {@link QueryClient#getQueryData} to read the cache directly. - * @param options - The query options, including the `queryKey` and the `queryFn` used if the - * query needs to fetch. - * @returns A promise that resolves to the data, 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 queryClient.query({ queryKey, queryFn, staleTime: 10000 }) - * } catch (error) { - * console.log(error) - * } - * ``` - */ - query< - TQueryFnData, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, - >( - options: WithoutSkipToken< - QueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - > - >, - ): Promise - query< - TQueryFnData, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, - >( - options: QueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - >, - ): Promise - async query< - TQueryFnData, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, - >( - options: QueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - >, - ): Promise { - const defaultedOptions = this.defaultQueryOptions(options) - let queryData: TQueryData - - if (options.queryFn === skipToken) { - const cachedData = this.#queryCache.get< - TQueryFnData, - TError, - TQueryData, - TQueryKey - >(defaultedOptions.queryHash)?.state.data - if (cachedData === undefined) return undefined - queryData = cachedData - } else { - // https://github.com/tannerlinsley/react-query/issues/652 - if (defaultedOptions.retry === undefined) { - defaultedOptions.retry = false - } - - const query = this.#queryCache.build(this, defaultedOptions) - - const isStale = query.isStaleByTime( - resolveQueryValue(defaultedOptions.staleTime, query), - ) - - queryData = isStale - ? await query.fetch(defaultedOptions) - : (query.state.data as TQueryData) - } - - const select = defaultedOptions.select - - if (select) { - return select[1](queryData) - } - - return queryData as unknown as TData - } - - /** - * Resumes mutations that were paused because there was no network connection. Does nothing - * (resolving immediately) if the client is currently offline. - * @returns A promise that resolves once the resumed mutations have settled. - * @example - * ```ts - * import { QueryClient } from '@tanstack/react-query-no-core-pluggable' - * - * const queryClient = new QueryClient() - * await queryClient.resumePausedMutations() - * ``` - */ - resumePausedMutations(): Promise { - if (onlineManager.isOnline()) { - return ( - this[mutationCacheKey]?.resumePausedMutations() ?? Promise.resolve([]) - ) - } - return Promise.resolve() - } - - /** - * Returns the query cache this client is connected to. - * @returns The {@link QueryCache} instance. - * @example - * ```ts - * import { QueryClient } from '@tanstack/react-query-no-core-pluggable' - * - * const queryClient = new QueryClient() - * const queryCache = queryClient.getQueryCache() - * const queries = queryCache.findAll({ queryKey: ['posts'] }) - * ``` - */ - getQueryCache(): QueryCache { - return this.#queryCache - } - - /** - * Returns the default options that were set when creating the client, or via - * {@link QueryClient#setDefaultOptions}. - * @returns The client's current default options. - * @example - * ```ts - * import { QueryClient } from '@tanstack/react-query-no-core-pluggable' - * - * const queryClient = new QueryClient() - * const defaultOptions = queryClient.getDefaultOptions() - * ``` - */ - getDefaultOptions(): DefaultOptions { - return this.#defaultOptions - } - - /** - * Dynamically sets the default options for this client, overwriting any previously defined - * default options. - * @param options - The new default options for queries and mutations. - * @see {@link QueryClient#getDefaultOptions} - * @example - * ```ts - * import { QueryClient } from '@tanstack/react-query-no-core-pluggable' - * - * const queryClient = new QueryClient() - * queryClient.setDefaultOptions({ - * queries: { - * staleTime: Infinity, - * }, - * }) - * ``` - */ - setDefaultOptions(options: DefaultOptions): void { - this.#defaultOptions = options - } - - /** - * Sets default options for queries whose query key partially matches the given `queryKey`. - * - * If several registered query defaults match a given query key, they are merged together in - * registration order by {@link QueryClient#getQueryDefaults}, so register defaults from the - * most generic key to the least generic one — more specific defaults should be registered - * after more generic ones so they take precedence. - * @param queryKey - The query key that query keys are partially matched against. - * @param options - The default options applied to matching queries. - * @example - * ```ts - * queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts }) - * - * await queryClient.query({ queryKey: ['posts'] }) - * ``` - */ - setQueryDefaults< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - >( - queryKey: QueryKey, - options: Partial< - OmitKeyof< - QueryObserverOptionsBase, - 'queryKey' - > - >, - ): void { - this.#queryDefaults.set(queryKey, options, this.#queryCache.config.queryKey) - } - - /** - * Returns the default options registered for queries whose query key partially matches the - * given `queryKey`, via {@link QueryClient#setQueryDefaults}. If multiple registered defaults - * match, they are merged together in registration order. - * @param queryKey - The query key to look up registered defaults for. - * @returns The merged default options of every registration that matches, or an empty object if - * none match. - * @example - * ```ts - * const defaultOptions = queryClient.getQueryDefaults(['posts']) - * ``` - */ - getQueryDefaults( - queryKey: QueryKey, - ): OmitKeyof, 'queryKey'> { - return this.#queryDefaults.get(queryKey, this.#queryCache.config.queryKey) - } - - /** - * Sets default options for mutations whose mutation key partially matches the given - * `mutationKey`. As with {@link QueryClient#setQueryDefaults}, the order of registration - * matters when several registered defaults match the same mutation key. - * @param mutationKey - The mutation key that mutation keys are partially matched against. - * @param options - The default options applied to matching mutations. - * @see {@link QueryClient#getMutationDefaults} - * @example - * ```ts - * queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost }) - * ``` - */ - setMutationDefaults< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, - >( - mutationKey: MutationKey, - options: OmitKeyof< - MutationObserverOptions, - 'mutationKey' - >, - ): void { - this.#mutationDefaults.set( - mutationKey, - options, - this[mutationCacheKey]?.config.mutationKey, - ) - } - - /** - * Returns the default options registered for mutations whose mutation key partially matches - * the given `mutationKey`, via {@link QueryClient#setMutationDefaults}. If multiple registered - * defaults match, they are merged together in registration order. - * @param mutationKey - The mutation key to look up registered defaults for. - * @returns The merged default options of every registration that matches, or an empty object if - * none match. - * @example - * ```ts - * const defaultOptions = queryClient.getMutationDefaults(['addPost']) - * ``` - */ - getMutationDefaults( - mutationKey: MutationKey, - ): OmitKeyof, 'mutationKey'> { - return this.#mutationDefaults.get( - mutationKey, - this[mutationCacheKey]?.config.mutationKey, - ) - } - - /** - * Called by framework adapters (e.g. inside `useQuery`) to resolve the options passed by the - * caller into their final, defaulted form: merging the client's own `defaultOptions.queries`, - * then `queryClient.setQueryDefaults` for the given `queryKey`, then the caller's options on - * top. A no-op if the options are already defaulted (`_defaulted: true`). - * @param options - The query options passed by the caller. - * @returns The defaulted options, with `queryHash` and dependent defaults (e.g. - * `refetchOnReconnect`) filled in. - */ - defaultQueryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, - >( - options: QueryObserverOptionsBase< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - >, - ): DefaultedQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - > { - if (options._defaulted) { - return options as DefaultedQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - > - } - - const queryDefaults = this.getQueryDefaults(options.queryKey) - const defaultedOptions = { - ...this.#defaultOptions.queries, - ...queryDefaults, - ...options, - _defaulted: true, - } - - if (defaultedOptions.queryFn === defaultQueryFn) { - defaultedOptions.queryFn = - 'queryFn' in queryDefaults - ? queryDefaults.queryFn - : this.#defaultOptions.queries?.queryFn - } - - if (!defaultedOptions.queryHash) { - defaultedOptions.queryHash = hashKeyByOptions( - defaultedOptions.queryKey, - this.#queryCache.config.queryKey, - ) - } - - // dependent default values - if (defaultedOptions.refetchOnReconnect === undefined) { - defaultedOptions.refetchOnReconnect = - defaultedOptions.networkMode !== 'always' - } - if (defaultedOptions.throwOnError === undefined) { - defaultedOptions.throwOnError = !!defaultedOptions.suspense - } - - if (!defaultedOptions.networkMode && defaultedOptions.persister) { - defaultedOptions.networkMode = 'offlineFirst' - } - - if (defaultedOptions.queryFn === skipToken) { - defaultedOptions.enabled = false - } - - return defaultedOptions as DefaultedQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - > - } - - /** - * The mutation counterpart of {@link QueryClient#defaultQueryOptions}. Called by framework - * adapters (e.g. inside `useMutation`) to merge the client's `defaultOptions.mutations`, then - * `queryClient.setMutationDefaults` for the given `mutationKey`, then the caller's options on - * top. A no-op if the options are already defaulted (`_defaulted: true`). - * @param options - The mutation options passed by the caller. - * @returns The defaulted options. - */ - defaultMutationOptions>( - options?: T, - ): T { - if (options?._defaulted) { - return options - } - return { - ...this.#defaultOptions.mutations, - ...(options?.mutationKey && - this.getMutationDefaults(options.mutationKey)), - ...options, - _defaulted: true, - } as T - } - - /** - * Clears both the query cache and the mutation cache this client is connected to. - * This clears their garbage collection timers and cancels in-flight query fetches. - * Running mutations continue to execute. - * @example - * ```ts - * import { QueryClient } from '@tanstack/react-query-no-core-pluggable' - * - * const queryClient = new QueryClient() - * queryClient.clear() - * ``` - */ - clear(): void { - this.#queryCache.clear() - this[mutationCacheKey]?.clear() - } -} diff --git a/packages/react-query-no-core-pluggable/src/runtime/removable.ts b/packages/react-query-no-core-pluggable/src/runtime/removable.ts deleted file mode 100644 index d6356c73845..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/removable.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { isServer as isServerEnvironment } from './environmentManager' -import { timeoutManager } from './timeoutManager' -import { isValidTimeout } from './utils' -import type { ManagedTimerId } from './timeoutManager' - -/** - * The base class for cache entries that are garbage collected once nothing is using them — - * `Query` and `Mutation` both extend it. `gcTime` controls how long an unused entry is kept. - */ -export abstract class Removable { - gcTime!: number - #gcTimeout?: ManagedTimerId - - /** - * Clears the pending garbage collection timeout, so the entry is no longer scheduled for removal. - * A subclass may override this to release what it holds on to as well — `Query` also cancels any - * in-flight fetch. - */ - destroy(): void { - this.clearGcTimeout() - } - - /** - * Schedules the entry to be removed from its cache after `gcTime`, replacing any timeout scheduled - * before. Nothing is scheduled if `gcTime` is `Infinity`. - */ - protected scheduleGc(): void { - this.clearGcTimeout() - - if (isValidTimeout(this.gcTime)) { - this.#gcTimeout = timeoutManager.setTimeout(() => { - this.optionalRemove() - }, this.gcTime) - } - } - - /** - * Updates `gcTime`, keeping the longest one seen so far. Without a value, it defaults to 5 minutes - * on the client and `Infinity` on the server. - * @param newGcTime - The `gcTime` from the latest options, if any. - */ - protected updateGcTime(newGcTime: number | undefined): void { - // Default to 5 minutes (Infinity for server-side) if no gcTime is set - this.gcTime = Math.max( - this.gcTime || 0, - newGcTime ?? (isServerEnvironment() ? Infinity : 5 * 60 * 1000), - ) - } - - /** - * Cancels the scheduled removal, if there is one. - */ - protected clearGcTimeout() { - if (this.#gcTimeout !== undefined) { - timeoutManager.clearTimeout(this.#gcTimeout) - this.#gcTimeout = undefined - } - } - - /** - * Called when the garbage collection timeout fires. Subclasses remove the entry from its cache - * unless it is still in use, e.g. because it has observers. - */ - protected abstract optionalRemove(): void -} diff --git a/packages/react-query-no-core-pluggable/src/runtime/retryer.ts b/packages/react-query-no-core-pluggable/src/runtime/retryer.ts deleted file mode 100644 index 5ac6a5eece1..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/retryer.ts +++ /dev/null @@ -1,241 +0,0 @@ -import { isServer as isServerEnvironment } from './environmentManager' -import { focusManager } from './focusManager' -import { onlineManager } from './onlineManager' -import { noop, sleep } from './utils' -import type { - Retryer, - RetryerConfig, - RetryerStatus, -} from '@tanstack/query-types/bindings' -import type { CancelOptions, DefaultError, NetworkMode } from './types' - -/** - * Applies exponential backoff with jitter. The base delay starts at 1 second - * and doubles for each retry, up to 30 seconds. - * @param failureCount - The number of previous failures. Starts at 0 for the first retry. - * @returns A random delay from 80% to 100% of the base delay, in milliseconds. - */ -function defaultRetryDelay(failureCount: number) { - const baseDelay = Math.min(1000 * 2 ** failureCount, 30000) - const maxJitter = baseDelay * 0.2 - return baseDelay - Math.floor(Math.random() * (maxJitter + 1)) -} - -/** - * Checks whether a fetch can run for the given network mode. - * @param networkMode - The `networkMode` option. Defaults to `'online'`. - * @returns `true` if the network mode is not `'online'`, or if it is and the client is online. - */ -export function canFetch(networkMode: NetworkMode | undefined): boolean { - return (networkMode ?? 'online') === 'online' - ? onlineManager.isOnline() - : true -} - -/** - * The error thrown by a `Retryer` (and surfaced to `query.promise`/`mutation`) when a fetch is cancelled, e.g. via - * `query.cancel()`. `revert`, if `true`, tells the caller to restore the state the query was in before the fetch - * started instead of surfacing the error. `silent`, if `true`, tells the caller to suppress this error and instead - * resolve with the promise of the fetch that triggered the cancellation. - * @example - * ```ts - * query.cancel() - * - * try { - * await query.promise - * } catch (error) { - * if (error instanceof CancelledError) { - * // the fetch was cancelled, e.g. via `query.cancel()` - * } - * } - * ``` - */ -export class CancelledError extends Error { - revert?: boolean - silent?: boolean - constructor(options?: CancelOptions) { - super('CancelledError') - this.revert = options?.revert - this.silent = options?.silent - } -} - -/** - * Creates a retryer, which runs a function and retries it on failure according to the `retry` and - * `retryDelay` options. It pauses while the network mode doesn't allow fetching or `canRun` returns - * `false`, and can be cancelled. Queries and mutations use it to run their `queryFn` and - * `mutationFn`. - * @param config - The function to run, the retry options, and the callbacks for failures, pausing, - * continuing, and cancellation. - * @returns The retryer, whose `promise` settles with the result of the function. - */ -export function createRetryer( - config: RetryerConfig, -): Retryer { - let isRetryCancelled = false - let failureCount = 0 - let continueFn: ((value?: unknown) => void) | undefined - let status: RetryerStatus = 'pending' - const { - promise, - resolve: promiseResolve, - reject: promiseReject, - } = Promise.withResolvers() - promise.catch(noop) - - const isResolved = () => status !== 'pending' - - const cancel = (cancelOptions?: CancelOptions): void => { - if (!isResolved()) { - const error = new CancelledError(cancelOptions) as TError - reject(error) - - config.onCancel?.(error) - } - } - const cancelRetry = () => { - isRetryCancelled = true - } - - const continueRetry = () => { - isRetryCancelled = false - } - - const canContinue = () => - focusManager.isFocused() && - (config.networkMode === 'always' || onlineManager.isOnline()) && - config.canRun() - - const canStart = () => canFetch(config.networkMode) && config.canRun() - - const resolve = (value: any) => { - if (!isResolved()) { - continueFn?.() - status = 'resolved' - promiseResolve(value) - } - } - - const reject = (value: any) => { - if (!isResolved()) { - continueFn?.() - status = 'rejected' - promiseReject(value) - } - } - - const pause = (canResume: () => boolean) => { - return new Promise((continueResolve) => { - continueFn = (value) => { - if (isResolved() || canResume()) { - continueResolve(value) - } - } - config.onPause?.() - }).then(() => { - continueFn = undefined - if (!isResolved()) { - config.onContinue?.() - } - }) - } - - // Create loop function - const run = () => { - // Do nothing if already resolved - if (isResolved()) { - return - } - - let promiseOrValue: any - - // we can re-use config.initialPromise on the first call of run() - const initialPromise = - failureCount === 0 ? config.initialPromise : undefined - - // Execute query - try { - promiseOrValue = initialPromise ?? config.fn() - } catch (error) { - promiseOrValue = Promise.reject(error) - } - - Promise.resolve(promiseOrValue) - .then(resolve) - .catch((error) => { - // Stop if the fetch is already resolved - if (isResolved()) { - return - } - - // Do we need to retry the request? - const retry = config.retry ?? (isServerEnvironment() ? 0 : 3) - const retryDelay = config.retryDelay ?? defaultRetryDelay - const delay = - typeof retryDelay === 'function' - ? retryDelay(failureCount, error) - : retryDelay - const shouldRetry = - retry === true || - (typeof retry === 'number' && failureCount < retry) || - (typeof retry === 'function' && retry(failureCount, error)) - - if (isRetryCancelled || !shouldRetry) { - // We are done if the query does not need to be retried - reject(error) - return - } - - failureCount++ - - // Notify on fail - config.onFail?.(failureCount, error) - - // Delay - sleep(delay) - // Pause if the document is not visible or when the device is offline - .then(() => { - return isResolved() || canContinue() - ? undefined - : pause(canContinue) - }) - .then(() => { - if (isRetryCancelled) { - reject(error) - } else { - run() - } - }) - }) - } - - return { - promise, - status: () => status, - cancel, - continue: () => { - continueFn?.() - return promise - }, - cancelRetry, - continueRetry, - canStart, - start: () => { - // Start loop - if (canStart()) { - run() - } else { - // Waiting to start (e.g. queued behind a scope) does not depend on focus, - // only on the same conditions that allow starting in the first place - pause(canStart).then(run) - } - return promise - }, - } -} - -export type { - Retryer, - RetryValue, - RetryDelayValue, -} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts b/packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts deleted file mode 100644 index 6afd2eaf048..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/runtimeBinding.ts +++ /dev/null @@ -1,63 +0,0 @@ -import type { RuntimeBinding } from '@tanstack/query-types/bindings' -import type { Mutation } from './mutation' -import type { MutationCache } from './mutationCache' -import type { MutationObserver } from './mutationObserver' -import type { PlaceholderData, Select } from './projectionTypes' -import type { Query } from './query' -import type { QueryCache } from './queryCache' -import type { QueryClient } from './queryClient' -import type { QueryObserver } from './queryObserver' -import type { RefetchInterval } from './refetchInterval' -import type { SerialScope } from './serialScope' - -/** Binds shared option and callback types to the concrete classes in this runtime. */ -export interface QueryRuntime extends RuntimeBinding { - /** The optional selector implementation carried by a select option. */ - selectFeature: Select[0] - /** The optional placeholder implementation carried by a placeholderData option. */ - placeholderFeature: PlaceholderData[0] - /** Per-mutation queueing behavior, installed with serialScope. */ - mutationScope: SerialScope - /** Polling can be installed independently on each observed query. */ - refetchInterval: - | false - | RefetchInterval - | (( - query: this['Query'], - ) => false | undefined | RefetchInterval) - /** {@inheritDoc RuntimeBinding.QueryClient} */ - QueryClient: QueryClient - /** {@inheritDoc RuntimeBinding.QueryCache} */ - QueryCache: QueryCache - /** {@inheritDoc RuntimeBinding.MutationCache} */ - MutationCache: MutationCache - /** {@inheritDoc RuntimeBinding.Query} */ - Query: Query< - this['queryFnData'], - this['error'], - this['data'], - this['queryKey'][0] - > - /** {@inheritDoc RuntimeBinding.Mutation} */ - Mutation: Mutation< - this['data'], - this['error'], - this['variables'], - this['onMutateResult'] - > - /** {@inheritDoc RuntimeBinding.QueryObserver} */ - QueryObserver: QueryObserver< - this['queryFnData'], - this['error'], - this['data'], - this['queryData'], - this['queryKey'][0] - > - /** {@inheritDoc RuntimeBinding.MutationObserver} */ - MutationObserver: MutationObserver< - this['data'], - this['error'], - this['variables'], - this['onMutateResult'] - > -} diff --git a/packages/react-query-no-core-pluggable/src/runtime/streamedQuery.ts b/packages/react-query-no-core-pluggable/src/runtime/streamedQuery.ts deleted file mode 100644 index 6efb1dbfcdd..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/streamedQuery.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { addConsumeAwareSignal, fetchSignal } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { QueryRuntime } from './runtimeBinding' -import type { OmitKeyof, QueryFunction, QueryKey } from './types' -import type { FetchSignalContext } from './utils' - -type StreamedQueryParams< - TQueryFnData, - TData, - TQueryKey extends QueryKey, -> = Shared.StreamedQueryParams - -/** - * Creates a query function that streams data from an `AsyncIterable`. - * By default, the query collects chunks into an array in the order they arrive. - * If there is no cached data, the first chunk moves the query from `pending` to `success`. - * If the stream ends without producing any chunks, the query uses the cached data or - * the initial value. With a `'replace'` refetch, it uses the initial value. - * The query's `fetchStatus` stays `fetching` while the stream is active. - * Explicit cancellation stops further cache updates, even if `streamFn` does not read `signal`. - * If `streamFn` does not read `signal`, the stream continues after the last observer unsubscribes. - * @param options - The `streamFn` that returns an AsyncIterable to stream data from, and the optional - * `refetchMode`, `reducer`, and `initialValue` options. - * @returns A query function to pass as `queryFn`. - * @example - * ```ts - * await queryClient.query({ - * queryKey: ['data'], - * queryFn: streamedQuery({ - * streamFn: fetchDataInChunks, - * }), - * }) - * ``` - */ -export function streamedQuery< - TQueryFnData = unknown, - TData = Array, - TQueryKey extends QueryKey = QueryKey, ->({ - streamFn, - refetchMode = 'reset', - reducer = (items, chunk) => - [...(items as Array), chunk] as TData, - initialValue = [] as TData, -}: StreamedQueryParams): QueryFunction< - TData, - TQueryKey -> { - return async (context) => { - const signalContext: FetchSignalContext = context - const signal = signalContext[fetchSignal] - if (signal?.aborted) { - return initialValue - } - - const query = context.client - .getQueryCache() - .find({ queryKey: context.queryKey, exact: true }) - const isRefetch = !!query && query.isFetched() - if (isRefetch && refetchMode === 'reset') { - query.setState({ - ...query.resetState, - fetchStatus: 'fetching', - }) - } - - let result = initialValue - - let cancelled = false as boolean - const streamFnContext = addConsumeAwareSignal< - OmitKeyof - >( - { - client: context.client, - meta: context.meta, - queryKey: context.queryKey, - pageParam: context.pageParam, - }, - () => context.signal, - () => (cancelled = true), - signal, - ) - - const isStreamInactive = () => cancelled || signal?.aborted === true - const stream = await streamFn(streamFnContext) - - const isReplaceRefetch = isRefetch && refetchMode === 'replace' - - for await (const chunk of stream) { - if (isStreamInactive()) { - break - } - - if (isReplaceRefetch) { - // don't append to the cache directly when replace-refetching - result = reducer(result, chunk) - } else { - context.client.setQueryData(context.queryKey, (prev) => - reducer(prev === undefined ? initialValue : prev, chunk), - ) - } - } - - // finalize result: replace-refetching needs to write to the cache - if (isReplaceRefetch && !isStreamInactive()) { - context.client.setQueryData(context.queryKey, result) - } - - const data = context.client.getQueryData(context.queryKey) - return data === undefined ? initialValue : data - } -} diff --git a/packages/react-query-no-core-pluggable/src/runtime/subscribable.ts b/packages/react-query-no-core-pluggable/src/runtime/subscribable.ts deleted file mode 100644 index 8b40e3ce868..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/subscribable.ts +++ /dev/null @@ -1,65 +0,0 @@ -/** - * The base class behind everything in Query that you can subscribe to: `QueryCache`, `MutationCache`, - * the observers, and the `FocusManager`/`OnlineManager` behind `focusManager` and `onlineManager`. - * Subclasses decide what a listener receives and when it is called. - */ -export class Subscribable< - // oxlint-disable-next-line typescript/no-unsafe-function-type -- also accepts construct signatures and functions with extra properties, which a call signature would reject - TListener extends Function, -> { - protected listeners = new Set() - - constructor() { - this.subscribe = this.subscribe.bind(this) - } - - /** - * Registers a listener to be called on every update this object notifies about. Returns a function - * that removes the listener again — call it to stop listening. The base class never drops a listener - * on its own, though some subclasses clear all of theirs in `destroy()`. - * @param listener - Called on each update, with whatever the subclass passes to its subscribers. - * @returns A function that removes the listener. - * @example - * ```ts - * const unsubscribe = subscribable.subscribe(() => { - * // react to the update - * }) - * - * unsubscribe() - * ``` - */ - subscribe(listener: TListener): () => void { - this.listeners.add(listener) - - this.onSubscribe() - - return () => { - this.listeners.delete(listener) - this.onUnsubscribe() - } - } - - /** - * Returns `true` while at least one listener is registered, `false` once they have all unsubscribed. - * @returns `true` if at least one listener is registered. - */ - hasListeners(): boolean { - return this.listeners.size > 0 - } - - /** - * Called after a listener is added. Does nothing here; subclasses override it, e.g. to start - * tracking what they observe once the first listener subscribes. - */ - protected onSubscribe(): void { - // Do nothing - } - - /** - * Called after a listener is removed. Does nothing here; subclasses override it, e.g. to clean up - * once the last listener unsubscribes. - */ - protected onUnsubscribe(): void { - // Do nothing - } -} diff --git a/packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts b/packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts deleted file mode 100644 index 7bfa05ebc45..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/timeoutManager.ts +++ /dev/null @@ -1,211 +0,0 @@ -import type { - ManagedTimerId, - SystemTimerId, - TimeoutCallback, - TimeoutProvider, -} from '@tanstack/query-types/bindings' - -export const defaultTimeoutProvider: TimeoutProvider = { - // We need the wrapper function syntax below instead of direct references to - // global setTimeout etc. - // - // BAD: `setTimeout: setTimeout` - // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)` - // - // If we use direct references here, then anything that wants to spy on or - // replace the global setTimeout (like tests) won't work since we'll already - // have a hard reference to the original implementation at the time when this - // file was imported. - setTimeout: (callback, delay) => setTimeout(callback, delay), - clearTimeout: (timeoutId) => - clearTimeout(timeoutId as SystemTimerId | undefined), - - setInterval: (callback, delay) => setInterval(callback, delay), - clearInterval: (intervalId) => - clearInterval(intervalId as SystemTimerId | undefined), -} - -/** - * Allows customization of how timeouts are created. - * - * The query runtime uses timeouts to implement `staleTime` - * and `gcTime`. The default TimeoutManager provider uses the platform's global - * `setTimeout` implementation, which is known to have scalability issues with - * thousands of timeouts on the event loop. - * - * If you hit this limitation, consider providing a custom TimeoutProvider that - * coalesces timeouts. - */ -export class TimeoutManager implements Omit { - // We cannot have TimeoutManager as we must instantiate it with a concrete - // type at app boot; and if we leave that type, then any new timer provider - // would need to support the default provider's concrete timer ID, which is - // infeasible across environments. - // - // We settle for type safety for the TimeoutProvider type, and accept that - // this class is unsafe internally to allow for extension. - #provider: TimeoutProvider = defaultTimeoutProvider - #providerCalled = false - - /** - * `setTimeoutProvider` can be used to set a custom implementation of the - * `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval` functions, - * called a `TimeoutProvider`. - * - * This may be useful if you notice event loop performance issues with - * thousands of queries. A custom TimeoutProvider could also support timer - * delays longer than the global `setTimeout` maximum delay value of about - * 24 days. - * - * It is important to call `setTimeoutProvider` before creating a - * QueryClient or queries, so that the same provider is used consistently - * for all timers in the application, since different TimeoutProviders - * cannot cancel each others' timers. - * @param provider - The `TimeoutProvider` to use for all timers from now on. - * @example - * ```ts - * import { timeoutManager, QueryClient } from '@tanstack/react-query-no-core-pluggable' - * import { CustomTimeoutProvider } from './CustomTimeoutProvider' - * - * timeoutManager.setTimeoutProvider(new CustomTimeoutProvider()) - * - * export const queryClient = new QueryClient() - * ``` - */ - setTimeoutProvider( - provider: TimeoutProvider, - ): void { - if (process.env.NODE_ENV !== 'production') { - if (this.#providerCalled && provider !== this.#provider) { - // After changing providers, `clearTimeout` will not work as expected for - // timeouts from the previous provider. - // - // Since they may allocate the same timeout ID, clearTimeout may cancel an - // arbitrary different timeout, or unexpected no-op. - // - // We could protect against this by mixing the timeout ID bits - // deterministically with some per-provider bits. - // - // We could internally queue `setTimeout` calls to `TimeoutManager` until - // some API call to set the initial provider. - console.error( - `[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`, - { previous: this.#provider, provider }, - ) - } - } - - this.#provider = provider - if (process.env.NODE_ENV !== 'production') { - this.#providerCalled = false - } - } - - /** - * `setTimeout` schedules a callback to run after approximately `delay` - * milliseconds, like the global `setTimeout` function. The callback can be - * canceled with `clearTimeout`. - * - * It returns a timer ID, which may be a number or an object that can be - * coerced to a number via `Symbol.toPrimitive`. - * @param callback - The function to call when the timeout elapses. - * @param delay - The time to wait before calling `callback`, in milliseconds. - * @returns The timer ID, to pass to {@link TimeoutManager#clearTimeout}. - * @example - * ```ts - * import { timeoutManager } from '@tanstack/react-query-no-core-pluggable' - * - * const timeoutId = timeoutManager.setTimeout( - * () => console.log('ran at:', new Date()), - * 1000, - * ) - * - * const timeoutIdNumber: number = Number(timeoutId) - * ``` - */ - setTimeout(callback: TimeoutCallback, delay: number): ManagedTimerId { - if (process.env.NODE_ENV !== 'production') { - this.#providerCalled = true - } - return this.#provider.setTimeout(callback, delay) - } - - /** - * `clearTimeout` cancels a timeout callback scheduled with `setTimeout`, - * like the global `clearTimeout` function. It should be called with a - * timer ID returned by `setTimeout`. - * @param timeoutId - The timer ID returned by `setTimeout`, or `undefined`. - * @example - * ```ts - * import { timeoutManager } from '@tanstack/react-query-no-core-pluggable' - * - * const timeoutId = timeoutManager.setTimeout( - * () => console.log('ran at:', new Date()), - * 1000, - * ) - * - * timeoutManager.clearTimeout(timeoutId) - * ``` - */ - clearTimeout(timeoutId: ManagedTimerId | undefined): void { - this.#provider.clearTimeout(timeoutId) - } - - /** - * `setInterval` schedules a callback to be called approximately every - * `delay` milliseconds, like the global `setInterval` function. - * - * Like `setTimeout`, it returns a timer ID, which may be a number or an - * object that can be coerced to a number via `Symbol.toPrimitive`. - * @param callback - The function to call on every interval. - * @param delay - The time between calls, in milliseconds. - * @returns The timer ID, to pass to {@link TimeoutManager#clearInterval}. - * @example - * ```ts - * import { timeoutManager } from '@tanstack/react-query-no-core-pluggable' - * - * const intervalId = timeoutManager.setInterval( - * () => console.log('ran at:', new Date()), - * 1000, - * ) - * ``` - */ - setInterval(callback: TimeoutCallback, delay: number): ManagedTimerId { - if (process.env.NODE_ENV !== 'production') { - this.#providerCalled = true - } - return this.#provider.setInterval(callback, delay) - } - - /** - * `clearInterval` can be used to cancel an interval, like the global - * `clearInterval` function. It should be called with an interval ID - * returned by `setInterval`. - * @param intervalId - The timer ID returned by `setInterval`, or `undefined`. - * @example - * ```ts - * import { timeoutManager } from '@tanstack/react-query-no-core-pluggable' - * - * const intervalId = timeoutManager.setInterval( - * () => console.log('ran at:', new Date()), - * 1000, - * ) - * - * timeoutManager.clearInterval(intervalId) - * ``` - */ - clearInterval(intervalId: ManagedTimerId | undefined): void { - this.#provider.clearInterval(intervalId) - } -} - -/** - * Singleton instance of {@link TimeoutManager}, used throughout TanStack Query to schedule and cancel timers. - */ -export const timeoutManager = /* #__PURE__ */ new TimeoutManager() - -export type { - TimeoutCallback, - ManagedTimerId, - TimeoutProvider, -} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core-pluggable/src/runtime/types.ts b/packages/react-query-no-core-pluggable/src/runtime/types.ts deleted file mode 100644 index df37aeba7d3..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/types.ts +++ /dev/null @@ -1,450 +0,0 @@ -import type * as Shared from '@tanstack/query-types/bindings' -import type { - DefaultError, - InfiniteData, - QueryKey, -} from '@tanstack/query-types/bindings' -import type { QueryRuntime } from './runtimeBinding' - -export const dataTagSymbol: Shared.dataTagSymbol = Symbol.for( - '@tanstack/query/dataTagSymbol', -) as Shared.dataTagSymbol -/** - * The type of the `dataTagSymbol` key, under which a {@link DataTag} stores its data type. - */ -export type dataTagSymbol = typeof dataTagSymbol -export const dataTagErrorSymbol: Shared.dataTagErrorSymbol = Symbol.for( - '@tanstack/query/dataTagErrorSymbol', -) as Shared.dataTagErrorSymbol -/** - * The type of the `dataTagErrorSymbol` key, under which a {@link DataTag} stores its error type. - */ -export type dataTagErrorSymbol = typeof dataTagErrorSymbol -export const unsetMarker: Shared.UnsetMarker = Symbol.for( - '@tanstack/query/unsetMarker', -) as Shared.UnsetMarker - -/** {@inheritDoc Shared.QueryFunction} */ -export type QueryFunction< - T = unknown, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.QueryFunction - -/** {@inheritDoc Shared.StaleTimeFunction} */ -export type StaleTimeFunction< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = Shared.StaleTimeFunction< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey -> - -/** {@inheritDoc Shared.QueryBooleanOption} */ -export type QueryBooleanOption< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = Shared.QueryBooleanOption< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey -> - -/** {@inheritDoc Shared.QueryPersister} */ -export type QueryPersister< - T = unknown, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.QueryPersister - -/** {@inheritDoc Shared.QueryFunctionContext} */ -export type QueryFunctionContext< - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.QueryFunctionContext - -// oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes every function-like value, including constructors, from the value branch - -/** {@inheritDoc Shared.PlaceholderDataFunction} */ -export type PlaceholderDataFunction< - TQueryFnData = unknown, - TError = DefaultError, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = Shared.PlaceholderDataFunction< - QueryRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey -> - -/** {@inheritDoc Shared.QueryOptions} */ -export type QueryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.QueryOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.ThrowOnError} */ -export type ThrowOnError< - TQueryFnData, - TError, - TQueryData, - TQueryKey extends QueryKey, -> = Shared.ThrowOnError< - QueryRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey -> - -/** {@inheritDoc Shared.QueryObserverOptionsBase} */ -export type QueryObserverOptionsBase< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.QueryObserverOptionsBase< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.QueryObserverOptions} */ -export type QueryObserverOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.QueryObserverOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.DefaultedQueryObserverOptions} */ -export type DefaultedQueryObserverOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.DefaultedQueryObserverOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.InfiniteQueryObserverOptions} */ -export type InfiniteQueryObserverOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> = Shared.InfiniteQueryObserverOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.DefaultedInfiniteQueryObserverOptions} */ -export type DefaultedInfiniteQueryObserverOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> = Shared.DefaultedInfiniteQueryObserverOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.QueryExecuteOptions} */ -export type QueryExecuteOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.QueryExecuteOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.InfiniteQueryExecuteOptions} */ -export type InfiniteQueryExecuteOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> = Shared.InfiniteQueryExecuteOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.InvalidateQueryFilters} */ -export type InvalidateQueryFilters = - Shared.InvalidateQueryFilters - -/** {@inheritDoc Shared.RefetchQueryFilters} */ -export type RefetchQueryFilters = - Shared.RefetchQueryFilters - -/** {@inheritDoc Shared.MutationFunctionContext} */ -export type MutationFunctionContext = - Shared.MutationFunctionContext - -/** {@inheritDoc Shared.MutationFunction} */ -export type MutationFunction< - TData = unknown, - TVariables = unknown, -> = Shared.MutationFunction - -/** {@inheritDoc Shared.MutationOptions} */ -export type MutationOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationOptions< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutationObserverOptions} */ -export type MutationObserverOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationObserverOptions< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutateOptions} */ -export type MutateOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutateOptions< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutateFunctionRest} */ -export type MutateFunctionRest< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutateFunctionRest< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutateFunction} */ -export type MutateFunction< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutateFunction< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutationObserverBaseResult} */ -export type MutationObserverBaseResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationObserverBaseResult< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutationObserverIdleResult} */ -export type MutationObserverIdleResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationObserverIdleResult< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutationObserverLoadingResult} */ -export type MutationObserverLoadingResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationObserverLoadingResult< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutationObserverErrorResult} */ -export type MutationObserverErrorResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationObserverErrorResult< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutationObserverSuccessResult} */ -export type MutationObserverSuccessResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationObserverSuccessResult< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutationObserverResult} */ -export type MutationObserverResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationObserverResult< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.QueryClientConfig} */ -export type QueryClientConfig = Shared.QueryClientConfig - -/** {@inheritDoc Shared.DefaultOptions} */ -export type DefaultOptions = Shared.DefaultOptions< - QueryRuntime, - TError -> - -export type { - OmitKeyof, - DefaultError, - QueryKey, - InferDataFromTag, - InferErrorFromTag, - StaleTime, - InitialDataFunction, - EqualityFn, - CacheKeyConfig, - InfiniteData, - QueryMeta, - NetworkMode, - InfiniteQueryPageParamsOptions, - WithRequired, - RefetchOptions, - InvalidateOptions, - ResetOptions, - FetchNextPageOptions, - FetchPreviousPageOptions, - QueryObserverBaseResult, - QueryObserverResult, - InfiniteQueryObserverBaseResult, - InfiniteQueryObserverResult, - MutationKey, - MutationMeta, - CancelOptions, - SetDataOptions, -} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core-pluggable/src/runtime/utils.ts b/packages/react-query-no-core-pluggable/src/runtime/utils.ts deleted file mode 100644 index 9d3c33c7bbf..00000000000 --- a/packages/react-query-no-core-pluggable/src/runtime/utils.ts +++ /dev/null @@ -1,746 +0,0 @@ -import { identity } from './identity' -import { timeoutManager } from './timeoutManager' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - DefaultQueryFn, - SkipToken, - Updater, -} from '@tanstack/query-types/bindings' -import type { Mutation } from './mutation' -import type { FetchOptions, Query } from './query' -import type { QueryRuntime } from './runtimeBinding' -import type { - CacheKeyConfig, - DefaultError, - EqualityFn, - MutationKey, - QueryFunction, - QueryKey, - QueryOptions, -} from './types' - -/** {@inheritDoc Shared.QueryFilters} */ -export type QueryFilters = - Shared.QueryFilters - -/** {@inheritDoc Shared.MutationFilters} */ -export type MutationFilters< - TData = unknown, - TError = DefaultError, - TVariables = unknown, - TOnMutateResult = unknown, -> = Shared.MutationFilters< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -// UTILS - -/** - * A function that does nothing. - */ -export function noop(): void -export function noop(): undefined -export function noop() {} - -/** - * Resolves an {@link Updater}: calls it with `input` if it is a function, otherwise returns it as - * is. - * @param updater - The new value, or a function that receives `input` and returns the new value. - * @param input - The current value, passed to `updater` if it is a function. - * @returns The new value. - */ -export function functionalUpdate( - updater: Updater, - input: TInput, -): TOutput { - return typeof updater === 'function' - ? (updater as (_: TInput) => TOutput)(input) - : updater -} - -/** - * Checks whether a value can be used as a timeout: a non-negative, finite number. - * @param value - The value to check. - * @returns `true` if `value` is a number that is `>= 0` and not `Infinity`. - */ -export function isValidTimeout(value: unknown): value is number { - return typeof value === 'number' && value >= 0 && value !== Infinity -} - -/** - * Calculates how long until data updated at `updatedAt` becomes stale. - * @param updatedAt - The timestamp, in milliseconds, at which the data was last updated. - * @param staleTime - The time, in milliseconds, after which data is considered stale. Defaults to - * `0`. - * @returns The remaining time in milliseconds, or `0` if the data is already stale. - */ -export function timeUntilStale(updatedAt: number, staleTime?: number): number { - return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0) -} - -/** - * Resolves an option that can be given either as a value or as a function of the query, such as - * `staleTime`. - * @param value - The option value, or a function that receives `query` and returns the value. - * @param query - The query passed to `value` if it is a function. - * @returns The resolved value, or `undefined` if `value` is `undefined`. - */ -export function resolveQueryValue< - TValue, - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - value: - | undefined - | TValue - | ((query: Query) => TValue), - query: Query, -): TValue | undefined { - return typeof value === 'function' - ? ( - value as ( - query: Query, - ) => TValue - )(query) - : value -} - -/** - * Checks whether a query matches the given {@link QueryFilters}. - * Every filter that is specified must match; filters that are left unspecified are ignored. - * @param filters - The filters to check the query against. - * @param query - The query to check. - * @param keyConfig - The cache configuration for key comparison and hashing. - * @returns `true` if the query matches every specified filter. - * @example - * ```ts - * const queryCache = queryClient.getQueryCache() - * - * const matchingQueries = queryCache - * .getAll() - * .filter((query) => matchQuery({ queryKey: ['posts'] }, query)) - * ``` - */ -export function matchQuery( - filters: QueryFilters, - query: Query, - keyConfig?: CacheKeyConfig, -): boolean { - const { - type = 'all', - exact, - fetchStatus, - predicate, - queryKey, - stale, - } = filters - - if (queryKey) { - if (exact) { - if (query.queryHash !== hashKeyByOptions(queryKey, keyConfig)) { - return false - } - } else if ( - !partialMatchKey(query.queryKey, queryKey, keyConfig?.equalityFn) - ) { - return false - } - } - - if (type !== 'all') { - const isActive = query.isActive() - if (type === 'active' && !isActive) { - return false - } - if (type === 'inactive' && isActive) { - return false - } - } - - if (typeof stale === 'boolean' && query.isStale() !== stale) { - return false - } - - if (fetchStatus && fetchStatus !== query.state.fetchStatus) { - return false - } - - if (predicate && !predicate(query)) { - return false - } - - return true -} - -/** - * Checks whether a mutation matches the given {@link MutationFilters}. - * Every filter that is specified must match; filters that are left unspecified are ignored. - * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match. - * @param filters - The filters to check the mutation against. - * @param mutation - The mutation to check. - * @param keyConfig - The cache configuration for key comparison and hashing. - * @returns `true` if the mutation matches every specified filter. - * @example - * ```ts - * const mutationCache = getMutationCache(queryClient) - * - * const matchingMutations = mutationCache - * .getAll() - * .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation)) - * ``` - */ -export function matchMutation( - filters: MutationFilters, - mutation: Mutation, - keyConfig?: CacheKeyConfig, -): boolean { - const { exact, status, predicate, mutationKey } = filters - if (mutationKey) { - if (!mutation.options.mutationKey) { - return false - } - if (exact) { - if ( - hashKeyByOptions(mutation.options.mutationKey, keyConfig) !== - hashKeyByOptions(mutationKey, keyConfig) - ) { - return false - } - } else if ( - !partialMatchKey( - mutation.options.mutationKey, - mutationKey, - keyConfig?.equalityFn, - ) - ) { - return false - } - } - - if (status && mutation.state.status !== status) { - return false - } - - if (predicate && !predicate(mutation)) { - return false - } - - return true -} - -/** - * Hashes a cache key with the cache's `hashFn`, falling back to {@link hashKey}. - * @param cacheKey - The query or mutation key to hash. - * @param keyConfig - The cache configuration that may provide a custom `hashFn`. - * @returns The hash, a string that identifies the key in the cache. - */ -export function hashKeyByOptions< - TCacheKey extends ReadonlyArray = ReadonlyArray, ->( - cacheKey: TCacheKey, - keyConfig: CacheKeyConfig | undefined, -): string { - const hashFn = keyConfig?.hashFn ?? hashKey - return hashFn(cacheKey) -} - -/** - * Default query & mutation keys hash function. - * Hashes the value into a stable hash. - * @param queryKey - The query or mutation key to hash. - * @returns The stable hash of the key, as a JSON string. - * @example - * ```ts - * // Object keys are sorted, so key order doesn't affect the hash: - * hashKey(['todos', { page: 1, filter: 'done' }]) // === '["todos",{"filter":"done","page":1}]' - * ``` - */ -export function hashKey(queryKey: QueryKey | MutationKey): string { - return JSON.stringify(queryKey, (_, val) => - isPlainObject(val) - ? Object.keys(val) - .sort() - .reduce((result, key) => { - result[key] = val[key] - return result - }, {} as any) - : val, - ) -} - -const defaultEqualityFn: EqualityFn = (a, b) => a === b - -/** - * Checks if key `b` partially matches with key `a`. - * @param a - The key to check, e.g. a query's own key. - * @param b - The (partial) key to match against `a`. - * @param equalityFn - Compares individual key values. Defaults to strict equality. - * @returns `true` if every array element or object property in `b` matches the one at the same - * position in `a`. - */ -export function partialMatchKey( - a: QueryKey, - b: QueryKey, - equalityFn?: EqualityFn, -): boolean -export function partialMatchKey( - a: unknown, - b: unknown, - equalityFn?: EqualityFn, -): boolean -export function partialMatchKey( - a: any, - b: any, - equalityFn: EqualityFn = defaultEqualityFn, -): boolean { - if (equalityFn(a, b)) { - return true - } - - if (typeof a !== typeof b) { - return false - } - - if (isPlainArray(a) && isPlainArray(b)) { - if (b.length > a.length) return false - for (let i = 0; i < b.length; i++) { - if (!partialMatchKey(a[i], b[i], equalityFn)) { - return false - } - } - return true - } - - if (isPlainObject(a) && isPlainObject(b)) { - const bKeys = Object.keys(b) - for (const key of bKeys) { - if (!partialMatchKey(a[key], b[key], equalityFn)) { - return false - } - } - return true - } - - return false -} - -/** - * This function returns `a` if `b` is deeply equal. - * If not, it will replace any deeply equal children of `b` with those of `a`. - * This can be used for structural sharing between JSON values for example. - * An optional equality function can be used for custom value types. - * @param a - The previous value, whose deeply equal parts are reused. - * @param b - The new value. - * @param equalityFn - Compares values for structural sharing. Defaults to strict equality. - * @returns `a` if `b` is deeply equal to it, otherwise `b` with its deeply equal parts replaced by - * those of `a`. - */ -export function replaceEqualDeep( - a: unknown, - b: T, - equalityFn?: EqualityFn, -): T -export function replaceEqualDeep( - a: any, - b: any, - equalityFn: EqualityFn = defaultEqualityFn, -): any { - return replaceEqualDeepInternal(a, b, equalityFn, 0) -} - -/** - * Reuses deeply equal values while limiting recursion to 500 levels. - * @param a - The previous value. - * @param b - The new value. - * @param equalityFn - Compares values for structural sharing. - * @param depth - The current recursion depth. - * @returns The new value with deeply equal parts of the previous value reused. - */ -function replaceEqualDeepInternal( - a: any, - b: any, - equalityFn: EqualityFn, - depth: number, -): any { - if (equalityFn(a, b)) { - return a - } - - if (depth > 500) return b - - const array = isPlainArray(a) && isPlainArray(b) - - if (!array && !(isPlainObject(a) && isPlainObject(b))) return b - - const aItems = array ? a : Object.keys(a) - const aSize = aItems.length - const bItems = array ? b : Object.keys(b) - const bSize = bItems.length - const copy: any = array ? new Array(bSize) : {} - - let equalItems = 0 - - for (let i = 0; i < bSize; i++) { - const key: any = array ? i : bItems[i] - const aItem = a[key] - const bItem = b[key] - - if (equalityFn(aItem, bItem)) { - copy[key] = aItem - if (array ? i < aSize : Object.hasOwn(a, key)) equalItems++ - continue - } - - if ( - aItem === null || - bItem === null || - typeof aItem !== 'object' || - typeof bItem !== 'object' - ) { - copy[key] = bItem - continue - } - - const v = replaceEqualDeepInternal(aItem, bItem, equalityFn, depth + 1) - copy[key] = v - if (v === aItem) equalItems++ - } - - return aSize === bSize && equalItems === aSize ? a : copy -} - -/** - * Shallow compare objects. - * @param a - The first object. - * @param b - The second object, or `undefined`. - * @returns `true` if both objects have the same keys, with strictly equal values for each key. - */ -export function shallowEqualObjects>( - a: T, - b: T | undefined, -): boolean { - if (!b || Object.keys(a).length !== Object.keys(b).length) { - return false - } - - for (const key of Object.keys(a)) { - if (!Object.hasOwn(b, key) || a[key] !== b[key]) { - return false - } - } - - return true -} - -/** - * Checks whether a value is an array with no holes and no extra properties. - * @param value - The value to check. - * @returns `true` if `value` is an array whose number of own keys equals its `length`. - */ -export function isPlainArray(value: unknown): value is Array { - return Array.isArray(value) && value.length === Object.keys(value).length -} - -// Copied from: https://github.com/jonschlinkert/is-plain-object -/** - * Checks whether a value is a plain object, e.g. created with an object literal or - * `Object.create(null)`. - * @param o - The value to check. - * @returns `true` if `o` is a plain object. - */ -export function isPlainObject(o: any): o is Record { - if (!hasObjectPrototype(o)) { - return false - } - - // If has no constructor - const objectPrototype = Object.getPrototypeOf(o) - const ctor = objectPrototype?.constructor - if (ctor === undefined) { - return true - } - - if (typeof ctor !== 'function') { - return false - } - - // If has modified prototype - const prot = ctor.prototype - if (!hasObjectPrototype(prot)) { - return false - } - - // If constructor does not have an Object-specific method - if (!prot.hasOwnProperty('isPrototypeOf')) { - return false - } - - // Handles Objects created by Object.create() - if (objectPrototype !== Object.prototype) { - return false - } - - // Most likely a plain Object - return true -} - -/** - * Checks whether a value's `Object.prototype.toString` tag is `[object Object]`. - * @param o - The value to check. - * @returns `true` if the tag is `[object Object]`. - */ -function hasObjectPrototype(o: any): boolean { - return Object.prototype.toString.call(o) === '[object Object]' -} - -/** - * Waits for the given time, using the configured {@link timeoutManager}. - * @param timeout - The time to wait, in milliseconds. - * @returns A promise that resolves after `timeout` milliseconds. - */ -export function sleep(timeout: number): Promise { - return new Promise((resolve) => { - timeoutManager.setTimeout(resolve, timeout) - }) -} - -/** - * Applies a query's `structuralSharing` option when writing new data. - * @param prevData - The previously cached data. - * @param data - The new data. - * @param options - The query options, whose `structuralSharing` decides how the data is merged. - * @returns The result of a custom `structuralSharing` function, `data` with its unchanged parts - * replaced by those of `prevData` by default, or `data` as is if `structuralSharing` is `false`. - * @throws {Error} The error from the default structural sharing, e.g. when the data is not JSON serializable. - * Outside production, it is also logged to the console. - */ -export function replaceData< - TData, - TOptions extends QueryOptions, ->(prevData: TData | undefined, data: TData, options: TOptions): TData { - if (typeof options.structuralSharing === 'function') { - return options.structuralSharing(prevData, data) as TData - } else if (options.structuralSharing !== false) { - if (process.env.NODE_ENV !== 'production') { - try { - return replaceEqualDeep(prevData, data) - } catch (error) { - console.error( - `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`, - ) - - // Prevent the replaceEqualDeep from being called again down below. - throw error - } - } - // Structurally share data between prev and new data if needed - return replaceEqualDeep(prevData, data) - } - return data -} - -/** - * Intended to be passed as a query's `placeholderData` option, for example - * `placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new - * query key is fetching, it keeps displaying the previously fetched data until the new data arrives. - * @param previousData - The data of the previous query key, passed by the observer. - * @returns The previous data, unchanged. - * @example - * ```ts - * new QueryObserver(queryClient, { - * queryKey: ['posts', page], - * queryFn: () => fetchPosts(page), - * placeholderData: keepPreviousData, - * }) - * ``` - */ -export const keepPreviousData: ( - previousData: T | undefined, -) => T | undefined = identity - -/** - * Adds an item to one end of a new array. If the result exceeds `max`, removes - * excess items from the opposite end. - * @param items - The current items. - * @param item - The value to add. - * @param max - The maximum number of items to keep. Omit it or use `0` for no limit. - * @param prepend - Pass `true` to add at the start. The default is to add at the end. - * @returns A new array with `item` added. - */ -export function addToArray( - items: Array, - item: T, - max?: number, - prepend?: boolean, -): Array { - const newItems = prepend ? [item, ...items] : [...items, item] - if (max && newItems.length > max) { - return prepend ? newItems.slice(0, max) : newItems.slice(-max) - } - return newItems -} - -/** - * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent - * to `enabled: false`) while preserving full type inference for the query's data. Unlike `enabled: false`, - * a query disabled via `skipToken` cannot be triggered with `refetch`. - * @example - * ```ts - * new QueryObserver(queryClient, { - * queryKey: ['post', postId], - * queryFn: postId != null ? () => fetchPost(postId) : skipToken, - * }) - * ``` - */ -export const skipToken: SkipToken = Symbol.for( - '@tanstack/query/skipToken', -) as SkipToken - -/** - * Pass this as `queryFn` to use the query function configured on the client. - * The defaults for the query key take precedence over the client's global query defaults. - * If no query function is configured, a fetch fails with a `Missing queryFn` error. - */ -export const defaultQueryFn: DefaultQueryFn = Symbol.for( - '@tanstack/query/defaultQueryFn', -) as DefaultQueryFn - -/** - * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from - * an `initialPromise`, that promise is returned instead. If there is no usable `queryFn`, the returned - * function rejects with a `Missing queryFn` error. - * @param options - The query options with the `queryFn`, and the `queryHash` used in error messages. - * @param fetchOptions - The fetch options, which may carry an `initialPromise`. - * @returns The function to call for the fetch. - */ -export function ensureQueryFn< - TQueryFnData = unknown, - TQueryKey extends QueryKey = QueryKey, ->( - options: { - queryFn?: - | QueryFunction - | SkipToken - | DefaultQueryFn - queryHash?: string - }, - fetchOptions?: FetchOptions, -): QueryFunction { - if (process.env.NODE_ENV !== 'production') { - if (options.queryFn === skipToken) { - console.error( - `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`, - ) - } - } - - // if we attempt to retry a fetch that was triggered from an initialPromise - // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise - // if an observer has already mounted, we will be able to retry with that queryFn - if (!options.queryFn && fetchOptions?.initialPromise) { - return () => fetchOptions.initialPromise! - } - - if ( - !options.queryFn || - options.queryFn === skipToken || - options.queryFn === defaultQueryFn - ) { - return () => - Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`)) - } - - return options.queryFn -} - -/** - * Resolves a `throwOnError` option to a boolean. - * If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller, - * additional context such as the query or mutation) and its result is returned, allowing the throwing - * behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined` - * resolves to `false`). - * @param throwOnError - The `throwOnError` option: a boolean, a function that decides per error, or - * `undefined`. - * @param params - The arguments passed to `throwOnError` if it is a function. - * @returns Whether the error should be thrown. - * @example - * ```ts - * const throwOnError = - * query.state.error && typeof options.throwOnError === 'function' - * ? shouldThrowError(options.throwOnError, [query.state.error, query]) - * : options.throwOnError - * ``` - */ -export function shouldThrowError) => boolean>( - throwOnError: boolean | T | undefined, - params: Parameters, -): boolean { - // Allow throwOnError function to override throwing behavior on a per-error basis - if (typeof throwOnError === 'function') { - return throwOnError(...params) - } - - return !!throwOnError -} - -export const fetchSignal: Shared.FetchSignal = Symbol.for( - '@tanstack/query/fetchSignal', -) as Shared.FetchSignal - -/** - * Adds a lazy `signal` getter to an object, such as a query function context. The first time - * `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right - * away if it is already aborted), so cancellation is only tracked when the signal is actually used. - * @param object - The object to add the `signal` property to. - * @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read. - * @param onCancelled - Called when the signal is aborted, if `signal` was read. - * @param internalSignal - The fetch signal to forward without consuming the getter. - * @returns The same object, with the `signal` property added. - */ -export function addConsumeAwareSignal( - object: T, - getSignal: () => AbortSignal, - onCancelled: () => void, - internalSignal?: AbortSignal, -): T & { signal: AbortSignal } { - let consumed = false - let signal: AbortSignal | undefined - - Object.defineProperties(object, { - [fetchSignal]: { value: internalSignal }, - signal: { - enumerable: true, - get: () => { - signal ??= getSignal() - if (consumed) { - return signal - } - - consumed = true - if (signal.aborted) { - onCancelled() - } else { - signal.addEventListener('abort', onCancelled, { once: true }) - } - - return signal - }, - }, - }) - - return object as T & { signal: AbortSignal } -} - -export type { - Updater, - QueryTypeFilter, - SkipToken, - DefaultQueryFn, - FetchSignalContext, -} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core-pluggable/src/suspense.ts b/packages/react-query-no-core-pluggable/src/suspense.ts deleted file mode 100644 index 09ff0957953..00000000000 --- a/packages/react-query-no-core-pluggable/src/suspense.ts +++ /dev/null @@ -1,214 +0,0 @@ -import { use } from 'react' -import { QueryObserver } from './runtime/queryObserver' -import type { - DefaultError, - QueryKey, - QueryObserverResult, -} from '@tanstack/query-types/bindings' -import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' -import type { Query } from './runtime/query' -import type { QueryClient } from './runtime/queryClient' -import type { DefaultedQueryObserverOptions } from './runtime/types' - -type SuspensePromiseEntry = { - fetchPromise: Promise - promise: Promise - settled: boolean -} - -const suspensePromiseCache = new WeakMap< - Query, - SuspensePromiseEntry ->() - -/** - * Uses the nearest error boundary when the query has no data to show. - * @param _error - The query error. - * @param query - The query that failed. - * @returns Whether the query has no data. - */ -export const defaultThrowOnError = < - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - _error: TError, - query: Query, -) => query.state.data === undefined - -/** - * Raises `staleTime` and a numeric `gcTime` to at least 1000ms when `suspense` is enabled, so a - * component that remounts after suspending doesn't refetch right away or find the query garbage - * collected. A `'static'` `staleTime` is kept as is. Mutates the options. - * @param defaultedOptions - The defaulted query options to adjust. - */ -export const ensureSuspenseTimers = ( - defaultedOptions: DefaultedQueryObserverOptions, -) => { - if (defaultedOptions.suspense) { - // Handle staleTime to ensure minimum 1000ms in Suspense mode - // This prevents unnecessary refetching when components remount after suspending - const MIN_SUSPENSE_TIME_MS = 1000 - - const clamp = (value: number | 'static' | undefined) => - value === 'static' - ? value - : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS) - - const originalStaleTime = defaultedOptions.staleTime - defaultedOptions.staleTime = - typeof originalStaleTime === 'function' - ? (...args) => clamp(originalStaleTime(...args)) - : clamp(originalStaleTime) - - if (typeof defaultedOptions.gcTime === 'number') { - defaultedOptions.gcTime = Math.max( - defaultedOptions.gcTime, - MIN_SUSPENSE_TIME_MS, - ) - } - } -} - -/** - * Decides whether a Suspense query needs to fetch during render. - * @param result - The result for this render. - * @param errorResetBoundary - The nearest query error reset boundary. - * @param query - The query to fetch. - * @returns `undefined` to skip the fetch, `false` to fetch in the background, or `true` to suspend. - */ -const shouldSuspend = ( - result: QueryObserverResult, - errorResetBoundary: QueryErrorResetBoundaryValue, - query: Query, -): boolean | undefined => { - if ( - result.isPending || - (query.state.status === 'error' && errorResetBoundary.isReset()) - ) { - return true - } - - if (result.isFetching && result.isPlaceholderData) { - return false - } - - return undefined -} - -/** - * Starts a fetch during render or reuses a promise for an existing fetch. - * @param defaultedOptions - The options of the query. - * @param observer - The observer that starts the fetch. - * @param errorResetBoundary - The nearest query error reset boundary. - * @param query - The query used to key the promise cache. - * @returns A promise that resolves when the fetch settles. - */ -export function getSuspensePromise( - defaultedOptions: DefaultedQueryObserverOptions, - observer: QueryObserver, - errorResetBoundary: QueryErrorResetBoundaryValue, - query: Query, -): Promise { - let entry = suspensePromiseCache.get(query) - if (!entry || entry.settled) { - const fetchPromise = observer.fetchOptimistic(defaultedOptions) - const settle = () => { - pending.settled = true - } - const pending: SuspensePromiseEntry = { - fetchPromise, - // Retry the render when the fetch settles, even on failure. - promise: fetchPromise.then(settle, settle), - settled: false, - } - suspensePromiseCache.set(query, pending) - entry = pending - } - - entry.fetchPromise.catch(() => errorResetBoundary.clearReset()) - return entry.promise -} - -type SuspenseOptions = DefaultedQueryObserverOptions -type SuspenseResult = QueryObserverResult -type SnapshotReader = { getSnapshot: () => T } - -const useReadSuspenseQuery = ( - defaultedOptions: SuspenseOptions, - reader: SnapshotReader, - observer: QueryObserver, - client: QueryClient, - errorResetBoundary: QueryErrorResetBoundaryValue, -) => { - if (!defaultedOptions.suspense) return - - const snapshot = reader.getSnapshot() - const query = client.getQueryCache().build(client, defaultedOptions) - const suspend = shouldSuspend(snapshot, errorResetBoundary, query) - if (suspend === undefined) return - - const promise = getSuspensePromise( - defaultedOptions, - observer, - errorResetBoundary, - query, - ) - if (suspend) { - use(promise) - } -} - -/** Supplies Suspense behavior for one query. */ -export const suspenseQueryPolicy = { - prepare: ensureSuspenseTimers, - readQuery: useReadSuspenseQuery, -} - -const useReadSuspenseQueries = ( - defaultedQueries: Array, - reader: SnapshotReader>, - client: QueryClient, - errorResetBoundary: QueryErrorResetBoundaryValue, -) => { - const snapshot = reader.getSnapshot() - - const suspensePromises = snapshot.map((result, index) => { - const opts = defaultedQueries[index] - - if (!opts?.suspense) { - return undefined - } - - const query = client.getQueryCache().build(client, opts) - const suspend = shouldSuspend(result, errorResetBoundary, query) - - if (suspend === undefined) { - return undefined - } - - const queryObserver = new QueryObserver(client, opts) - const promise = getSuspensePromise( - opts, - queryObserver, - errorResetBoundary, - query, - ) - - return suspend ? promise : undefined - }) - - // Start every fetch before calling use(), because use() suspends immediately. - for (const promise of suspensePromises) { - if (promise) { - use(promise) - } - } -} - -/** Supplies Suspense behavior for parallel queries. */ -export const suspenseQueriesPolicy = { - prepare: ensureSuspenseTimers, - readQueries: useReadSuspenseQueries, -} diff --git a/packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts b/packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts deleted file mode 100644 index 967af141bf0..00000000000 --- a/packages/react-query-no-core-pluggable/src/useInfiniteQuery.ts +++ /dev/null @@ -1,364 +0,0 @@ -'use client' -import { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' -import { useBaseQuery } from './useBaseQuery' -import type { - DefaultError, - InfiniteData, - QueryKey, -} from '@tanstack/query-types/bindings' -import type { - DefinedInitialDataInfiniteOptions, - UndefinedInitialDataInfiniteOptions, -} from './infiniteQueryOptions' -import type { QueryClient } from './runtime/queryClient' -import type { QueryObserver } from './runtime/queryObserver' -import type { - DefinedUseInfiniteQueryResult, - UseInfiniteQueryOptions, - UseInfiniteQueryResult, -} from './types' - -/** - * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of - * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. - * - * This overload is selected when `initialData` is known to be defined. - * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`, with `initialData` known to be defined. - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will - * be used. - * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`, - * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and - * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default - * `InfiniteData` shape. - * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default - * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user - * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `infiniteQuery(client, options)`. - * @example - * ```tsx - * import { useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' - * - * function Projects() { - * // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the - * // list stays visible alongside the error. - * const { data, isError, error } = useInfiniteQuery({ - * queryKey: ['projects'], - * queryFn: ({ pageParam }) => fetchProjects(pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * initialData: { pages: [], pageParams: [] }, - * }) - * - * return ( - *
    - * {isError ? Error: {error.message} : null} - *
      - * {data.pages.map((page) => page.projects.map((p) =>
    • {p.name}
    • ))} - *
    - *
    - * ) - * } - * ``` - */ -export function useInfiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, ->( - options: DefinedInitialDataInfiniteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - queryClient?: QueryClient, -): DefinedUseInfiniteQueryResult - -/** - * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of - * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. - * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will - * be used. - * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`, - * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and - * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default - * `InfiniteData` shape. - * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default - * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user - * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `infiniteQuery(client, options)`. - * @example - * Fetching the next page from a "Load More" button click: - * ```tsx - * import { useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' - * - * function Projects() { - * const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = - * useInfiniteQuery({ - * queryKey: ['projects'], - * queryFn: ({ pageParam }) => fetchProjects(pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * }) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return ( - * <> - *
      - * {data.pages.map((page) => - * page.projects.map((project) =>
    • {project.name}
    • ), - * )} - *
    - * - * - * ) - * } - * ``` - * @example - * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a - * sentinel element after the list: - * ```tsx - * import { useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' - * import { useEffect, useRef } from 'react' - * - * function Projects() { - * const { - * data, - * isPending, - * isError, - * error, - * fetchNextPage, - * hasNextPage, - * isFetching, - * isFetchingNextPage, - * } = useInfiniteQuery({ - * queryKey: ['projects'], - * queryFn: ({ pageParam }) => fetchProjects(pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * }) - * - * const sentinelRef = useRef(null) - * - * useEffect(() => { - * const sentinel = sentinelRef.current - * if (sentinel == null || !hasNextPage || isFetching) return - * - * const observer = new IntersectionObserver(([entry]) => { - * if (entry?.isIntersecting) fetchNextPage() - * }) - * observer.observe(sentinel) - * - * return () => observer.disconnect() - * }, [hasNextPage, isFetching, fetchNextPage]) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return ( - * <> - *
      - * {data.pages.map((page) => - * page.projects.map((project) =>
    • {project.name}
    • ), - * )} - *
    - *
    {isFetchingNextPage ? 'Loading more...' : null}
    - * - * ) - * } - * ``` - */ -export function useInfiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, ->( - options: UndefinedInitialDataInfiniteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - queryClient?: QueryClient, -): UseInfiniteQueryResult - -/** - * The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of - * `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. - * @param options - The {@link UseInfiniteQueryOptions} to use — everything you can pass to `useInfiniteQuery`. - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will - * be used. - * @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`, - * `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and - * `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default - * `InfiniteData` shape. - * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default - * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user - * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `infiniteQuery(client, options)`. - * @example - * Fetching the next page from a "Load More" button click: - * ```tsx - * import { useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' - * - * function Projects() { - * const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = - * useInfiniteQuery({ - * queryKey: ['projects'], - * queryFn: ({ pageParam }) => fetchProjects(pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * }) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return ( - * <> - *
      - * {data.pages.map((page) => - * page.projects.map((project) =>
    • {project.name}
    • ), - * )} - *
    - * - * - * ) - * } - * ``` - * @example - * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a - * sentinel element after the list: - * ```tsx - * import { useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' - * import { useEffect, useRef } from 'react' - * - * function Projects() { - * const { - * data, - * isPending, - * isError, - * error, - * fetchNextPage, - * hasNextPage, - * isFetching, - * isFetchingNextPage, - * } = useInfiniteQuery({ - * queryKey: ['projects'], - * queryFn: ({ pageParam }) => fetchProjects(pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * }) - * - * const sentinelRef = useRef(null) - * - * useEffect(() => { - * const sentinel = sentinelRef.current - * if (sentinel == null || !hasNextPage || isFetching) return - * - * const observer = new IntersectionObserver(([entry]) => { - * if (entry?.isIntersecting) fetchNextPage() - * }) - * observer.observe(sentinel) - * - * return () => observer.disconnect() - * }, [hasNextPage, isFetching, fetchNextPage]) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return ( - * <> - *
      - * {data.pages.map((page) => - * page.projects.map((project) =>
    • {project.name}
    • ), - * )} - *
    - *
    {isFetchingNextPage ? 'Loading more...' : null}
    - * - * ) - * } - * ``` - * @example - * A query that's disabled, type safe, until `postId` is set — pass `skipToken` as `queryFn` - * instead of setting `enabled: false`: - * ```tsx - * import { skipToken, useInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' - * - * function Comments({ postId }: { postId: string | undefined }) { - * // Use `isLoading`, not `isPending`, so the loading state doesn't show while the query is disabled. - * const { data, isLoading, isError, error } = useInfiniteQuery({ - * queryKey: ['post', postId, 'comments'], - * queryFn: - * postId != null - * ? ({ pageParam }) => fetchComments(postId, pageParam) - * : skipToken, - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * }) - * - * if (postId == null) return 'Select a post' - * if (isLoading) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return ( - *
      - * {data?.pages.map((page) => page.comments.map((c) =>
    • {c.text}
    • ))} - *
    - * ) - * } - * ``` - */ -export function useInfiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, ->( - options: UseInfiniteQueryOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - queryClient?: QueryClient, -): UseInfiniteQueryResult - -export function useInfiniteQuery( - options: UseInfiniteQueryOptions, - queryClient?: QueryClient, -) { - return useBaseQuery( - options, - InfiniteQueryObserver as typeof QueryObserver, - queryClient, - ) -} diff --git a/packages/react-query-no-core-pluggable/src/useIsFetching.ts b/packages/react-query-no-core-pluggable/src/useIsFetching.ts deleted file mode 100644 index a34c4aafe9e..00000000000 --- a/packages/react-query-no-core-pluggable/src/useIsFetching.ts +++ /dev/null @@ -1,57 +0,0 @@ -'use client' -import * as React from 'react' -import { useQueryClient } from './QueryClientProvider' -import { notifyManager } from './runtime/notifyManager' -import type { QueryClient } from './runtime/queryClient' -import type { QueryFilters } from './runtime/utils' - -/** - * The `useIsFetching` hook returns the `number` of the queries that your application is loading or fetching in - * the background (useful for app-wide loading indicators). - * @param filters - The {@link QueryFilters} to narrow down the matched queries. - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will - * be used. - * @returns Will be the `number` of the queries that your application is currently loading or fetching in the - * background. - * @example - * ```tsx - * import { useIsFetching } from '@tanstack/react-query-no-core-pluggable' - * - * function PostsFetchingIndicator() { - * // How many queries matching the posts prefix are fetching? - * const isFetchingPosts = useIsFetching({ queryKey: ['posts'] }) - * - * return isFetchingPosts ? Refreshing posts... : null - * } - * ``` - * @example - * A global loading indicator for any query fetching in the background, not just the ones on screen: - * ```tsx - * import { useIsFetching } from '@tanstack/react-query-no-core-pluggable' - * - * function GlobalLoadingIndicator() { - * const isFetching = useIsFetching() - * - * return isFetching ? ( - *
    Queries are fetching in the background...
    - * ) : null - * } - * ``` - */ -export function useIsFetching( - filters?: Omit, - queryClient?: QueryClient, -): number { - const client = useQueryClient(queryClient) - const queryCache = client.getQueryCache() - - return React.useSyncExternalStore( - React.useCallback( - (onStoreChange) => - queryCache.subscribe(notifyManager.batchCalls(onStoreChange)), - [queryCache], - ), - () => client.isFetching(filters), - () => client.isFetching(filters), - ) -} diff --git a/packages/react-query-no-core-pluggable/src/useMutation.ts b/packages/react-query-no-core-pluggable/src/useMutation.ts deleted file mode 100644 index 702969bd830..00000000000 --- a/packages/react-query-no-core-pluggable/src/useMutation.ts +++ /dev/null @@ -1,239 +0,0 @@ -'use client' -import * as React from 'react' -import { useQueryClient } from './QueryClientProvider' -import { MutationObserver } from './runtime/mutationObserver' -import { notifyManager } from './runtime/notifyManager' -import { noop, shouldThrowError } from './runtime/utils' -import type { DefaultError } from '@tanstack/query-types/bindings' -import type { QueryClient } from './runtime/queryClient' -import type { - UseMutateFunction, - UseMutationOptions, - UseMutationResult, -} from './types' - -// HOOK - -/** - * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. - * `useMutation` is the hook for that. - * @param options - The {@link UseMutationOptions} to use — everything you can pass to `useMutation`. - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will - * be used. - * @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second - * argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared - * mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks - * fire only for the latest call you've made, and only while the component is still mounted — unmounting before - * the mutation settles removes the subscription and prevents them from firing. - * @throws {Error} The mutation error, when `throwOnError` is `true` or returns `true` for it, so that it is - * thrown to the nearest error boundary. - * @see {@link mutationOptions} to share these options across multiple `useMutation` call sites, or to look - * the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`). - * @example - * ```tsx - * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core-pluggable' - * - * function AddTodo() { - * const queryClient = useQueryClient() - * - * const addMutation = useMutation({ - * mutationFn: addTodo, - * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), - * }) - * - * return ( - * - * ) - * } - * ``` - * @example - * Rendering the mutation's own state, rather than just firing it off: - * ```tsx - * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core-pluggable' - * - * function AddTodo() { - * const queryClient = useQueryClient() - * - * const addMutation = useMutation({ - * mutationFn: addTodo, - * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), - * }) - * - * return ( - *
    - * {addMutation.isPending ? ( - * 'Adding todo...' - * ) : ( - * <> - * {addMutation.isError ? ( - *
    An error occurred: {addMutation.error.message}
    - * ) : null} - * - * - * )} - *
    - * ) - * } - * ``` - * @example - * Optimistic update via `onMutate`, rolling back on `onError`: - * ```tsx - * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core-pluggable' - * - * function AddTodo() { - * const queryClient = useQueryClient() - * - * const addMutation = useMutation({ - * mutationFn: addTodo, - * onMutate: async (newTodo) => { - * await queryClient.cancelQueries({ queryKey: ['todos'] }) - * const previousTodos = queryClient.getQueryData>(['todos']) - * - * queryClient.setQueryData>(['todos'], (old) => [ - * ...(old ?? []), - * newTodo, - * ]) - * - * // Passed to `onError` as `onMutateResult` if the mutation fails. - * return { previousTodos } - * }, - * onError: (_err, _newTodo, onMutateResult) => { - * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos) - * }, - * onSettled: () => { - * queryClient.invalidateQueries({ queryKey: ['todos'] }) - * }, - * }) - * - * return ( - * - * ) - * } - * ``` - * @example - * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a - * promise per call instead, so you can wait for all of them when they succeed: - * ```tsx - * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core-pluggable' - * - * function AddTodos() { - * const queryClient = useQueryClient() - * - * const addMutation = useMutation({ - * mutationFn: addTodo, - * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), - * }) - * - * async function handleAddAll(todos: Array) { - * try { - * await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo))) - * } catch (error) { - * console.error('Failed to add todos:', error) - * } - * } - * - * return ( - * - * ) - * } - * ``` - * @example - * If some of the mutations above can fail independently of the others, and you want to know which ones - * did — rather than losing that information the moment the first one rejects — swap `Promise.all` for - * `Promise.allSettled`: - * ```tsx - * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core-pluggable' - * - * function AddTodos() { - * const queryClient = useQueryClient() - * - * const addMutation = useMutation({ - * mutationFn: addTodo, - * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), - * }) - * - * async function handleAddAll(todos: Array) { - * const addResults = await Promise.allSettled( - * todos.map((todo) => addMutation.mutateAsync(todo)), - * ) - * - * addResults.forEach((addResult, index) => { - * if (addResult.status === 'rejected') { - * console.error(`Failed to add "${todos[index]}":`, addResult.reason) - * } - * }) - * } - * - * return ( - * - * ) - * } - * ``` - */ -export function useMutation< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, ->( - options: UseMutationOptions, - queryClient?: QueryClient, -): UseMutationResult { - const client = useQueryClient(queryClient) - - const [observer] = React.useState( - () => - new MutationObserver( - client, - options, - ), - ) - - React.useEffect(() => { - observer.setOptions(options) - }, [observer, options]) - - const result = React.useSyncExternalStore( - React.useCallback( - (onStoreChange) => - observer.subscribe(notifyManager.batchCalls(onStoreChange)), - [observer], - ), - () => observer.getCurrentResult(), - () => observer.getCurrentResult(), - ) - - const mutate = React.useCallback< - UseMutateFunction - >( - ( - ...args: Parameters< - UseMutateFunction - > - ) => { - observer.mutate(args[0] as TVariables, args[1]).catch(noop) - }, - [observer], - ) - - if ( - result.error && - shouldThrowError(observer.options.throwOnError, [result.error]) - ) { - throw result.error - } - - return { ...result, mutate, mutateAsync: result.mutate } -} diff --git a/packages/react-query-no-core-pluggable/src/usePrefetchQuery.tsx b/packages/react-query-no-core-pluggable/src/usePrefetchQuery.tsx deleted file mode 100644 index 04429309988..00000000000 --- a/packages/react-query-no-core-pluggable/src/usePrefetchQuery.tsx +++ /dev/null @@ -1,60 +0,0 @@ -import { useQueryClient } from './QueryClientProvider' -import { noop } from './runtime/utils' -import type { DefaultError, QueryKey } from '@tanstack/query-types/bindings' -import type { QueryClient } from './runtime/queryClient' -import type { UsePrefetchQueryOptions } from './types' - -/** - * `usePrefetchQuery` does not return anything, it should be used just to fire a prefetch during render, before - * a suspense boundary that wraps a component that uses `useSuspenseQuery`. You can pass everything to - * `usePrefetchQuery` that you can pass to `queryClient.query`, though `queryKey` is always required, and - * `queryFn` is required. Pass `defaultQueryFn` to use the client defaults. - * - * The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left - * over from a previous attempt — so calling this on every render is cheap and won't refetch data that's - * already there or already in flight. - * @param options - The {@link UsePrefetchQueryOptions} to use — everything you can pass to `queryClient.query`. - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will - * be used. - * @example - * ```tsx - * import { Suspense } from 'react' - * import { usePrefetchQuery } from '@tanstack/react-query-no-core-pluggable' - * - * function App() { - * // Fire the prefetch during render, before the suspense boundary below. - * usePrefetchQuery({ - * queryKey: ['posts'], - * queryFn: fetchPosts, - * }) - * - * return ( - * Loading posts...}> - * - * - * ) - * } - * ``` - */ -export function usePrefetchQuery< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - options: UsePrefetchQueryOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >, - queryClient?: QueryClient, -): void { - const client = useQueryClient(queryClient) - - if (!client.getQueryState(options.queryKey)) { - void client.query(options).catch(noop) - } -} diff --git a/packages/react-query-no-core-pluggable/src/useSuspenseInfiniteQuery.ts b/packages/react-query-no-core-pluggable/src/useSuspenseInfiniteQuery.ts deleted file mode 100644 index 0b347444c20..00000000000 --- a/packages/react-query-no-core-pluggable/src/useSuspenseInfiniteQuery.ts +++ /dev/null @@ -1,185 +0,0 @@ -'use client' -import { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' -import { skipToken } from './runtime/utils' -import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' -import { useBaseQuery } from './useBaseQuery' -import type { - DefaultError, - InfiniteData, - OmitKeyof, - QueryKey, -} from '@tanstack/query-types/bindings' -import type { QueryClient } from './runtime/queryClient' -import type { QueryObserver } from './runtime/queryObserver' -import type { - UseInfiniteQueryOptions, - UseInfiniteQueryResult, - UseSuspenseInfiniteQueryOptions, - UseSuspenseInfiniteQueryResult, -} from './types' - -type SkippableSuspenseInfiniteQueryOptions< - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey, - TPageParam, -> = OmitKeyof< - UseInfiniteQueryOptions, - 'enabled' | 'throwOnError' -> - -/** - * The options for `useSuspenseInfiniteQuery` are the same as for `useInfiniteQuery`, except for `throwOnError` - * and `enabled`. - * - * Caveat: cancellation does not work. - * @param options - The {@link UseSuspenseInfiniteQueryOptions} to use — the same options as `useInfiniteQuery`, minus the ones listed above. - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will - * be used. - * @returns The same object as `useInfiniteQuery`, except that `data` is guaranteed to be defined, - * `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived flags set - * accordingly). - * @remarks Multiple suspenseful query calls in the same component suspend serially, causing a request - * waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until - * then. There's no way to parallelize multiple infinite queries under Suspense. Also keep in mind that - * imperative fetch calls, such as `fetchNextPage`, may interfere with the default refetch behavior, - * resulting in outdated data. Make sure to call these functions only in response to user actions, or add - * conditions like `hasNextPage && !isFetching`. - * @see {@link useInfiniteQuery} for the non-Suspense version of this hook. - * @example - * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is - * required around ``. A failed background refetch instead continues to render the cached data. - * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: - * ```tsx - * import { Suspense } from 'react' - * import { ErrorBoundary } from 'react-error-boundary' - * import { - * QueryErrorResetBoundary, - * useSuspenseInfiniteQuery, - * } from '@tanstack/react-query-no-core-pluggable' - * - * function Projects() { - * // `data` is guaranteed to be defined here — no `isPending` check needed. - * const { data, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = - * useSuspenseInfiniteQuery({ - * queryKey: ['projects'], - * queryFn: ({ pageParam }) => fetchProjects(pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * }) - * - * return ( - *
    - *
      - * {data.pages.map((page) => - * page.projects.map((project) =>
    • {project.name}
    • ), - * )} - *
    - * - *
    - * ) - * } - * - * function App() { - * return ( - * - * {({ reset }) => ( - * ( - *
    - * There was an error! - * - *
    - * )} - * > - * Loading projects...}> - * - * - *
    - * )} - *
    - * ) - * } - * ``` - */ -export function useSuspenseInfiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, ->( - options: UseSuspenseInfiniteQueryOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - queryClient?: QueryClient, -): UseSuspenseInfiniteQueryResult - -/** - * A skipped query does not fetch automatically or suspend. Query errors without cached - * data reach the nearest error boundary. - * @param options - The infinite query options. The query function can be `skipToken`. - * @param queryClient - The client to use. Defaults to the client from the nearest context. - * @returns An infinite query result that can be pending and can have undefined data. - */ -export function useSuspenseInfiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, ->( - options: SkippableSuspenseInfiniteQueryOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - queryClient?: QueryClient, -): UseInfiniteQueryResult - -export function useSuspenseInfiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, ->( - options: SkippableSuspenseInfiniteQueryOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - queryClient?: QueryClient, -): UseInfiniteQueryResult { - const skipped = options.queryFn === skipToken - - return useBaseQuery( - { - ...options, - enabled: !skipped, - throwOnError: defaultThrowOnError, - }, - InfiniteQueryObserver as typeof QueryObserver, - queryClient, - skipped ? undefined : suspenseQueryPolicy, - ) as UseInfiniteQueryResult -} diff --git a/packages/react-query-no-core-pluggable/src/useSuspenseQuery.ts b/packages/react-query-no-core-pluggable/src/useSuspenseQuery.ts deleted file mode 100644 index 258522826ba..00000000000 --- a/packages/react-query-no-core-pluggable/src/useSuspenseQuery.ts +++ /dev/null @@ -1,151 +0,0 @@ -'use client' -import { QueryObserver } from './runtime/queryObserver' -import { skipToken } from './runtime/utils' -import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' -import { useBaseQuery } from './useBaseQuery' -import type { - DefaultError, - OmitKeyof, - QueryKey, -} from '@tanstack/query-types/bindings' -import type { QueryClient } from './runtime/queryClient' -import type { - UseQueryOptions, - UseQueryResult, - UseSuspenseQueryOptions, - UseSuspenseQueryResult, -} from './types' - -type SkippableSuspenseQueryOptions< - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey, -> = OmitKeyof< - UseQueryOptions, - 'enabled' | 'throwOnError' -> - -/** - * Runs a query with Suspense. The options match those of `useQuery` except for `throwOnError` and `enabled`. - * - * Caveat: cancellation does not work. - * @param options - The {@link UseSuspenseQueryOptions} for a query that always runs. - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will - * be used. - * @returns A result with data of type `TData` and a status of `success` or `error`. - * @remarks Multiple `useSuspenseQuery` calls in the same component suspend serially, causing a request - * waterfall — each one blocks rendering until it resolves, so the next doesn't even start fetching until then. - * Use {@link useSuspenseQueries} instead when you have more than one suspenseful query in a component, so they - * fetch in parallel. - * @example - * The query error is thrown if the fetch fails and no cached data exists yet, so an error boundary is - * required around ``. A failed background refetch instead continues to render the cached data. - * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: - * ```tsx - * import { Suspense } from 'react' - * import { ErrorBoundary } from 'react-error-boundary' - * import { QueryErrorResetBoundary, useSuspenseQuery } from '@tanstack/react-query-no-core-pluggable' - * - * function Posts() { - * // `data` is guaranteed to be defined here — no `isPending` check needed. - * const { data, isFetching } = useSuspenseQuery({ - * queryKey: ['posts'], - * queryFn: fetchPosts, - * }) - * - * return ( - *
    - *

    Posts {isFetching ? '(refreshing...)' : null}

    - *
      - * {data.map((post) => ( - *
    • {post.title}
    • - * ))} - *
    - *
    - * ) - * } - * - * function App() { - * return ( - * - * {({ reset }) => ( - * ( - *
    - * There was an error! - * - *
    - * )} - * > - * Loading posts...}> - * - * - *
    - * )} - *
    - * ) - * } - * ``` - */ -export function useSuspenseQuery< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - options: UseSuspenseQueryOptions, - queryClient?: QueryClient, -): UseSuspenseQueryResult - -/** - * Pass `skipToken` as `queryFn` to skip the query. While skipped, the query can read cached data - * but does not fetch automatically or suspend. Query errors without cached data reach the nearest error boundary. - * Pass a query function to resume normal Suspense behavior. - * @param options - Options for a query that can be skipped. - * @param queryClient - The client to use. Defaults to the client from the nearest context. - * @returns A result whose data can be undefined and whose status can be `pending`. - */ -export function useSuspenseQuery< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - options: SkippableSuspenseQueryOptions< - TQueryFnData, - TError, - TData, - TQueryKey - >, - queryClient?: QueryClient, -): UseQueryResult - -export function useSuspenseQuery< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - options: SkippableSuspenseQueryOptions< - TQueryFnData, - TError, - TData, - TQueryKey - >, - queryClient?: QueryClient, -): UseQueryResult { - const skipped = options.queryFn === skipToken - - return useBaseQuery( - { - ...options, - enabled: !skipped, - throwOnError: defaultThrowOnError, - }, - QueryObserver, - queryClient, - skipped ? undefined : suspenseQueryPolicy, - ) -} diff --git a/packages/react-query-no-core-pluggable/tests/compat-cacheOperations.ts b/packages/react-query-no-core-pluggable/tests/compat-cacheOperations.ts deleted file mode 100644 index 4981592c4f1..00000000000 --- a/packages/react-query-no-core-pluggable/tests/compat-cacheOperations.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { - cancelQueries, - getQueriesData, - invalidateQueries, - refetchQueries, - removeQueries, - resetQueries, - setQueriesData, -} from '../src/runtime/cacheOperations' -import { bindInfiniteQuery } from './compat-infiniteQuery' -import type { QueryClient } from '../src/runtime/queryClient' - -export function cacheOperations(client: TClient) { - function bind, TResult>( - operation: (client: QueryClient, ...args: TArgs) => TResult, - ) { - return (...args: TArgs) => operation(client, ...args) - } - - return { - infiniteQuery: bindInfiniteQuery(client), - getQueriesData: bind(getQueriesData), - setQueriesData: bind(setQueriesData), - removeQueries: bind(removeQueries), - resetQueries: bind(resetQueries), - cancelQueries: bind(cancelQueries), - invalidateQueries: bind(invalidateQueries), - refetchQueries: bind(refetchQueries), - } -} - -export { getMutationCache } from '../src' diff --git a/packages/react-query-no-core-pluggable/tests/compat-infiniteQuery.ts b/packages/react-query-no-core-pluggable/tests/compat-infiniteQuery.ts deleted file mode 100644 index 2dffedf0a79..00000000000 --- a/packages/react-query-no-core-pluggable/tests/compat-infiniteQuery.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { infiniteQuery } from '../src/runtime/infiniteQuery' -import type { WithoutSkipToken } from '@tanstack/query-types/bindings' -import type { QueryClient } from '../src/runtime/queryClient' -import type { - DefaultError, - InfiniteData, - InfiniteQueryExecuteOptions, - QueryKey, -} from '../src/runtime/types' - -export function bindInfiniteQuery(client: QueryClient) { - function run< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: WithoutSkipToken< - InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - > - >, - ): Promise< - Array extends Array> - ? InfiniteData - : TData - > - function run< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - ): Promise< - | undefined - | (Array extends Array> - ? InfiniteData - : TData) - > - function run< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - ): Promise< - | undefined - | (Array extends Array> - ? InfiniteData - : TData) - > { - return infiniteQuery(client, options) - } - return run -} diff --git a/packages/react-query-no-core-pluggable/tsconfig.prod.json b/packages/react-query-no-core-pluggable/tsconfig.prod.json deleted file mode 100644 index 2bb29fdf02a..00000000000 --- a/packages/react-query-no-core-pluggable/tsconfig.prod.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "incremental": false, - "composite": false, - "rootDir": "../../" - }, - "include": ["src"], - "exclude": ["src/__tests__"] -} diff --git a/packages/react-query-no-core/README.md b/packages/react-query-no-core/README.md deleted file mode 100644 index 7140b4f9f42..00000000000 --- a/packages/react-query-no-core/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# @tanstack/react-query-no-core - -An experimental ESM adapter for React 19 with its own query runtime. Import the client, provider and hooks from this package. Its client includes mutations and infinite queries by default. - -```tsx -import { - QueryClient, - QueryClientProvider, - useQuery, -} from '@tanstack/react-query-no-core' - -const client = new QueryClient() - -function Greeting() { - const { data } = useQuery({ - queryKey: ['greeting'], - queryFn: () => Promise.resolve('Hello'), - }) - return

    {data}

    -} - -export function App() { - return ( - - - - ) -} -``` - -The original adapter and both experimental adapters share their TypeScript definitions through `@tanstack/query-types`. Each React adapter owns its provider context and each client owns its caches. - -Use v6 option values directly, including `select: (data) => data.title`, `refetchInterval: 3000`, and `scope: { id: 'orders' }`. Imperative operations stay on the client, for example `client.infiniteQuery(options)` and `client.invalidateQueries({ queryKey: ['orders'] })`. The `queryOptions`, `infiniteQueryOptions`, and `mutationOptions` helpers all return their argument unchanged and share one JavaScript implementation. - -React batches subscriber updates. Use `notifyManager.setScheduler` to choose when notifications run, or `setNotifyFunction` to wrap them in `act` during tests. To inspect the queries in a `QueriesObserver`, call `observer.getObservers().map((item) => item.getCurrentQuery())`. diff --git a/packages/react-query-no-core/oxlint.config.ts b/packages/react-query-no-core/oxlint.config.ts deleted file mode 100644 index 91da02f7ef4..00000000000 --- a/packages/react-query-no-core/oxlint.config.ts +++ /dev/null @@ -1,51 +0,0 @@ -import pluginReact from '@eslint-react/eslint-plugin' -import reactHooks from 'eslint-plugin-react-hooks' -import { defineConfig } from 'oxlint' -import rootConfig from './root.oxlint.config.ts' - -export default defineConfig({ - extends: [rootConfig], - settings: rootConfig.settings, - jsPlugins: [ - // 'react-hooks' is reserved for Oxlint's native plugin, which lacks the React Compiler rules - { name: 'react-hooks-js', specifier: 'eslint-plugin-react-hooks' }, - '@eslint-react/eslint-plugin', - ], - rules: { - ...Object.fromEntries( - Object.entries(reactHooks.configs.flat.recommended.rules).map( - ([name, value]) => [ - name.replace(/^react-hooks\//, 'react-hooks-js/'), - value, - ], - ), - ), - ...pluginReact.configs.recommended.rules, - 'react-hooks-js/exhaustive-deps': 'error', - 'react-hooks-js/unsupported-syntax': 'error', - 'react-hooks-js/incompatible-library': 'error', - '@eslint-react/no-context-provider': 'off', // We need to be React 18 compatible - '@eslint-react/no-use-context': 'off', // We need to be React 18 compatible - // Covered by 'eslint-plugin-react-hooks' - '@eslint-react/error-boundaries': 'off', - '@eslint-react/exhaustive-deps': 'off', - '@eslint-react/globals': 'off', - '@eslint-react/immutability': 'off', - '@eslint-react/purity': 'off', - '@eslint-react/refs': 'off', - '@eslint-react/rules-of-hooks': 'off', - '@eslint-react/set-state-in-effect': 'off', - '@eslint-react/set-state-in-render': 'off', - '@eslint-react/static-components': 'off', - '@eslint-react/unsupported-syntax': 'off', - '@eslint-react/use-memo': 'off', - }, - overrides: [ - { - files: ['**/__tests__/**'], - rules: { - 'typescript/no-unnecessary-condition': 'off', - }, - }, - ], -}) diff --git a/packages/react-query-no-core/package.json b/packages/react-query-no-core/package.json deleted file mode 100644 index d58db8aaee9..00000000000 --- a/packages/react-query-no-core/package.json +++ /dev/null @@ -1,80 +0,0 @@ -{ - "name": "@tanstack/react-query-no-core", - "version": "5.108.4", - "description": "React Query with an integrated query runtime", - "author": "tannerlinsley", - "license": "MIT", - "repository": { - "type": "git", - "url": "git+https://github.com/TanStack/query.git", - "directory": "packages/react-query-no-core" - }, - "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": "node ../../scripts/test-react-query-compat.mjs", - "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__" - ], - "dependencies": { - "@tanstack/query-types": "workspace:*" - }, - "devDependencies": { - "@eslint-react/eslint-plugin": "catalog:", - "@types/react": "catalog:", - "eslint-plugin-react-hooks": "catalog:", - "react": "catalog:", - "typescript": "catalog:" - }, - "peerDependencies": { - "@types/react": "^19", - "react": "^19" - }, - "peerDependenciesMeta": { - "@types/react": { - "optional": true - } - }, - "nx": { - "targets": { - "test:lib": { - "inputs": [ - "default", - "^production", - "reactQueryCompatibility" - ] - } - } - } -} diff --git a/packages/react-query-no-core/root.oxlint.config.ts b/packages/react-query-no-core/root.oxlint.config.ts deleted file mode 120000 index 56565c65534..00000000000 --- a/packages/react-query-no-core/root.oxlint.config.ts +++ /dev/null @@ -1 +0,0 @@ -../../oxlint.config.ts \ No newline at end of file diff --git a/packages/react-query-no-core/root.tsdown.config.js b/packages/react-query-no-core/root.tsdown.config.js deleted file mode 120000 index a997d5d337c..00000000000 --- a/packages/react-query-no-core/root.tsdown.config.js +++ /dev/null @@ -1 +0,0 @@ -../../scripts/getTsdownConfig.js \ No newline at end of file diff --git a/packages/react-query-no-core/src/HydrationBoundary.tsx b/packages/react-query-no-core/src/HydrationBoundary.tsx deleted file mode 100644 index d323f68d103..00000000000 --- a/packages/react-query-no-core/src/HydrationBoundary.tsx +++ /dev/null @@ -1,137 +0,0 @@ -'use client' -import * as React from 'react' -import { useQueryClient } from './QueryClientProvider' -import { hydrate } from './runtime/hydration' -import type { DehydratedState, OmitKeyof } from '@tanstack/query-types/bindings' -import type { HydrateOptions } from './runtime/hydration' -import type { QueryClient } from './runtime/queryClient' - -/** - * The props accepted by `HydrationBoundary`. - */ -export interface HydrationBoundaryProps { - /** - * The state to hydrate. Pass the result of `dehydrate(queryClient)`. - */ - state: DehydratedState - /** - * Optional. Note: unlike `hydrate`, `mutations` cannot be set here. - */ - options?: OmitKeyof & { - defaultOptions?: OmitKeyof< - Exclude, - 'mutations' - > - } - /** - * The components to render — always rendered unconditionally, not gated on hydration. New queries are - * hydrated into the cache during render; for queries that already exist in the cache, only newer dehydrated - * data is hydrated, and that happens in an effect after commit, so `children` may render briefly before it - * lands. - */ - children?: React.ReactNode - /** - * Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will be used. - */ - queryClient?: QueryClient -} - -/** - * `HydrationBoundary` adds a previously dehydrated state into the `queryClient` that would be returned by - * `useQueryClient()`. If the client already contains data, the new queries will be intelligently merged based on - * update timestamp. - * - * Note: Only `queries` can be dehydrated with an `HydrationBoundary`. - * @param props - The dehydrated `state` to hydrate, the hydrate `options`, an optional custom - * `queryClient`, and the `children` to render. - * @returns The provided `children`, rendered unconditionally. New queries in `state` are hydrated into the - * cache during render; for queries already in the cache, only newer dehydrated data is hydrated, in an effect - * after commit. - * @example - * ```tsx - * import { HydrationBoundary } from '@tanstack/react-query-no-core' - * - * function App() { - * return ... - * } - * ``` - * @example - * Server-side prefetch handed off to the client via `dehydrate`: - * ```tsx - * import { HydrationBoundary, dehydrate, noop } from '@tanstack/react-query-no-core' - * - * async function ServerComponent() { - * const queryClient = getQueryClient() - * - * await queryClient - * .query({ - * queryKey: ['posts'], - * queryFn: fetchPosts, - * }) - * .catch(noop) - * - * return ( - * - * - * - * ) - * } - * ``` - */ -export const HydrationBoundary = ({ - children, - options = {}, - state, - queryClient, -}: HydrationBoundaryProps) => { - const client = useQueryClient(queryClient) - - const optionsRef = React.useRef(options) - React.useEffect(() => { - optionsRef.current = options - }) - - // Hydrate new queries during render so children can read their data. - // Hydrate existing queries after commit so an aborted transition cannot update them. - const hydrationQueue: DehydratedState['queries'] | undefined = - React.useMemo(() => { - const queryCache = client.getQueryCache() - - const newQueries: DehydratedState['queries'] = [] - const existingQueries: DehydratedState['queries'] = [] - for (const dehydratedQuery of state.queries) { - const existingQuery = queryCache.get(dehydratedQuery.queryHash) - - if (!existingQuery) { - newQueries.push(dehydratedQuery) - continue - } - - const hydrationIsNewer = - dehydratedQuery.state.dataUpdatedAt > - existingQuery.state.dataUpdatedAt || - (dehydratedQuery.promise && - existingQuery.state.status !== 'pending' && - existingQuery.state.fetchStatus !== 'fetching' && - dehydratedQuery.dehydratedAt > existingQuery.state.dataUpdatedAt) - - if (hydrationIsNewer) { - existingQueries.push(dehydratedQuery) - } - } - - if (newQueries.length > 0) { - // oxlint-disable-next-line react-hooks-js/refs -- new queries are hydrated during render on purpose, and 'options' is read through a ref so that a new 'options' object does not rerun this memo - hydrate(client, { queries: newQueries }, optionsRef.current) - } - return existingQueries.length > 0 ? existingQueries : undefined - }, [client, state]) - - React.useEffect(() => { - if (hydrationQueue) { - hydrate(client, { queries: hydrationQueue }, optionsRef.current) - } - }, [client, hydrationQueue]) - - return children as React.ReactElement -} diff --git a/packages/react-query-no-core/src/IsRestoringProvider.ts b/packages/react-query-no-core/src/IsRestoringProvider.ts deleted file mode 100644 index abb353406a6..00000000000 --- a/packages/react-query-no-core/src/IsRestoringProvider.ts +++ /dev/null @@ -1,18 +0,0 @@ -'use client' -import * as React from 'react' - -const IsRestoringContext = React.createContext(false) - -/** - * If you are using `PersistQueryClientProvider`, you can also use the `useIsRestoring` hook alongside it to - * check if a restore is currently in progress. `useQuery` and friends also check this internally to avoid - * race conditions between the restore and mounting queries. - * @returns `true` while a persisted client is being restored, `false` otherwise. - */ -export const useIsRestoring = () => React.useContext(IsRestoringContext) - -/** - * The Provider that `PersistQueryClientProvider` uses to signal whether a persisted client is currently - * being restored, read by `useIsRestoring`. - */ -export const IsRestoringProvider = IsRestoringContext.Provider diff --git a/packages/react-query-no-core/src/QueryClientProvider.tsx b/packages/react-query-no-core/src/QueryClientProvider.tsx deleted file mode 100644 index d1d7b9fc14d..00000000000 --- a/packages/react-query-no-core/src/QueryClientProvider.tsx +++ /dev/null @@ -1,84 +0,0 @@ -'use client' -import * as React from 'react' -import type { QueryClient } from './runtime/queryClient' - -/** - * The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it. - */ -export const QueryClientContext = React.createContext( - undefined, -) - -/** - * The `useQueryClient` hook returns the current `QueryClient` instance. - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will - * be used. - * @returns The current `QueryClient` instance. - * @throws {Error} If no `queryClient` argument is passed and no `QueryClientProvider` is found in the - * component tree. - */ -export const useQueryClient = (queryClient?: QueryClient) => { - const client = React.useContext(QueryClientContext) - - if (queryClient) { - return queryClient - } - - if (!client) { - throw new Error('No QueryClient set, use QueryClientProvider to set one') - } - - return client -} - -/** - * The props accepted by `QueryClientProvider`. - */ -export type QueryClientProviderProps = { - /** - * **Required** - * - * The `QueryClient` instance to provide. - */ - client: QueryClient - /** - * The components that get access to the provided `QueryClient`. - */ - children?: React.ReactNode -} - -/** - * Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also - * calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to - * focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or - * comes back online). - * @param props - The `client` to provide, and the `children` that get access to it. - * @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`. - * @example - * ```tsx - * import { QueryClient, QueryClientProvider } from '@tanstack/react-query-no-core' - * - * const queryClient = new QueryClient() - * - * function App() { - * return ... - * } - * ``` - */ -export const QueryClientProvider = ({ - client, - children, -}: QueryClientProviderProps): React.JSX.Element => { - React.useEffect(() => { - client.mount() - return () => { - client.unmount() - } - }, [client]) - - return ( - - {children} - - ) -} diff --git a/packages/react-query-no-core/src/errorBoundaryUtils.ts b/packages/react-query-no-core/src/errorBoundaryUtils.ts deleted file mode 100644 index 8ba639b93bc..00000000000 --- a/packages/react-query-no-core/src/errorBoundaryUtils.ts +++ /dev/null @@ -1,105 +0,0 @@ -'use client' -import * as React from 'react' -import { shouldThrowError } from './runtime/utils' -import type { - QueryKey, - QueryObserverResult, -} from '@tanstack/query-types/bindings' -import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' -import type { Query } from './runtime/query' -import type { - DefaultedQueryObserverOptions, - ThrowOnError, -} from './runtime/types' - -/** - * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`), - * unless the error boundary has been reset, so a remount doesn't retry the failed query before the - * user resets the boundary. Mutates the options. - * @param options - The defaulted query options to adjust. - * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`. - * @param query - The query, used to evaluate a `throwOnError` function against its error. - */ -export const ensurePreventErrorBoundaryRetry = < - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey extends QueryKey, ->( - options: DefaultedQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >, - errorResetBoundary: QueryErrorResetBoundaryValue, - query: Query | undefined, -) => { - const throwOnError = - query?.state.status === 'error' && - typeof options.throwOnError === 'function' - ? shouldThrowError(options.throwOnError, [ - query.state.error as TError, - query, - ]) - : options.throwOnError - - if (options.suspense || throwOnError) { - // Prevent retrying failed query if the error boundary has not been reset yet - if (!errorResetBoundary.isReset()) { - options.retryOnMount = false - } - } -} - -/** - * Clears the reset state of the error boundary after the component mounts, so later errors are - * thrown to the boundary again. - * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`. - */ -export const useClearResetErrorBoundary = ( - errorResetBoundary: QueryErrorResetBoundaryValue, -) => { - React.useEffect(() => { - errorResetBoundary.clearReset() - }, [errorResetBoundary]) -} - -/** - * Checks whether the query error should be thrown to the nearest error boundary: the query errored - * and isn't fetching, the boundary hasn't been reset, and either `suspense` is enabled with no data - * or `throwOnError` says so. - * @param params - The observer `result`, the `errorResetBoundary`, the `throwOnError` option, the - * `query`, and the `suspense` option. - * @returns `true` if the error should be thrown. - */ -export const getHasError = < - TData, - TError, - TQueryFnData, - TQueryData, - TQueryKey extends QueryKey, ->({ - result, - errorResetBoundary, - throwOnError, - query, - suspense, -}: { - result: QueryObserverResult - errorResetBoundary: QueryErrorResetBoundaryValue - throwOnError: ThrowOnError - query: Query | undefined - suspense: boolean | undefined -}) => { - return ( - result.isError && - !errorResetBoundary.isReset() && - !result.isFetching && - query && - ((suspense && result.data === undefined) || - shouldThrowError(throwOnError, [result.error, query])) - ) -} diff --git a/packages/react-query-no-core/src/index.ts b/packages/react-query-no-core/src/index.ts deleted file mode 100644 index ed1f2e1c562..00000000000 --- a/packages/react-query-no-core/src/index.ts +++ /dev/null @@ -1,240 +0,0 @@ -/* istanbul ignore file */ - -// Public cache and observer API -export { focusManager } from './runtime/focusManager' -export type { FocusManager } from './runtime/focusManager' -export { environmentManager } from './runtime/environmentManager' -export { - defaultShouldDehydrateMutation, - defaultShouldDehydrateQuery, - dehydrate, - dehydrateQuery, - hydrate, -} from './runtime/hydration' -export { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' -export { MutationCache } from './runtime/mutationCache' -export type { - MutationCacheNotifyEvent, - MutationCacheConfig, -} from './runtime/mutationCache' -export { MutationObserver } from './runtime/mutationObserver' -export { defaultScheduler, notifyManager } from './runtime/notifyManager' -export { onlineManager } from './runtime/onlineManager' -export type { OnlineManager } from './runtime/onlineManager' -export { QueriesObserver } from './runtime/queriesObserver' -export { QueryCache } from './runtime/queryCache' -export type { - QueryCacheNotifyEvent, - QueryCacheConfig, -} from './runtime/queryCache' -export { QueryClient } from './runtime/queryClient' -export type { QueryRuntime } from './runtime/runtimeBinding' -export { QueryObserver } from './runtime/queryObserver' -export type { - QueryObserverResultReader, - ManagedTimerId, - TimeoutCallback, - TimeoutProvider, - DefaultQueryFn, - SkipToken, - Updater, - DehydratedState, - MutationState, - QueriesObserverOptions, - QueriesObserverResultReader, - QueryState, - NonUndefinedGuard, - DistributiveOmit, - OmitKeyof, - Override, - Register, - DefaultError, - QueryKey, - 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, - QueryObserverResult, - InfiniteQueryObserverBaseResult, - InfiniteQueryObserverPendingResult, - InfiniteQueryObserverLoadingResult, - InfiniteQueryObserverLoadingErrorResult, - InfiniteQueryObserverRefetchErrorResult, - InfiniteQueryObserverSuccessResult, - InfiniteQueryObserverPlaceholderResult, - DefinedInfiniteQueryObserverResult, - InfiniteQueryObserverResult, - MutationKey, - MutationStatus, - MutationScope, - MutationMeta, - CancelOptions, - SetDataOptions, - NotifyEventType, - NotifyEvent, -} from '@tanstack/query-types/bindings' -export { CancelledError } from './runtime/retryer' -export { timeoutManager } from './runtime/timeoutManager' -export type { TimeoutManager } from './runtime/timeoutManager' -export { - hashKey, - keepPreviousData, - matchMutation, - matchQuery, - noop, - partialMatchKey, - replaceEqualDeep, - shouldThrowError, - defaultQueryFn, - skipToken, -} from './runtime/utils' -export type { MutationFilters, QueryFilters } from './runtime/utils' -export { streamedQuery } from './runtime/streamedQuery' -export type { DehydrateOptions, HydrateOptions } from './runtime/hydration' -export { Mutation } from './runtime/mutation' -export { Query } from './runtime/query' -export { dataTagSymbol, dataTagErrorSymbol, unsetMarker } from './runtime/types' -export type { - QueryFunction, - StaleTimeFunction, - QueryBooleanOption, - QueryPersister, - QueryFunctionContext, - PlaceholderDataFunction, - QueryOptions, - ThrowOnError, - QueryObserverOptions, - DefaultedQueryObserverOptions, - InfiniteQueryObserverOptions, - DefaultedInfiniteQueryObserverOptions, - QueryExecuteOptions, - InfiniteQueryExecuteOptions, - InvalidateQueryFilters, - RefetchQueryFilters, - MutationFunctionContext, - MutationFunction, - MutationOptions, - MutationObserverOptions, - MutateOptions, - MutateFunctionRest, - MutateFunction, - MutationObserverBaseResult, - MutationObserverIdleResult, - MutationObserverLoadingResult, - MutationObserverErrorResult, - MutationObserverSuccessResult, - MutationObserverResult, - QueryClientConfig, - DefaultOptions, -} from './runtime/types' - -// React Query -export type { - AnyUseBaseQueryOptions, - UseBaseQueryOptions, - UsePrefetchQueryOptions, - UsePrefetchInfiniteQueryOptions, - AnyUseQueryOptions, - UseQueryOptions, - AnyUseSuspenseQueryOptions, - UseSuspenseQueryOptions, - AnyUseInfiniteQueryOptions, - UseInfiniteQueryOptions, - AnyUseSuspenseInfiniteQueryOptions, - UseSuspenseInfiniteQueryOptions, - UseBaseQueryResult, - UseQueryResult, - UseSuspenseQueryResult, - DefinedUseQueryResult, - UseInfiniteQueryResult, - DefinedUseInfiniteQueryResult, - UseSuspenseInfiniteQueryResult, - AnyUseMutationOptions, - UseMutationOptions, - UseMutateFunction, - UseMutateAsyncFunction, - UseBaseMutationResult, - UseMutationResult, -} from './types' -export { useQueries } from './useQueries' -export type { QueriesResults, QueriesOptions } from './useQueries' -export { useQuery } from './useQuery' -export { useSuspenseQuery } from './useSuspenseQuery' -export { useSuspenseInfiniteQuery } from './useSuspenseInfiniteQuery' -export { useSuspenseQueries } from './useSuspenseQueries' -export type { - SuspenseQueriesResults, - SuspenseQueriesOptions, -} from './useSuspenseQueries' -export { usePrefetchQuery } from './usePrefetchQuery' -export { usePrefetchInfiniteQuery } from './usePrefetchInfiniteQuery' -export { queryOptions } from './queryOptions' -export type { - DefinedInitialDataOptions, - UndefinedInitialDataOptions, - UnusedSkipTokenOptions, -} from './queryOptions' -export { infiniteQueryOptions } from './infiniteQueryOptions' -export type { - DefinedInitialDataInfiniteOptions, - UndefinedInitialDataInfiniteOptions, - UnusedSkipTokenInfiniteOptions, -} from './infiniteQueryOptions' -export { - QueryClientContext, - QueryClientProvider, - useQueryClient, -} from './QueryClientProvider' -export type { QueryClientProviderProps } from './QueryClientProvider' -export type { QueryErrorResetBoundaryProps } from './QueryErrorResetBoundary' -export { HydrationBoundary } from './HydrationBoundary' -export type { HydrationBoundaryProps } from './HydrationBoundary' -export type { - QueryErrorClearResetFunction, - QueryErrorIsResetFunction, - QueryErrorResetBoundaryFunction, - QueryErrorResetFunction, -} from './QueryErrorResetBoundary' -export { - QueryErrorResetBoundary, - useQueryErrorResetBoundary, -} from './QueryErrorResetBoundary' -export { useIsFetching } from './useIsFetching' -export { useIsMutating, useMutationState } from './useMutationState' -export { useMutation } from './useMutation' -export { mutationOptions } from './mutationOptions' -export { useInfiniteQuery } from './useInfiniteQuery' -export { useIsRestoring, IsRestoringProvider } from './IsRestoringProvider' diff --git a/packages/react-query-no-core/src/runtime/environmentManager.ts b/packages/react-query-no-core/src/runtime/environmentManager.ts deleted file mode 100644 index 884adf23e94..00000000000 --- a/packages/react-query-no-core/src/runtime/environmentManager.ts +++ /dev/null @@ -1,41 +0,0 @@ -import type { IsServerValue } from '@tanstack/query-types/bindings' - -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/react-query-no-core' - * - * 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 - }, -} - -export type { IsServerValue } from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/focusManager.ts b/packages/react-query-no-core/src/runtime/focusManager.ts deleted file mode 100644 index d2b8745b1cc..00000000000 --- a/packages/react-query-no-core/src/runtime/focusManager.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { Subscribable } from './subscribable' -import type { - FocusManagerListener as Listener, - FocusManagerSetupFn as SetupFn, -} from '@tanstack/query-types/bindings' - -/** - * 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/react-query-no-core' - * - * 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/react-query-no-core' - * - * // 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/react-query-no-core/src/runtime/hydration.ts b/packages/react-query-no-core/src/runtime/hydration.ts deleted file mode 100644 index bafec476b72..00000000000 --- a/packages/react-query-no-core/src/runtime/hydration.ts +++ /dev/null @@ -1,370 +0,0 @@ -import { Mutation } from './mutation' -import { noop } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - DehydratedMutation, - DehydratedQuery, - DehydratedState, - TransformerFn, -} from '@tanstack/query-types/bindings' -import type { Query } from './query' -import type { QueryClient } from './queryClient' -import type { QueryRuntime } from './runtimeBinding' - -/** - * 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 Promise | undefined - - // .catch can be unavailable on certain kinds of thenable's - // oxlint-disable-next-line typescript/no-unnecessary-condition - thenResult?.catch?.(noop) - - if (data !== undefined) { - return { data } - } - - return undefined -} - -/** {@inheritDoc Shared.DehydrateOptions} */ -export type DehydrateOptions = Shared.DehydrateOptions - -/** {@inheritDoc Shared.HydrateOptions} */ -export type HydrateOptions = Shared.HydrateOptions - -// 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: mutation.options.scope }), - ...(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 queryClient.query({ - * queryKey: ['posts'], - * queryFn: getPosts, - * }) - * - * const dehydratedState = dehydrate(queryClient) - * ``` - */ -export function dehydrate( - client: QueryClient, - options: DehydrateOptions = {}, -): DehydratedState { - const filterMutation = - options.shouldDehydrateMutation ?? - client.getDefaultOptions().dehydrate?.shouldDehydrateMutation ?? - defaultShouldDehydrateMutation - - const mutations = client - .getMutationCache() - .getAll() - .flatMap((mutation) => - filterMutation(mutation) ? [dehydrateMutation(mutation)] : [], - ) - - const filterQuery = - options.shouldDehydrateQuery ?? - client.getDefaultOptions().dehydrate?.shouldDehydrateQuery ?? - defaultShouldDehydrateQuery - - const shouldRedactErrors = - options.shouldRedactErrors ?? - client.getDefaultOptions().dehydrate?.shouldRedactErrors - - const serializeData = - options.serializeData ?? client.getDefaultOptions().dehydrate?.serializeData - - const queries = client - .getQueryCache() - .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 { - const queryCache = client.getQueryCache() - const deserializeData = - options?.defaultOptions?.deserializeData ?? - client.getDefaultOptions().hydrate?.deserializeData - - dehydratedState.mutations?.forEach(({ state, ...mutationOptions }) => { - Mutation.build( - client, - { - ...client.getDefaultOptions().hydrate?.mutations, - ...options?.defaultOptions?.mutations, - ...mutationOptions, - }, - state, - ) - }) - - dehydratedState.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, - { - ...client.getDefaultOptions().hydrate?.queries, - ...options?.defaultOptions?.queries, - queryKey, - queryHash, - meta, - _type: queryType, - }, - // 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) - } - }, - ) -} - -export type { DehydratedState } from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/identity.ts b/packages/react-query-no-core/src/runtime/identity.ts deleted file mode 100644 index d6857688755..00000000000 --- a/packages/react-query-no-core/src/runtime/identity.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * Returns its argument by reference. Option helpers specialize the signature with - * their own overloads and add their key tags at compile time. - * @param value - The original value. - * @returns The original value. - */ -export function identity(value: T): T { - return value -} diff --git a/packages/react-query-no-core/src/runtime/infiniteQueryBehavior.ts b/packages/react-query-no-core/src/runtime/infiniteQueryBehavior.ts deleted file mode 100644 index f7774ecfb81..00000000000 --- a/packages/react-query-no-core/src/runtime/infiniteQueryBehavior.ts +++ /dev/null @@ -1,184 +0,0 @@ -import { - addConsumeAwareSignal, - addToArray, - ensureQueryFn, - fetchSignal, -} from './utils' -import type { FetchContext, Query } from './query' -import type { InfiniteData, InfiniteQueryPageParamsOptions } from './types' -import type { FetchSignalContext } from './utils' - -/** - * Installs 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. - */ -export function prepareInfiniteFetch( - context: FetchContext>, - query: Query, -): void { - 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) { - context.fetchFn = () => { - return context.options.persister?.( - fetchFn as any, - { - client: context.client, - queryKey: context.queryKey, - meta: context.options.meta, - signal: context.signal, - }, - query, - ) - } - } else { - context.fetchFn = 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 -} diff --git a/packages/react-query-no-core/src/runtime/infiniteQueryObserver.ts b/packages/react-query-no-core/src/runtime/infiniteQueryObserver.ts deleted file mode 100644 index 8fbd5546791..00000000000 --- a/packages/react-query-no-core/src/runtime/infiniteQueryObserver.ts +++ /dev/null @@ -1,277 +0,0 @@ -import { hasNextPage, hasPreviousPage } from './infiniteQueryBehavior' -import { QueryObserver } from './queryObserver' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - InfiniteQueryObserverListener, - ReplaceReturnType, -} from '@tanstack/query-types/bindings' -import type { Query } from './query' -import type { QueryClient } from './queryClient' -import type { - QueryObserverResultContext, - QueryObserverResultReader, -} from './queryObserver' -import type { QueryRuntime } from './runtimeBinding' -import type { Subscribable } from './subscribable' -import type { - DefaultError, - DefaultedInfiniteQueryObserverOptions, - FetchNextPageOptions, - FetchPreviousPageOptions, - InfiniteData, - InfiniteQueryObserverBaseResult, - InfiniteQueryObserverResult, - QueryKey, - QueryObserverResult, -} from './types' - -type InfiniteObserverOptionsInput< - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey, - TPageParam, -> = Shared.InfiniteObserverOptionsInput< - QueryRuntime, - 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`, and is the primitive that framework adapters (e.g. - * `useInfiniteQuery`) build their hooks on top of. - * @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 { - options._type = 'infinite' - super.setOptions(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({ - ...options, - _type: 'infinite', - }) 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' }, - }, - }) - } - - protected 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 { isFetching, isRefetching, isError, isRefetchError } = parentResult - const fetchDirection = state.fetchMeta?.fetchMore?.direction - - const isFetchNextPageError = isError && fetchDirection === 'forward' - const isFetchingNextPage = isFetching && fetchDirection === 'forward' - - const isFetchPreviousPageError = isError && fetchDirection === 'backward' - const isFetchingPreviousPage = isFetching && fetchDirection === 'backward' - - const result: InfiniteQueryObserverBaseResult = { - ...parentResult, - fetchNextPage: this.fetchNextPage, - fetchPreviousPage: this.fetchPreviousPage, - hasNextPage: hasNextPage(options, state.data), - hasPreviousPage: hasPreviousPage(options, state.data), - isFetchNextPageError, - isFetchingNextPage, - isFetchPreviousPageError, - isFetchingPreviousPage, - isRefetchError: - isRefetchError && !isFetchNextPageError && !isFetchPreviousPageError, - isRefetching: - isRefetching && !isFetchingNextPage && !isFetchingPreviousPage, - } - - return result as InfiniteQueryObserverResult - } -} diff --git a/packages/react-query-no-core/src/runtime/mutation.ts b/packages/react-query-no-core/src/runtime/mutation.ts deleted file mode 100644 index 79a3c27bf95..00000000000 --- a/packages/react-query-no-core/src/runtime/mutation.ts +++ /dev/null @@ -1,503 +0,0 @@ -import { notifyManager } from './notifyManager' -import { Removable } from './removable' -import { createRetryer } from './retryer' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - MutationAction as Action, - MutationState, -} from '@tanstack/query-types/bindings' -import type { MutationCache } from './mutationCache' -import type { MutationObserver } from './mutationObserver' -import type { QueryClient } from './queryClient' -import type { Retryer } from './retryer' -import type { QueryRuntime } from './runtimeBinding' -import type { - DefaultError, - MutationFunctionContext, - MutationMeta, - MutationOptions, -} from './types' - -type MutationConfig = - Shared.MutationConfig< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult - > - -// 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 = queryClient.getMutationCache() - * - * 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 = client.getMutationCache() - return cache.register( - (mutationId) => - new Mutation({ - client, - mutationCache: cache, - mutationId, - options: client.defaultMutationOptions(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.setOptions(config.options) - this.scheduleGc() - } - - /** - * Replaces the mutation's options and applies their `gcTime`. - * @internal - * @param options - The new mutation options. - */ - setOptions( - options: MutationOptions, - ): void { - this.options = options - - this.updateGcTime(this.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. queryClient.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, - } -} - -export type { - MutationState, - MutationAction as Action, -} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/mutationCache.ts b/packages/react-query-no-core/src/runtime/mutationCache.ts deleted file mode 100644 index c1d718aef25..00000000000 --- a/packages/react-query-no-core/src/runtime/mutationCache.ts +++ /dev/null @@ -1,272 +0,0 @@ -import { notifyManager } from './notifyManager' -import { Subscribable } from './subscribable' -import { matchMutation, noop } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { Mutation } from './mutation' -import type { QueryRuntime } from './runtimeBinding' -import type { DefaultError } from './types' -import type { MutationFilters } from './utils' - -/** {@inheritDoc Shared.MutationCacheConfig} */ -export type MutationCacheConfig = Shared.MutationCacheConfig - -/** {@inheritDoc Shared.MutationCacheNotifyEvent} */ -export type MutationCacheNotifyEvent = - Shared.MutationCacheNotifyEvent - -type MutationCacheListener = Shared.MutationCacheListener - -// CLASS - -/** - * The `MutationCache` is the storage for mutations. - * - * Normally, you will not interact with the `MutationCache` directly and instead use a - * `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of - * safe/known updates to the cache, such as mutations being added, removed, or updated. - * @example - * ```ts - * const unsubscribe = mutationCache.subscribe((event) => { - * console.log(event.type, event.mutation) - * }) - * ``` - */ -export class MutationCache extends Subscribable { - #mutations: Set> - #scopes: Map>> - #mutationId: number - - constructor(public config: MutationCacheConfig = {}) { - super() - this.#mutations = new Set() - this.#scopes = new Map() - 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) - const scope = scopeFor(mutation) - if (typeof scope === 'string') { - const scopedMutations = this.#scopes.get(scope) - if (scopedMutations) { - scopedMutations.push(mutation) - } else { - this.#scopes.set(scope, [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() - const scope = scopeFor(mutation) - const scopedMutations = this.#scopes.get(scope) - if (scopedMutations) { - const index = scopedMutations.indexOf(mutation) - if (index !== -1) { - scopedMutations.splice(index, 1) - if (!scopedMutations.length) { - this.#scopes.delete(scope) - } - } - } - } - - // 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 { - const firstPendingMutation = this.#scopes - .get(scopeFor(mutation)) - ?.find((candidate) => candidate.state.status === 'pending') - return !firstPendingMutation || firstPendingMutation === mutation - } - - /** - * 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 { - const next = this.#scopes - .get(scopeFor(mutation)) - ?.find((entry) => entry !== mutation && entry.state.isPaused) - - return next?.continue() ?? Promise.resolve() - } - - /** - * Removes all mutations and clears their garbage collection timers. - * Mutations that are already running continue to execute. - * @example - * ```ts - * const mutationCache = queryClient.getMutationCache() - * - * mutationCache.clear() - * ``` - */ - clear(): void { - notifyManager.batch(() => { - const mutations = this.getAll() - this.#mutations.clear() - this.#scopes.clear() - mutations.forEach((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 = queryClient.getMutationCache() - * - * 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 = queryClient.getMutationCache() - * - * 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 = queryClient.getMutationCache() - * - * 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)), - ), - ) - } -} - -/** - * Returns the scope id of a mutation, used to run mutations with the same scope one after another. - * @param mutation - The mutation to read the scope of. - * @returns The mutation's `scope.id`, or `undefined` if it has no scope. - */ -function scopeFor(mutation: Mutation) { - return mutation.options.scope?.id -} diff --git a/packages/react-query-no-core/src/runtime/mutationObserver.ts b/packages/react-query-no-core/src/runtime/mutationObserver.ts deleted file mode 100644 index 2feb3590d83..00000000000 --- a/packages/react-query-no-core/src/runtime/mutationObserver.ts +++ /dev/null @@ -1,331 +0,0 @@ -import { Mutation, getDefaultState } from './mutation' -import { notifyManager } from './notifyManager' -import { Subscribable } from './subscribable' -import { hashKeyByOptions, shallowEqualObjects } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { Action } from './mutation' -import type { QueryClient } from './queryClient' -import type { QueryRuntime } from './runtimeBinding' -import type { - DefaultError, - MutateOptions, - MutationFunctionContext, - MutationObserverOptions, - MutationObserverResult, -} from './types' - -type MutationObserverListener = - Shared.MutationObserverListener< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult - > - -// 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 - * QueryClient#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 = this.#client.defaultMutationOptions(options) - if (!shallowEqualObjects(this.options, prevOptions)) { - this.#client.getMutationCache().notify({ - type: 'observerOptionsUpdated', - mutation: this.#currentMutation, - observer: this, - }) - } - - if ( - prevOptions?.mutationKey && - this.options.mutationKey && - hashKeyByOptions( - prevOptions.mutationKey, - this.#client.getMutationCache().config.mutationKey, - ) !== - hashKeyByOptions( - this.options.mutationKey, - this.#client.getMutationCache().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/react-query-no-core/src/runtime/onlineManager.ts b/packages/react-query-no-core/src/runtime/onlineManager.ts deleted file mode 100644 index 78a07bb1662..00000000000 --- a/packages/react-query-no-core/src/runtime/onlineManager.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { Subscribable } from './subscribable' -import type { - OnlineManagerListener as Listener, - OnlineManagerSetupFn as SetupFn, -} from '@tanstack/query-types/bindings' - -/** - * 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/react-query-no-core' - * - * 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/react-query-no-core' - * - * // 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/react-query-no-core/src/runtime/queriesObserver.ts b/packages/react-query-no-core/src/runtime/queriesObserver.ts deleted file mode 100644 index 2b91a71a5d8..00000000000 --- a/packages/react-query-no-core/src/runtime/queriesObserver.ts +++ /dev/null @@ -1,459 +0,0 @@ -import { notifyManager } from './notifyManager' -import { QueryObserver } from './queryObserver' -import { Subscribable } from './subscribable' -import { - replaceEqualDeep, - shallowEqualObjects, - shouldThrowError, -} from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - CombineContext, - CombineFn, - QueriesObserverListener, - QueriesObserverOptions, - QueriesObserverResultReader, -} from '@tanstack/query-types/bindings' -import type { QueryClient } from './queryClient' -import type { ObserverOptionsInput } from './queryObserver' -import type { QueryRuntime } from './runtimeBinding' -import type { QueryObserverResult } from './types' - -/** - * 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, - ): QueriesObserverResultReader { - const matches = this.#findMatchingObservers(queries).map((match) => ({ - ...match, - reader: match.observer.createResultReader(match.defaultedQueryOptions), - })) - const queryHashes = matches.map( - (match) => match.defaultedQueryOptions.queryHash, - ) - const combine = options?.combine - const context = { ...this.#combineContext } - let result = this.#result - - const getSnapshot = () => { - const nextResult = matches.map((match) => match.reader.getSnapshot()) - if (!shallowEqualObjects(nextResult, result)) { - result = nextResult - } - return result - } - - return { - getSnapshot, - combineResult: (input) => { - // Notifications may have already combined these results. - const committed = this.#combineContext - if ( - committed.combine === combine && - equalResults(input, committed.result) && - shallowEqualObjects(queryHashes, committed.queryHashes) - ) { - Object.assign(context, committed) - } - return this.#combineResult( - this.#trackResult(input, matches), - combine, - queryHashes, - context, - input, - ) - }, - commit: () => { - this.#combineContext = { ...context } - this.#setQueries(matches, { combine }) - if ( - this.#options?.combine === combine && - equalResults(this.#result, context.result) - ) { - this.#combinedResult = context.value - } - }, - } - } - - #trackResult( - result: Array, - matches: Array, - ) { - const trackedProps = new Set() - - return matches.map((match, index) => { - const observerResult = result[index]! - return !match.defaultedQueryOptions.notifyOnChangeProps - ? match.observer.trackResult(observerResult, (accessedProp) => { - // track property on all observers to ensure proper (synchronized) tracking (#7000) - if (!trackedProps.has(accessedProp)) { - trackedProps.add(accessedProp) - matches.forEach((m) => { - m.observer.trackProp(accessedProp) - }) - } - }) - : observerResult - }) - } - - #combineResult( - input: Array, - combine: CombineFn | undefined, - queryHashes?: Array, - context = this.#combineContext, - result = this.#result, - ): TCombinedResult { - if (combine) { - const queryHashesChanged = - queryHashes !== undefined && - context.queryHashes !== undefined && - !shallowEqualObjects(queryHashes, context.queryHashes) - - if ( - !equalResults(result, context.result) || - queryHashesChanged || - combine !== context.combine - ) { - context.value = replaceEqualDeep(context.value, combine(input)) - context.combine = combine - context.result = result - if (queryHashes !== undefined) { - context.queryHashes = queryHashes - } - } - - return context.value as TCombinedResult - } - return input as any - } - - #shouldSkipCombine(): boolean { - return ( - !this.#options?.combine || - this.#observers.some((observer, index) => { - const result = this.#result[index] - return ( - (observer.options.suspense && result?.data === undefined) || - (!!result?.isError && - !result.isFetching && - shouldThrowError(observer.options.throwOnError, [ - result.error, - observer.getCurrentQuery(), - ])) - ) - }) - ) - } - - #findMatchingObservers( - queries: Array, - ): Array { - const prevObserversMap = new Map>() - - this.#observers.forEach((observer) => { - const key = observer.options.queryHash - if (!key) return - - const previousObservers = prevObserversMap.get(key) - - if (previousObservers) { - previousObservers.push(observer) - } else { - prevObserversMap.set(key, [observer]) - } - }) - - const observers: Array = [] - - queries.forEach((options) => { - const defaultedOptions = this.#client.defaultQueryOptions(options) - const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift() - const observer = - match ?? new QueryObserver(this.#client, defaultedOptions) - - observers.push({ - defaultedQueryOptions: defaultedOptions, - observer, - }) - }) - - return observers - } - - #subscribeTo(observer: QueryObserver): void { - // Create the listener here, not in `setQueries`: a listener created there - // keeps the previous observers, and their queries, alive (#12656) - observer.subscribe((result) => { - this.#onUpdate(observer, result) - }) - } - - #onUpdate(observer: QueryObserver, result: QueryObserverResult): void { - if (this.#updatingQueries) return - - const index = this.#observers.indexOf(observer) - if (index !== -1) { - this.#result = this.#result.slice() - this.#result[index] = result - this.#notify() - } - } - - #notify(): void { - if (this.hasListeners()) { - const shouldSkipCombine = this.#shouldSkipCombine() - const previousResult = this.#combinedResult - const newResult = shouldSkipCombine - ? previousResult - : this.#combineResult( - this.#trackResult(this.#result, this.#observerMatches), - this.#options?.combine, - this.#observerMatches.map( - (match) => match.defaultedQueryOptions.queryHash, - ), - ) - - this.#combinedResult = newResult - if (shouldSkipCombine || previousResult !== newResult) { - notifyManager.batch(() => { - this.listeners.forEach((listener) => { - listener(this.#result) - }) - }) - } - } - } -} - -type QueryObserverMatch = Shared.QueryObserverMatch - -export type { - QueriesObserverResultReader, - QueriesObserverOptions, -} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/query.ts b/packages/react-query-no-core/src/runtime/query.ts deleted file mode 100644 index befd4dfdd16..00000000000 --- a/packages/react-query-no-core/src/runtime/query.ts +++ /dev/null @@ -1,877 +0,0 @@ -import { prepareInfiniteFetch } from './infiniteQueryBehavior' -import { notifyManager } from './notifyManager' -import { Removable } from './removable' -import { CancelledError, canFetch, createRetryer } from './retryer' -import { - ensureQueryFn, - fetchSignal, - noop, - replaceData, - resolveQueryValue, - skipToken, - timeUntilStale, -} from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - FetchOptions, - QueryAction, - QueryState, -} from '@tanstack/query-types/bindings' -import type { QueryCache } from './queryCache' -import type { QueryClient } from './queryClient' -import type { QueryObserver } from './queryObserver' -import type { Retryer } from './retryer' -import type { QueryRuntime } from './runtimeBinding' -import type { - CancelOptions, - DefaultError, - InitialDataFunction, - QueryKey, - QueryMeta, - QueryOptions, - SetDataOptions, - StaleTime, -} from './types' - -type QueryConfig< - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey = QueryKey, -> = Shared.QueryConfig - -/** {@inheritDoc Shared.FetchContext} */ -export type FetchContext< - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey = QueryKey, -> = Shared.FetchContext - -/** {@inheritDoc Shared.QueryBehavior} */ -export type QueryBehavior< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = Shared.QueryBehavior - -// CLASS - -/** - * Represents a single cached query. A `Query` holds the query's key, options, - * state (data/error/status), and the observers currently subscribed to it. - * - * Instances are created and managed internally by `QueryCache`; application - * code typically interacts with queries indirectly through `QueryClient` or - * a framework hook like `useQuery`. Direct access to a `Query` instance is - * possible via `queryCache.find()`/`findAll()` for inspecting cache state. - * @example - * ```ts - * const queryCache = queryClient.getQueryCache() - * const query = queryCache.find({ queryKey: ['posts'] }) - * - * if (query) { - * console.log(query.state.dataUpdatedAt) - * } - * ``` - */ -export class Query< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> extends Removable { - queryKey: TQueryKey - queryHash: string - options!: QueryOptions - state: QueryState - #queryType?: 'infinite' - - #initialState: QueryState - #revertState?: QueryState - #cache: QueryCache - #client: QueryClient - #retryer?: Retryer - #fetchPromise?: Promise - observers: Array> - #defaultOptions?: QueryOptions - #abortSignalConsumed: boolean - - constructor(config: QueryConfig) { - super() - - this.#abortSignalConsumed = false - this.#defaultOptions = config.defaultOptions - this.setOptions(config.options) - this.observers = [] - this.#client = config.client - this.#cache = this.#client.getQueryCache() - this.queryKey = config.queryKey - this.queryHash = config.queryHash - this.#initialState = getDefaultState(this.options) - this.state = config.state ?? this.#initialState - this.scheduleGc() - } - /** - * The `meta` object passed in the query's options, if any. - * @returns The query's `meta`, or `undefined` if none was set. - */ - get meta(): QueryMeta | undefined { - return this.options.meta - } - - /** - * `'infinite'` for an infinite query, otherwise `undefined`. - * @internal - * @returns The type of the query, set from the `_type` option (e.g. `'infinite'`). - */ - get queryType() { - return this.#queryType - } - - /** - * The promise for the currently in-flight fetch, if the query is fetching. - * `undefined` when the query is not fetching. - * @returns The promise of the in-flight fetch, or `undefined`. - */ - get promise(): Promise | undefined { - return this.#retryer?.promise - } - - /** - * Replaces the query's options and applies their `gcTime`. If the query has no data yet, it gets - * the `initialData` from the new options, if any. - * @internal - * @param options - The new query options, merged on top of the query's default options. - */ - setOptions( - options?: QueryOptions, - ): void { - this.options = { ...this.#defaultOptions, ...options } - - if (options?._type) { - this.#queryType = options._type - } - - this.updateGcTime(this.options.gcTime) - - // oxlint-disable-next-line typescript/no-unnecessary-condition -- the constructor calls 'setOptions' before it assigns 'state' - if (this.state && this.state.data === undefined) { - const defaultState = getDefaultState(this.options) - if (defaultState.data !== undefined) { - this.setState( - successState(defaultState.data, defaultState.dataUpdatedAt), - ) - this.#initialState = defaultState - } - } - } - - protected override optionalRemove() { - if (!this.observers.length && this.state.fetchStatus === 'idle') { - this.#cache.remove(this) - } - } - - /** - * Writes new data to the query and marks it as successfully fetched. - * @internal - * @param newData - The data to write. Structural sharing with the current data is applied. - * @param options - Set `updatedAt` to override the timestamp, and `manual` to mark the write as - * manual (e.g. from `queryClient.setQueryData`). - * @returns The data that was written. - */ - setData( - newData: TData, - options?: SetDataOptions & { manual: boolean }, - ): TData { - const data = replaceData(this.state.data, newData, this.options) - - const manual = options?.manual - const dataUpdatedAt = options?.updatedAt - this.state = { - ...this.state, - ...successState(data, dataUpdatedAt), - dataUpdateCount: this.state.dataUpdateCount + 1, - ...(!manual && { - fetchStatus: 'idle' as const, - fetchFailureCount: 0, - fetchFailureReason: null, - }), - } - // A manual write becomes the snapshot to restore if a fetch is cancelled. - this.#revertState = manual ? this.state : undefined - this.#notify({ type: 'success', data, dataUpdatedAt, manual }) - - return data - } - - /** - * Merges the given partial state directly into this query's state, notifying observers. Used - * by persistence and broadcast plugins to restore a state snapshot, and by devtools to let a - * user manually trigger a loading/error state or edit the cached data. - * @param state - The partial state to merge into the query's state. - */ - setState(state: Partial>): void { - this.#update(state, { type: 'setState', state }) - } - - /** - * Cancels the query's currently in-flight fetch, if any. - * - Returns a promise that resolves once the cancellation has settled. - * - If no fetch is in progress, resolves immediately. - * @param options - Set `revert` to restore the state from before the fetch started, and `silent` - * to suppress the cancellation error when a new fetch replaces the cancelled one. - * @returns A promise that resolves once the cancellation has settled. - * @example - * ```ts - * await query.cancel() - * ``` - */ - cancel(options?: CancelOptions): Promise { - const promise = this.#retryer?.promise - this.#retryer?.cancel(options) - return promise ? promise.then(noop, noop) : Promise.resolve() - } - - /** - * Silently cancels any in-flight fetch, then clears the query's garbage - * collection timeout. Called by `QueryCache` when the query is removed from - * the cache. - * @see {@link Query#cancel} - */ - override destroy(): void { - this.cancel({ silent: true }) - // An abort listener can unsubscribe and schedule GC during cancellation. - super.destroy() - } - - /** - * The state the query was created with. - * @internal - * @returns The state the query had when it was first created, used by {@link Query#reset}. - */ - get resetState(): QueryState { - return this.#initialState - } - - /** - * Resets the query back to its initial state (the state it had when it was - * first created, e.g. any `initialData`), destroying it first to cancel any - * in-flight fetch. - */ - reset(): void { - this.destroy() - this.setState(this.resetState) - } - - /** - * Returns `true` if the query has at least one observer for which `enabled` - * does not resolve to `false`. - * @returns `true` if the query has an enabled observer. - */ - isActive(): boolean { - return this.observers.some( - (observer) => resolveQueryValue(observer.options.enabled, this) !== false, - ) - } - - /** - * Returns `true` if the query is disabled, meaning it will not fetch - * automatically. - * - If the query has observers, it is disabled when none of them are active - * (see `isActive`). - * - If the query has no observers, it is disabled when its `queryFn` is - * `skipToken` or it has never been fetched. - * @returns `true` if the query is disabled. - */ - isDisabled(): boolean { - if (this.getObserversCount() > 0) { - return !this.isActive() - } - // if a query has no observers, it should still be considered disabled if it never attempted a fetch - return this.options.queryFn === skipToken || !this.isFetched() - } - - /** - * Returns `true` if the query has been fetched, i.e. it has resolved with - * either data or an error at least once. - * @returns `true` if the query has been fetched. - */ - isFetched() { - return this.state.dataUpdateCount + this.state.errorUpdateCount > 0 - } - - /** - * Returns `true` if the query has data and at least one observer configured with - * `staleTime: 'static'`, meaning it is treated as never stale. - * @returns `true` if the query is static. - */ - isStatic(): boolean { - if (this.state.data === undefined) { - return false - } - - if (this.getObserversCount() > 0) { - return this.observers.some( - (observer) => - resolveQueryValue(observer.options.staleTime, this) === 'static', - ) - } - - return false - } - - /** - * Returns `true` if the query is stale. - * - If the query has observers, defers to whether any observer's current - * result reports `isStale` (which accounts for each observer's own - * `staleTime` and `enabled` state). - * - If the query has no observers, it is considered stale when it has no - * data or has been invalidated. - * @returns `true` if the query is stale. - * @see {@link Query#isStaleByTime} - * @example - * ```ts - * if (query.isStale()) { - * // refetch or otherwise treat the cached data as outdated - * } - * ``` - */ - isStale(): boolean { - // check observers first, their `isStale` has the source of truth - // calculated with `isStaleByTime` and it takes `enabled` into account - if (this.getObserversCount() > 0) { - return this.observers.some( - (observer) => observer.getCurrentResult().isStale, - ) - } - - return this.state.data === undefined || this.state.isInvalidated - } - - /** - * Returns `true` if the query's data is stale relative to the given - * `staleTime` (defaults to `0`). - * - A query with no data is always stale. - * - `staleTime: 'static'` is never stale. - * - An invalidated query is always stale. - * - Otherwise, staleness is based on elapsed time since `dataUpdatedAt`. - * @param staleTime - The time, in milliseconds, after which data is considered stale, or - * `'static'` to never treat existing data as stale. A query without data is stale either way. - * @returns `true` if the query's data is stale. - * @see {@link Query#isStale} - * @example - * ```ts - * const isStale = query.isStaleByTime(60 * 1000) - * ``` - */ - isStaleByTime(staleTime: StaleTime = 0): boolean { - // no data is always stale - if (this.state.data === undefined) { - return true - } - // static is never stale - if (staleTime === 'static') { - return false - } - // if the query is invalidated, it is stale - if (this.state.isInvalidated) { - return true - } - - return !timeUntilStale(this.state.dataUpdatedAt, staleTime) - } - - /** - * Refetches the query when the window regains focus, if an observer wants that, and continues a - * paused fetch. - * @internal - */ - onFocus(): void { - const observer = this.observers.find((x) => x.shouldFetchOnWindowFocus()) - - observer?.refetch({ cancelRefetch: false }) - - // Continue fetch if currently paused - this.#retryer?.continue() - } - - /** - * Refetches the query when the app reconnects, if an observer wants that, and continues a paused - * fetch. - * @internal - */ - onOnline(): void { - const observer = this.observers.find((x) => x.shouldFetchOnReconnect()) - - observer?.refetch({ cancelRefetch: false }) - - // Continue fetch if currently paused - this.#retryer?.continue() - } - - /** - * Subscribes an observer to the query and stops its garbage collection. - * @internal - * @param observer - The observer to add. Adding an observer that is already subscribed does - * nothing. - */ - addObserver(observer: QueryObserver): void { - if (!this.observers.includes(observer)) { - this.observers.push(observer) - - // Stop the query from being garbage collected - this.clearGcTimeout() - - this.#cache.notify({ type: 'observerAdded', query: this, observer }) - } - } - - /** - * Unsubscribes an observer from the query. - * @internal - * @param observer - The observer to remove. When the last observer is removed, the in-flight - * fetch is cancelled if its abort signal was consumed (otherwise only its retries are stopped), - * and garbage collection is scheduled if the query is still in the cache. - */ - removeObserver(observer: QueryObserver): void { - const index = this.observers.indexOf(observer) - if (index !== -1) { - this.observers.splice(index, 1) - - if (!this.observers.length) { - // If the transport layer does not support cancellation - // we'll let the query continue so the result can be cached - if (this.#retryer) { - if ( - this.#abortSignalConsumed || - (this.state.fetchStatus === 'paused' && - this.state.status === 'pending') - ) { - this.#retryer.cancel({ revert: true }) - } else { - this.#retryer.cancelRetry() - } - } - - this.#scheduleGcIfCached() - } - - this.#cache.notify({ type: 'observerRemoved', query: this, observer }) - } - } - - /** - * Returns the number of observers currently subscribed to this query. - * @returns The number of observers. - * @example - * ```ts - * if (query.getObserversCount() === 0) { - * // no component is currently watching this query - * } - * ``` - */ - getObserversCount(): number { - return this.observers.length - } - - /** - * Marks the query as invalidated, unless it is already invalidated. This - * updates `state.isInvalidated` and notifies observers, but does not by - * itself trigger a refetch. - * @example - * ```ts - * query.invalidate() - * ``` - */ - invalidate(): void { - if (!this.state.isInvalidated) { - this.#update({ isInvalidated: true }, { type: 'invalidate' }) - } - } - - /** - * Fetches the query, i.e. runs its `queryFn` (through any configured - * retryer/behavior) and updates the query's state with the result. - * - If a fetch is already in flight, returns its promise instead of - * starting a new one, unless `fetchOptions.cancelRefetch` is set and the - * query already has data, in which case the current fetch is silently - * cancelled first. - * - If `options` is passed, it replaces the query's current options - * before fetching. - * @param options - Query options that replace the query's current options before fetching. They - * are not applied when an in-flight fetch is reused. - * @param fetchOptions - Set `cancelRefetch` to cancel an in-flight fetch first (only if the query - * already has data), and `meta` to pass extra information to the query's behavior. - * @returns A promise that resolves with the fetched data, or rejects with the fetch error. If the - * fetch is cancelled with `revert` while the query has data, it resolves with the restored data - * instead. - */ - async fetch( - options?: QueryOptions, - fetchOptions?: FetchOptions, - ): Promise { - if ( - this.state.fetchStatus !== 'idle' && - // If the promise in the retryer is already rejected, we have to definitely - // re-start the fetch; there is a chance that the query is still in a - // pending state when that happens - this.#retryer?.status() !== 'rejected' - ) { - if (this.state.data !== undefined && fetchOptions?.cancelRefetch) { - // Silently cancel current fetch if the user wants to cancel refetch - this.cancel({ silent: true }) - } else if (this.#retryer && this.#fetchPromise) { - // make sure that retries that were potentially cancelled due to unmounts can continue - this.#retryer.continueRetry() - // Return current promise if we are already fetching - return this.#fetchPromise - } - } - - // Update config if passed, otherwise the config from the last execution is used - if (options) { - this.setOptions(options) - } - - // Use the options from the first observer with a query function if no function is found. - // This can happen when the query is hydrated or created with setQueryData. - if (!this.options.queryFn) { - const observer = this.observers.find((x) => x.options.queryFn) - if (observer) { - this.setOptions(observer.options) - } - } - - if (process.env.NODE_ENV !== 'production') { - if (!Array.isArray(this.options.queryKey)) { - console.error( - `As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']`, - ) - } - } - - const abortController = new AbortController() - - const addSignalProperty: ( - object: object, - ) => asserts object is { signal: AbortSignal } = (object) => { - Object.defineProperties(object, { - [fetchSignal]: { value: abortController.signal, enumerable: true }, - signal: { - enumerable: true, - get: () => { - this.#abortSignalConsumed = true - return abortController.signal - }, - }, - }) - } - - // Create fetch function - const fetchFn = () => { - const queryFn = ensureQueryFn(this.options, fetchOptions) - - const queryFnContext = { - client: this.#client, - queryKey: this.queryKey, - meta: this.meta, - } - addSignalProperty(queryFnContext) - - this.#abortSignalConsumed = false - if (this.options.persister) { - return this.options.persister( - queryFn, - queryFnContext, - this as unknown as Query, - ) - } - - return queryFn(queryFnContext) - } - - // Trigger behavior hook - const context = { - fetchOptions, - options: this.options, - queryKey: this.queryKey, - client: this.#client, - state: this.state, - fetchFn, - } - addSignalProperty(context) - - if (this.#queryType === 'infinite') { - const prepare = prepareInfiniteFetch as QueryBehavior< - TQueryFnData, - TError, - TData, - TQueryKey - >['onFetch'] - prepare(context, this as unknown as Query) - } - - // Store state in case the current fetch needs to be reverted - this.#revertState = this.state - - // Set to fetching state if not already in it - if ( - this.state.fetchStatus === 'idle' || - this.state.fetchMeta !== context.fetchOptions?.meta - ) { - const meta = context.fetchOptions?.meta - this.#update( - { - ...fetchState(this.state.data, this.options), - fetchMeta: meta ?? null, - }, - { type: 'fetch', meta }, - ) - } - - // Try to fetch the data - const retryer = (this.#retryer = createRetryer({ - initialPromise: fetchOptions?.initialPromise as - | Promise - | undefined, - fn: context.fetchFn as () => Promise, - onCancel: (error) => { - if (error instanceof CancelledError && error.revert) { - this.setState({ - ...this.#revertState, - fetchStatus: 'idle' as const, - }) - } - abortController.abort() - }, - onFail: (failureCount, error) => { - this.#update( - { fetchFailureCount: failureCount, fetchFailureReason: error }, - { type: 'failed', failureCount, error }, - ) - }, - onPause: () => { - this.#update({ fetchStatus: 'paused' }, { type: 'pause' }) - }, - onContinue: () => { - this.#update({ fetchStatus: 'fetching' }, { type: 'continue' }) - }, - retry: context.options.retry, - retryDelay: context.options.retryDelay, - networkMode: context.options.networkMode, - canRun: () => true, - })) - - const fetchPromise = (async () => { - try { - const data = await retryer.promise - // this is more of a runtime guard - if (data === undefined) { - if (process.env.NODE_ENV !== 'production') { - console.error( - `Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`, - ) - } - throw new Error(`${this.queryHash} data is undefined`) - } - - this.setData(data) - - // Notify cache callback - this.#cache.config.onSuccess?.(data, this as Query) - this.#cache.config.onSettled?.( - data, - this.state.error as any, - this as Query, - ) - return data - } catch (error) { - if (error instanceof CancelledError) { - if (error.silent) { - if (this.#retryer !== retryer && this.#fetchPromise) { - // A new fetch replaced the silently cancelled one, - // so we piggyback onto that promise. - return this.#fetchPromise - } - throw error - } else if (error.revert) { - // transform error into reverted state data - // if the initial fetch was cancelled, we have no data, so we have - // to get reject with a CancelledError - if (this.state.data === undefined) { - throw error - } - return this.state.data - } - } - const fetchError = error as TError - this.#update( - { - error: fetchError, - errorUpdatedAt: Date.now(), - errorUpdateCount: this.state.errorUpdateCount + 1, - fetchFailureCount: this.state.fetchFailureCount + 1, - fetchFailureReason: fetchError, - fetchStatus: 'idle', - status: 'error', - isInvalidated: true, - }, - { type: 'error', error: fetchError }, - ) - - // Notify cache callback - this.#cache.config.onError?.( - error as any, - this as Query, - ) - this.#cache.config.onSettled?.( - this.state.data, - error as any, - this as Query, - ) - - throw error // rethrow the error for further handling - } finally { - // The settled retryer's promise would otherwise pin this fetch's raw - // result (a second copy after structural sharing) for the query's lifetime - if (this.#retryer === retryer) { - this.#retryer = undefined - this.#fetchPromise = undefined - } - this.#scheduleGcIfCached() - } - })() - this.#fetchPromise = fetchPromise - retryer.start() - return fetchPromise - } - - #scheduleGcIfCached(): void { - if ( - this.#cache.get( - this.queryHash, - ) === this - ) { - this.scheduleGc() - } - } - - #update( - state: Partial>, - action: QueryAction, - ): void { - this.state = { ...this.state, ...state } - this.#notify(action) - } - - #notify(action: QueryAction): void { - notifyManager.batch(() => { - // Keep the current iteration stable if an observer unsubscribes - // synchronously while it is being notified. - this.observers.slice().forEach((observer) => { - observer.onQueryUpdate() - }) - - this.#cache.notify({ query: this, type: 'updated', action }) - }) - } -} - -/** - * Returns the state changes applied when a query starts fetching. - * @param data - The query's current data. If it is `undefined`, the query is also reset to - * `'pending'` with no error. - * @param options - The query options, whose `networkMode` decides whether the query is `'fetching'` - * or `'paused'`. - * @returns The partial query state for a starting fetch. - */ -export function fetchState< - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey, ->( - data: TData | undefined, - options: QueryOptions, -) { - return { - fetchFailureCount: 0, - fetchFailureReason: null, - fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused', - ...(data === undefined && - ({ - error: null, - status: 'pending', - } as const)), - } as const -} - -/** - * Returns the state changes applied when a query receives data. - * @param data - The new data. - * @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to the current time. - * @returns The partial query state for a successful update. - */ -function successState(data: TData | undefined, dataUpdatedAt?: number) { - return { - data, - dataUpdatedAt: dataUpdatedAt ?? Date.now(), - error: null, - isInvalidated: false, - status: 'success' as const, - } -} - -/** - * Returns the initial state of a query, based on its `initialData` and `initialDataUpdatedAt` - * options. - * @param options - The query options. - * @returns The initial query state: `'success'` if `initialData` is set, otherwise `'pending'`. - */ -function getDefaultState< - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey, ->( - options: QueryOptions, -): QueryState { - const data = - typeof options.initialData === 'function' - ? (options.initialData as InitialDataFunction)() - : options.initialData - - const hasData = data !== undefined - - const initialDataUpdatedAt = hasData - ? typeof options.initialDataUpdatedAt === 'function' - ? options.initialDataUpdatedAt() - : options.initialDataUpdatedAt - : 0 - - return { - data, - dataUpdateCount: 0, - dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0, - error: null, - errorUpdateCount: 0, - errorUpdatedAt: 0, - fetchFailureCount: 0, - fetchFailureReason: null, - fetchMeta: null, - isInvalidated: false, - status: hasData ? 'success' : 'pending', - fetchStatus: 'idle', - } -} - -export type { - QueryState, - FetchDirection, - FetchMeta, - FetchOptions, - QueryAction as Action, -} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/queryClient.ts b/packages/react-query-no-core/src/runtime/queryClient.ts deleted file mode 100644 index 5afee16c341..00000000000 --- a/packages/react-query-no-core/src/runtime/queryClient.ts +++ /dev/null @@ -1,1077 +0,0 @@ -import { focusManager } from './focusManager' -import { MutationCache } from './mutationCache' -import { notifyManager } from './notifyManager' -import { onlineManager } from './onlineManager' -import { QueryCache } from './queryCache' -import { - defaultQueryFn, - functionalUpdate, - hashKeyByOptions, - noop, - partialMatchKey, - resolveQueryValue, - skipToken, -} from './utils' -import type { WithoutSkipToken } from '@tanstack/query-types/bindings' -import type { QueryState } from './query' -import type { - CacheKeyConfig, - CancelOptions, - DefaultError, - DefaultOptions, - DefaultedQueryObserverOptions, - InferDataFromTag, - InferErrorFromTag, - InfiniteData, - InfiniteQueryExecuteOptions, - InvalidateOptions, - InvalidateQueryFilters, - MutationKey, - MutationObserverOptions, - MutationOptions, - OmitKeyof, - QueryClientConfig, - QueryExecuteOptions, - QueryKey, - QueryObserverOptionsBase, - QueryOptions, - RefetchOptions, - RefetchQueryFilters, - ResetOptions, - SetDataOptions, -} from './types' -import type { MutationFilters, QueryFilters, Updater } from './utils' - -type QueryDefaults = OmitKeyof, 'queryKey'> -type MutationDefaults = MutationOptions - -class KeyDefaults< - TKey extends ReadonlyArray, - TOptions extends object, -> { - #entries = new Map() - - set(key: TKey, options: TOptions, config?: CacheKeyConfig): void { - this.#entries.set(hashKeyByOptions(key, config), { key, options }) - } - - get(key: TKey, config?: CacheKeyConfig): Partial { - const result: Partial = {} - for (const entry of this.#entries.values()) { - if (partialMatchKey(key, entry.key, config?.equalityFn)) { - Object.assign(result, entry.options) - } - } - return result - } -} - -// CLASS - -/** - * `QueryClient` is used to interact with a cache of queries and mutations. It owns a - * `QueryCache` and a `MutationCache` (creating default ones if none are passed in) and holds - * the default options that are applied to queries and mutations created through it. - * @example - * ```ts - * const queryClient = new QueryClient({ - * defaultOptions: { - * queries: { - * staleTime: Infinity, - * }, - * }, - * }) - * - * await queryClient.query({ queryKey: ['posts'], queryFn: fetchPosts }) - * ``` - */ -export class QueryClient { - #queryCache: QueryCache - #mutationCache: MutationCache - #defaultOptions: DefaultOptions - #queryDefaults = new KeyDefaults() - #mutationDefaults = new KeyDefaults() - #mountCount: number - #unsubscribeFocus?: () => void - #unsubscribeOnline?: () => void - - constructor(config: QueryClientConfig = {}) { - this.#queryCache = config.queryCache || new QueryCache() - this.#mutationCache = config.mutationCache || new MutationCache() - this.#defaultOptions = config.defaultOptions || {} - this.#mountCount = 0 - } - - /** - * Called by a framework adapter's `QueryClientProvider`-equivalent when it mounts, to start - * listening for focus/online events and resume paused mutations. Ref-counted via an internal - * mount count, so nested or multiple providers sharing the same `QueryClient` don't tear down - * the shared listeners until the last one unmounts. - */ - mount(): void { - this.#mountCount++ - if (this.#mountCount !== 1) return - - this.#unsubscribeFocus = focusManager.subscribe(async (focused) => { - if (focused) { - await this.resumePausedMutations() - this.#queryCache.onFocus() - } - }) - this.#unsubscribeOnline = onlineManager.subscribe(async (online) => { - if (online) { - await this.resumePausedMutations() - this.#queryCache.onOnline() - } - }) - } - - /** - * The inverse of {@link QueryClient#mount} — called by a framework adapter's - * `QueryClientProvider`-equivalent when it unmounts. Only tears down the focus/online - * listeners once the mount count returns to `0`. - */ - unmount(): void { - this.#mountCount-- - if (this.#mountCount !== 0) return - - this.#unsubscribeFocus?.() - this.#unsubscribeFocus = undefined - - this.#unsubscribeOnline?.() - this.#unsubscribeOnline = undefined - } - - /** - * Returns the number of queries in the cache that are currently fetching, optionally - * matching a set of filters. This includes background-fetching, loading new pages, and - * loading more infinite query results. - * @param filters - Narrows down which fetching queries are counted. Without filters, every - * fetching query is counted. - * @returns The number of matching queries whose `fetchStatus` is `'fetching'`. - * @example - * ```ts - * if (queryClient.isFetching()) { - * console.log('At least one query is fetching!') - * } - * ``` - */ - isFetching(filters?: Omit): number { - return this.#queryCache.findAll({ ...filters, fetchStatus: 'fetching' }) - .length - } - - /** - * Returns the number of mutations in the cache that are currently pending, optionally - * matching a set of filters. - * @param filters - Narrows down which pending mutations are counted. Without filters, every - * pending mutation is counted. - * @returns The number of matching mutations whose `status` is `'pending'`. - * @example - * ```ts - * if (queryClient.isMutating()) { - * console.log('At least one mutation is pending!') - * } - * ``` - */ - isMutating< - TMutationFilters extends MutationFilters = MutationFilters< - any, - any - >, - >(filters?: NoInfer>): number { - return this.#mutationCache.findAll({ ...filters, status: 'pending' }).length - } - - /** - * Imperative (non-reactive) way to retrieve data for a QueryKey. - * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates. - * - * Hint: Do not use this function inside a component, because it won't receive updates. - * Use `useQuery` to create a `QueryObserver` that subscribes to changes. - * @param queryKey - The query key of the query to read. - * @returns The cached data for the query, or `undefined` if no query with this key has been observed yet. - * @see {@link QueryClient#getQueriesData} - */ - getQueryData< - TQueryFnData = unknown, - TTaggedQueryKey extends QueryKey = QueryKey, - TInferredQueryFnData = InferDataFromTag, - >(queryKey: TTaggedQueryKey): TInferredQueryFnData | undefined { - const options = this.defaultQueryOptions({ queryKey }) - - return this.#queryCache.get(options.queryHash)?.state - .data - } - - /** - * 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 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 QueryClient#getQueryData} - * @example - * ```ts - * const data = queryClient.getQueriesData({ queryKey: ['posts'] }) - * ``` - */ - getQueriesData< - TQueryFnData = unknown, - TQueryFilters extends QueryFilters = QueryFilters, - >(filters: TQueryFilters): Array<[QueryKey, TQueryFnData | undefined]> { - return this.#queryCache.findAll(filters).map(({ queryKey, state }) => { - const data = state.data as TQueryFnData | undefined - return [queryKey, data] - }) - } - - /** - * Synchronous way to immediately update a query's cached data. If the updater (or the value - * passed) resolves to `undefined`, the cache is left untouched and no query is created; - * otherwise, if the query does not exist yet, it will be created. To update multiple queries - * at once by partially matching query keys, use {@link QueryClient#setQueriesData} instead. - * - * Updates must be performed immutably: do not mutate `oldData`, or data previously retrieved - * via {@link QueryClient#getQueryData}, in place. - * @param queryKey - The query key to set data for. - * @param updater - Either the new data, or a function that receives the 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 The data that was written, or `undefined` if the updater returned `undefined` — in that case - * the write is skipped and the cache is left unchanged. - * @example - * ```ts - * queryClient.setQueryData(['posts'], newPosts) - * - * // Or, using an updater function that receives the current data: - * queryClient.setQueryData(['posts'], (oldPosts) => [...oldPosts, newPost]) - * ``` - */ - setQueryData< - TQueryFnData = unknown, - TTaggedQueryKey extends QueryKey = QueryKey, - TInferredQueryFnData = InferDataFromTag, - >( - queryKey: TTaggedQueryKey, - updater: Updater< - InferDataFromTag, TTaggedQueryKey> | undefined, - NoInfer | undefined - >, - options?: SetDataOptions, - ): NoInfer | undefined { - const defaultedOptions = this.defaultQueryOptions< - any, - any, - unknown, - any, - QueryKey - >({ queryKey }) - - const query = this.#queryCache.get< - InferDataFromTag, TTaggedQueryKey> - >(defaultedOptions.queryHash) - const prevData = query?.state.data - const data = functionalUpdate(updater, prevData) - - if (data === undefined) { - return undefined - } - - return this.#queryCache - .build(this, defaultedOptions) - .setData(data, { ...options, manual: true }) - } - - /** - * 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 QueryClient#setQueryData} for each matching query. - * @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 QueryClient#setQueryData}. - * @example - * ```ts - * queryClient.setQueriesData({ queryKey: ['posts'] }, (oldPosts) => - * oldPosts ? oldPosts.filter((post) => post.id !== deletedId) : oldPosts, - * ) - * ``` - */ - setQueriesData< - TQueryFnData, - TQueryFilters extends QueryFilters = QueryFilters, - >( - filters: TQueryFilters, - updater: Updater< - NoInfer | undefined, - NoInfer | undefined - >, - options?: SetDataOptions, - ): Array<[QueryKey, TQueryFnData | undefined]> { - return notifyManager.batch(() => - this.#queryCache - .findAll(filters) - .map(({ queryKey }) => [ - queryKey, - this.setQueryData(queryKey, updater, options), - ]), - ) - } - - /** - * Imperative (non-reactive) way to retrieve an existing query's state. If the query does not - * exist, `undefined` is returned. - * @param queryKey - The query key of the query to read. - * @returns The query's state, or `undefined` if no query with this key exists. - * @example - * ```ts - * const state = queryClient.getQueryState(['posts']) - * console.log(state?.dataUpdatedAt) - * ``` - */ - getQueryState< - TQueryFnData = unknown, - TError = DefaultError, - TTaggedQueryKey extends QueryKey = QueryKey, - TInferredQueryFnData = InferDataFromTag, - TInferredError = InferErrorFromTag, - >( - queryKey: TTaggedQueryKey, - ): QueryState | undefined { - const options = this.defaultQueryOptions({ queryKey }) - return this.#queryCache.get( - options.queryHash, - )?.state - } - - /** - * Removes queries from the cache that match the given filters. Unlike - * {@link QueryClient#invalidateQueries} or {@link QueryClient#refetchQueries}, this removes - * matching queries from the cache instead of refetching them. Without filters, every query in - * the cache is removed. - * @param filters - The filters that select which queries to remove. Without filters, every query - * is removed. - * @example - * ```ts - * queryClient.removeQueries({ queryKey: ['posts'], exact: true }) - * ``` - */ - removeQueries( - filters?: QueryFilters, - ): void { - const queryCache = this.#queryCache - notifyManager.batch(() => { - queryCache.findAll(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 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 queryClient.resetQueries({ queryKey: ['posts'], exact: true }) - * ``` - */ - resetQueries( - filters?: QueryFilters, - options?: ResetOptions, - ): Promise { - const queryCache = this.#queryCache - - return notifyManager.batch(() => { - const matched = queryCache.findAll(filters) - const queriesToRefetch = new Set(matched) - matched.forEach((query) => { - query.reset() - }) - return this.refetchQueries( - { - 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 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 queryClient.cancelQueries({ queryKey: ['posts'], exact: true }) - * ``` - */ - cancelQueries( - filters?: QueryFilters, - cancelOptions: CancelOptions = {}, - ): Promise { - const defaultedCancelOptions = { revert: true, ...cancelOptions } - - const promises = notifyManager.batch(() => - this.#queryCache - .findAll(filters) - .map((query) => query.cancel(defaultedCancelOptions)), - ) - - return Promise.all(promises).then(noop, noop) - } - - /** - * Marks queries matching the given filters as invalidated. Unlike - * {@link QueryClient#removeQueries}, invalidated queries stay in the cache. - * - * Unless `filters.refetchType` is `'none'`, matching queries are then refetched via - * {@link QueryClient#refetchQueries}, using `filters.refetchType` if set, otherwise - * `filters.type`, otherwise `'active'`. - * @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 QueryClient#refetchQueries}, e.g. `cancelRefetch` and - * `throwOnError`. - * @returns A promise that resolves once the refetch settles, or immediately if `refetchType` is - * `'none'`. - * @example - * ```ts - * await queryClient.invalidateQueries({ queryKey: ['posts'], refetchType: 'active' }) - * ``` - */ - invalidateQueries( - filters?: InvalidateQueryFilters, - options: InvalidateOptions = {}, - ): Promise { - return notifyManager.batch(() => { - this.#queryCache.findAll(filters).forEach((query) => { - query.invalidate() - }) - - if (filters?.refetchType === 'none') { - return Promise.resolve() - } - return this.refetchQueries( - { - ...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 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 queryClient.refetchQueries({ queryKey: ['posts'], type: 'active' }) - * ``` - */ - refetchQueries( - filters?: RefetchQueryFilters, - options: RefetchOptions = {}, - ): Promise { - const fetchOptions = { - ...options, - cancelRefetch: options.cancelRefetch ?? true, - } - const promises = notifyManager.batch(() => - this.#queryCache - .findAll(filters) - .filter((query) => !query.isDisabled() && !query.isStatic()) - .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) - } - - /** - * Asynchronous method to fetch and cache a query, resolving with the data or throwing with - * the error. - * - * If the query already exists in the cache and its data is not stale (per the given - * `staleTime`), the cached data is returned without fetching. Otherwise, the query is fetched - * and the promise resolves once the fetch settles. If a `select` function is provided, it is - * applied to the data in both cases (cached or freshly fetched) before it is returned. - * - * Unlike a reactive observer, retries are disabled by default here (`retry: false`) unless - * explicitly configured, since there is no component to catch a thrown error and retry through - * re-render. - * - * The accepted options are `QueryObserverOptions` minus the fields that only make sense for a - * reactive observer — `enabled`, `refetchInterval`, `refetchIntervalInBackground`, - * `refetchOnWindowFocus`, `refetchOnReconnect`, `refetchOnMount`, `retryOnMount`, - * `notifyOnChangeProps`, `throwOnError`, `suspense`, and `placeholderData` are not part of this - * method's options. - * Shared query options can contain `skipToken` as their `queryFn`. If the supplied options contain - * the token, the call skips fetching and resolves with existing data regardless of freshness. - * It applies `select` when data exists and resolves to `undefined` on a cache miss. - * Use {@link QueryClient#getQueryData} to read the cache directly. - * @param options - The query options, including the `queryKey` and the `queryFn` used if the - * query needs to fetch. - * @returns A promise that resolves to the data, 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 queryClient.query({ queryKey, queryFn, staleTime: 10000 }) - * } catch (error) { - * console.log(error) - * } - * ``` - */ - query< - TQueryFnData, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, - >( - options: WithoutSkipToken< - QueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - > - >, - ): Promise - query< - TQueryFnData, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, - >( - options: QueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - >, - ): Promise - async query< - TQueryFnData, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, - >( - options: QueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - >, - ): Promise { - const defaultedOptions = this.defaultQueryOptions(options) - let queryData: TQueryData - - if (options.queryFn === skipToken) { - const cachedData = this.#queryCache.get< - TQueryFnData, - TError, - TQueryData, - TQueryKey - >(defaultedOptions.queryHash)?.state.data - if (cachedData === undefined) return undefined - queryData = cachedData - } else { - // https://github.com/tannerlinsley/react-query/issues/652 - if (defaultedOptions.retry === undefined) { - defaultedOptions.retry = false - } - - const query = this.#queryCache.build(this, defaultedOptions) - - const isStale = query.isStaleByTime( - resolveQueryValue(defaultedOptions.staleTime, query), - ) - - queryData = isStale - ? await query.fetch(defaultedOptions) - : (query.state.data as TQueryData) - } - - const select = defaultedOptions.select - - if (select) { - return select(queryData) - } - - return queryData as unknown as TData - } - - /** - * 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 QueryClient#getQueryData} - * to read the cache directly. - * @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 queryClient.infiniteQuery({ - * queryKey, - * queryFn, - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextCursor, - * }) - * console.log(data.pages) - * } catch (error) { - * console.log(error) - * } - * ``` - */ - infiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: WithoutSkipToken< - InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - > - >, - ): Promise< - Array extends Array> - ? InfiniteData - : TData - > - infiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - ): Promise< - | undefined - | (Array extends Array> - ? InfiniteData - : TData) - > - infiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, - >( - options: InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - ): Promise< - | undefined - | (Array extends Array> - ? InfiniteData - : TData) - > { - return this.query({ ...options, _type: 'infinite' } as any) - } - - /** - * Resumes mutations that were paused because there was no network connection. Does nothing - * (resolving immediately) if the client is currently offline. - * @returns A promise that resolves once the resumed mutations have settled. - * @example - * ```ts - * import { QueryClient } from '@tanstack/react-query-no-core' - * - * const queryClient = new QueryClient() - * await queryClient.resumePausedMutations() - * ``` - */ - resumePausedMutations(): Promise { - if (onlineManager.isOnline()) { - return this.#mutationCache.resumePausedMutations() - } - return Promise.resolve() - } - - /** - * Returns the query cache this client is connected to. - * @returns The {@link QueryCache} instance. - * @example - * ```ts - * import { QueryClient } from '@tanstack/react-query-no-core' - * - * const queryClient = new QueryClient() - * const queryCache = queryClient.getQueryCache() - * const queries = queryCache.findAll({ queryKey: ['posts'] }) - * ``` - */ - getQueryCache(): QueryCache { - return this.#queryCache - } - - /** - * Returns the mutation cache this client is connected to. - * @returns The {@link MutationCache} instance. - * @example - * ```ts - * import { QueryClient } from '@tanstack/react-query-no-core' - * - * const queryClient = new QueryClient() - * const mutationCache = queryClient.getMutationCache() - * const mutations = mutationCache.findAll({ status: 'pending' }) - * ``` - */ - getMutationCache(): MutationCache { - return this.#mutationCache - } - - /** - * Returns the default options that were set when creating the client, or via - * {@link QueryClient#setDefaultOptions}. - * @returns The client's current default options. - * @example - * ```ts - * import { QueryClient } from '@tanstack/react-query-no-core' - * - * const queryClient = new QueryClient() - * const defaultOptions = queryClient.getDefaultOptions() - * ``` - */ - getDefaultOptions(): DefaultOptions { - return this.#defaultOptions - } - - /** - * Dynamically sets the default options for this client, overwriting any previously defined - * default options. - * @param options - The new default options for queries and mutations. - * @see {@link QueryClient#getDefaultOptions} - * @example - * ```ts - * import { QueryClient } from '@tanstack/react-query-no-core' - * - * const queryClient = new QueryClient() - * queryClient.setDefaultOptions({ - * queries: { - * staleTime: Infinity, - * }, - * }) - * ``` - */ - setDefaultOptions(options: DefaultOptions): void { - this.#defaultOptions = options - } - - /** - * Sets default options for queries whose query key partially matches the given `queryKey`. - * - * If several registered query defaults match a given query key, they are merged together in - * registration order by {@link QueryClient#getQueryDefaults}, so register defaults from the - * most generic key to the least generic one — more specific defaults should be registered - * after more generic ones so they take precedence. - * @param queryKey - The query key that query keys are partially matched against. - * @param options - The default options applied to matching queries. - * @example - * ```ts - * queryClient.setQueryDefaults(['posts'], { queryFn: fetchPosts }) - * - * await queryClient.query({ queryKey: ['posts'] }) - * ``` - */ - setQueryDefaults< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - >( - queryKey: QueryKey, - options: Partial< - OmitKeyof< - QueryObserverOptionsBase, - 'queryKey' - > - >, - ): void { - this.#queryDefaults.set(queryKey, options, this.#queryCache.config.queryKey) - } - - /** - * Returns the default options registered for queries whose query key partially matches the - * given `queryKey`, via {@link QueryClient#setQueryDefaults}. If multiple registered defaults - * match, they are merged together in registration order. - * @param queryKey - The query key to look up registered defaults for. - * @returns The merged default options of every registration that matches, or an empty object if - * none match. - * @example - * ```ts - * const defaultOptions = queryClient.getQueryDefaults(['posts']) - * ``` - */ - getQueryDefaults( - queryKey: QueryKey, - ): OmitKeyof, 'queryKey'> { - return this.#queryDefaults.get(queryKey, this.#queryCache.config.queryKey) - } - - /** - * Sets default options for mutations whose mutation key partially matches the given - * `mutationKey`. As with {@link QueryClient#setQueryDefaults}, the order of registration - * matters when several registered defaults match the same mutation key. - * @param mutationKey - The mutation key that mutation keys are partially matched against. - * @param options - The default options applied to matching mutations. - * @see {@link QueryClient#getMutationDefaults} - * @example - * ```ts - * queryClient.setMutationDefaults(['addPost'], { mutationFn: addPost }) - * ``` - */ - setMutationDefaults< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, - >( - mutationKey: MutationKey, - options: OmitKeyof< - MutationObserverOptions, - 'mutationKey' - >, - ): void { - this.#mutationDefaults.set( - mutationKey, - options, - this.#mutationCache.config.mutationKey, - ) - } - - /** - * Returns the default options registered for mutations whose mutation key partially matches - * the given `mutationKey`, via {@link QueryClient#setMutationDefaults}. If multiple registered - * defaults match, they are merged together in registration order. - * @param mutationKey - The mutation key to look up registered defaults for. - * @returns The merged default options of every registration that matches, or an empty object if - * none match. - * @example - * ```ts - * const defaultOptions = queryClient.getMutationDefaults(['addPost']) - * ``` - */ - getMutationDefaults( - mutationKey: MutationKey, - ): OmitKeyof, 'mutationKey'> { - return this.#mutationDefaults.get( - mutationKey, - this.#mutationCache.config.mutationKey, - ) - } - - /** - * Called by framework adapters (e.g. inside `useQuery`) to resolve the options passed by the - * caller into their final, defaulted form: merging the client's own `defaultOptions.queries`, - * then `queryClient.setQueryDefaults` for the given `queryKey`, then the caller's options on - * top. A no-op if the options are already defaulted (`_defaulted: true`). - * @param options - The query options passed by the caller. - * @returns The defaulted options, with `queryHash` and dependent defaults (e.g. - * `refetchOnReconnect`) filled in. - */ - defaultQueryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, - >( - options: QueryObserverOptionsBase< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - >, - ): DefaultedQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - > { - if (options._defaulted) { - return options as DefaultedQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - > - } - - const queryDefaults = this.getQueryDefaults(options.queryKey) - const defaultedOptions = { - ...this.#defaultOptions.queries, - ...queryDefaults, - ...options, - _defaulted: true, - } - - if (defaultedOptions.queryFn === defaultQueryFn) { - defaultedOptions.queryFn = - 'queryFn' in queryDefaults - ? queryDefaults.queryFn - : this.#defaultOptions.queries?.queryFn - } - - if (!defaultedOptions.queryHash) { - defaultedOptions.queryHash = hashKeyByOptions( - defaultedOptions.queryKey, - this.#queryCache.config.queryKey, - ) - } - - // dependent default values - if (defaultedOptions.refetchOnReconnect === undefined) { - defaultedOptions.refetchOnReconnect = - defaultedOptions.networkMode !== 'always' - } - if (defaultedOptions.throwOnError === undefined) { - defaultedOptions.throwOnError = !!defaultedOptions.suspense - } - - if (!defaultedOptions.networkMode && defaultedOptions.persister) { - defaultedOptions.networkMode = 'offlineFirst' - } - - if (defaultedOptions.queryFn === skipToken) { - defaultedOptions.enabled = false - } - - return defaultedOptions as DefaultedQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam - > - } - - /** - * The mutation counterpart of {@link QueryClient#defaultQueryOptions}. Called by framework - * adapters (e.g. inside `useMutation`) to merge the client's `defaultOptions.mutations`, then - * `queryClient.setMutationDefaults` for the given `mutationKey`, then the caller's options on - * top. A no-op if the options are already defaulted (`_defaulted: true`). - * @param options - The mutation options passed by the caller. - * @returns The defaulted options. - */ - defaultMutationOptions>( - options?: T, - ): T { - if (options?._defaulted) { - return options - } - return { - ...this.#defaultOptions.mutations, - ...(options?.mutationKey && - this.getMutationDefaults(options.mutationKey)), - ...options, - _defaulted: true, - } as T - } - - /** - * Clears both the query cache and the mutation cache this client is connected to. - * This clears their garbage collection timers and cancels in-flight query fetches. - * Running mutations continue to execute. - * @example - * ```ts - * import { QueryClient } from '@tanstack/react-query-no-core' - * - * const queryClient = new QueryClient() - * queryClient.clear() - * ``` - */ - clear(): void { - this.#queryCache.clear() - this.#mutationCache.clear() - } -} diff --git a/packages/react-query-no-core/src/runtime/queryObserver.ts b/packages/react-query-no-core/src/runtime/queryObserver.ts deleted file mode 100644 index b36532fa9fb..00000000000 --- a/packages/react-query-no-core/src/runtime/queryObserver.ts +++ /dev/null @@ -1,1036 +0,0 @@ -import { isServer as isServerEnvironment } from './environmentManager' -import { focusManager } from './focusManager' -import { notifyManager } from './notifyManager' -import { fetchState } from './query' -import { Subscribable } from './subscribable' -import { timeoutManager } from './timeoutManager' -import { - isValidTimeout, - noop, - replaceData, - resolveQueryValue, - shallowEqualObjects, - timeUntilStale, -} from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - ObserverFetchOptions, - ProjectionFailure, - QueryObserverListener, - QueryObserverResultReader, -} from '@tanstack/query-types/bindings' -import type { Query, QueryState } from './query' -import type { QueryClient } from './queryClient' -import type { QueryRuntime } from './runtimeBinding' -import type { ManagedTimerId } from './timeoutManager' -import type { - DefaultError, - DefaultedQueryObserverOptions, - PlaceholderDataFunction, - QueryKey, - QueryObserverBaseResult, - QueryObserverOptionsBase, - QueryObserverResult, - RefetchOptions, -} from './types' - -/** {@inheritDoc Shared.QueryObserverResultContext} */ -export type QueryObserverResultContext< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey extends QueryKey, -> = Shared.QueryObserverResultContext< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey -> - -/** {@inheritDoc Shared.ObserverOptionsInput} */ -export type ObserverOptionsInput< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = Shared.ObserverOptionsInput< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey -> - -/** - * A `QueryObserver` watches a single query in the `QueryCache` and computes a - * `QueryObserverResult` from its state, recomputing and notifying subscribers - * whenever the underlying query (or the observer's options) changes. It is - * the primitive that framework adapters (e.g. `useQuery`) build their hooks - * on top of, but it can also be used directly to observe and switch between - * queries outside of any framework. - * @example - * ```ts - * const observer = new QueryObserver(queryClient, { - * queryKey: ['posts'], - * queryFn: fetchPosts, - * }) - * - * const unsubscribe = observer.subscribe((result) => { - * console.log(result.data) - * }) - * ``` - */ -export class QueryObserver< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> extends Subscribable> { - #client: QueryClient - #currentQuery: Query = undefined! - #currentQueryInitialState: QueryState = undefined! - #currentResult: QueryObserverResult = undefined! - #resultContext: QueryObserverResultContext< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - > = {} - // This property keeps track of the last query with defined data. - // It will be used to pass the previous data and query to the placeholder function between renders. - #lastQueryWithDefinedData?: Query - #staleTimeoutId?: ManagedTimerId - #refetchIntervalId?: ManagedTimerId - #currentRefetchInterval?: number | false - #trackedProps = new Set() - - constructor( - client: QueryClient, - public options: ObserverOptionsInput< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >, - ) { - super() - - this.#client = client - - this.bindMethods() - this.setOptions(options) - } - - /** - * Binds the methods of the result (`refetch`) to the observer, so they keep working when destructured - * from it. Subclasses override it to bind their own result methods as well. - */ - protected bindMethods(): void { - this.refetch = this.refetch.bind(this) - } - - protected override onSubscribe(): void { - if (this.listeners.size === 1) { - this.#currentQuery.addObserver(this) - - if (shouldFetchOnMount(this.#currentQuery, this.options)) { - this.#executeFetch() - } else { - this.updateResult() - } - - this.#updateTimers() - } - } - - protected override onUnsubscribe(): void { - if (!this.hasListeners()) { - this.destroy() - } - } - - /** - * Returns whether the observed query is currently stale and configured - * (via the `refetchOnReconnect` option) to refetch when the network - * reconnects. - * @returns `true` if the observer should refetch the query on reconnect. - */ - shouldFetchOnReconnect(): boolean { - return shouldFetchOn( - this.#currentQuery, - this.options, - this.options.refetchOnReconnect, - ) - } - - /** - * Returns whether the observed query is currently stale and configured - * (via the `refetchOnWindowFocus` option) to refetch when the window - * regains focus. - * @returns `true` if the observer should refetch the query on window focus. - */ - shouldFetchOnWindowFocus(): boolean { - return shouldFetchOn( - this.#currentQuery, - this.options, - this.options.refetchOnWindowFocus, - ) - } - - /** - * Stops observing the current query: clears all listeners, cancels the - * stale and refetch-interval timers, and removes this observer from the - * query it was observing. - */ - destroy(): void { - this.listeners = new Set() - this.#clearStaleTimeout() - this.#clearRefetchInterval() - this.#currentQuery.removeObserver(this) - } - - /** - * Updates the observer's options. This will re-resolve the query being - * observed (switching to a different query if the `queryKey` changed), - * trigger a fetch if the new options require one and the observer has - * subscribers, recompute the current result, and reschedule the stale and - * refetch-interval timers as needed. - * @param options - The new observer options. They are defaulted with {@link - * QueryClient#defaultQueryOptions} before being applied. - * @throws {Error} If `enabled` is neither a boolean nor a function. - * @example - * ```ts - * observer.setOptions({ queryKey: ['posts', 1], queryFn: () => fetchPost(1) }) - * // later: switch to a different query, reusing the same observer - * observer.setOptions({ queryKey: ['posts', 2], queryFn: () => fetchPost(2) }) - * ``` - */ - setOptions( - options: ObserverOptionsInput< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >, - ): void { - const prevOptions = this.options - const prevQuery = this.#currentQuery - - this.options = this.#client.defaultQueryOptions(options) - - if ( - this.options.enabled !== undefined && - typeof this.options.enabled !== 'boolean' && - typeof this.options.enabled !== 'function' && - typeof resolveQueryValue(this.options.enabled, this.#currentQuery) !== - 'boolean' - ) { - throw new Error( - 'Expected enabled to be a boolean or a callback that returns a boolean', - ) - } - - this.#updateQuery() - this.#currentQuery.setOptions(this.options) - - if ( - prevOptions._defaulted && - !shallowEqualObjects(this.options, prevOptions) - ) { - this.#client.getQueryCache().notify({ - type: 'observerOptionsUpdated', - query: this.#currentQuery, - observer: this, - }) - } - - const mounted = this.hasListeners() - - // Fetch if there are subscribers - if ( - mounted && - shouldFetchOptionally( - this.#currentQuery, - prevQuery, - this.options, - prevOptions, - ) - ) { - this.#executeFetch() - } - - // Update result - this.updateResult() - - // Update stale interval if needed - if ( - mounted && - (this.#currentQuery !== prevQuery || - resolveQueryValue(this.options.enabled, this.#currentQuery) !== - resolveQueryValue(prevOptions.enabled, this.#currentQuery) || - resolveQueryValue(this.options.staleTime, this.#currentQuery) !== - resolveQueryValue(prevOptions.staleTime, this.#currentQuery)) - ) { - this.#updateStaleTimeout() - } - - const nextRefetchInterval = this.#computeRefetchInterval() - - // Update refetch interval if needed - if ( - mounted && - (this.#currentQuery !== prevQuery || - resolveQueryValue(this.options.enabled, this.#currentQuery) !== - resolveQueryValue(prevOptions.enabled, this.#currentQuery) || - nextRefetchInterval !== this.#currentRefetchInterval) - ) { - this.#updateRefetchInterval(nextRefetchInterval) - } - } - - /** - * Creates a result reader that captures the supplied query options. - * Reads cache the complete result locally and retain its reference while its - * fields are unchanged. They do not update this observer's committed result, - * options, or selection state. Missing queries are built in the query cache. - * Call `commit` after the render commits to apply the options and reuse the - * reader's computation. An abandoned reader needs no cleanup. - * @param options - The defaulted options used to read and commit the query result. - * @returns A reader with local snapshot and computation caches. - */ - createResultReader( - options: DefaultedQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >, - ): QueryObserverResultReader> { - const readerOptions = { ...options } - const { select, structuralSharing } = readerOptions - const context = { ...this.#resultContext } - let result = this.#currentResult - - const getSnapshot = () => { - const query = this.#client - .getQueryCache() - .build(this.#client, readerOptions) - const { selection, selected } = this.#resultContext - const input = query.state.data - - // A query update may already have selected this data. - if ( - input !== undefined && - select && - shallowEqualObjects( - { input, select, structuralSharing }, - selection?.key, - ) - ) { - context.selection = selection - context.selected = selected - } - - const nextResult = this.createResult( - query, - readerOptions, - context, - result, - ) - if (!shallowEqualObjects(nextResult, result)) { - result = nextResult - } - return result - } - - return { - getSnapshot, - commit: () => { - // Reuse selections computed since the last read. - getSnapshot() - this.#resultContext = { ...context } - this.setOptions(readerOptions) - }, - } - } - - /** - * Returns the most recently computed `QueryObserverResult` for the - * observed query. This is a point-in-time read; to be notified of updates - * as they happen, subscribe to the observer instead (its inherited - * `subscribe` method). - * @returns The observer's latest result. - * @example - * ```ts - * const result = observer.getCurrentResult() - * console.log(result.status, result.data) - * ``` - */ - getCurrentResult(): QueryObserverResult { - return this.#currentResult - } - - /** - * Wraps a `QueryObserverResult` in a `Proxy` that records which properties are read, via - * {@link QueryObserver#trackProp} (and an optional `onPropTracked` callback). Used by framework - * adapters when `notifyOnChangeProps` is not set, to implement its default "only re-render on - * properties you actually read" behavior. - * @param result - The result to wrap. - * @param onPropTracked - Called with the name of each property that is read. - * @returns A proxy of `result` that tracks property reads. - */ - trackResult( - result: QueryObserverResult, - onPropTracked?: (key: keyof QueryObserverResult) => void, - ): QueryObserverResult { - return new Proxy(result, { - get: (target, key) => { - this.trackProp(key as keyof QueryObserverResult) - onPropTracked?.(key as keyof QueryObserverResult) - return Reflect.get(target, key) - }, - }) - } - - /** - * Records that the given `QueryObserverResult` property was read, so a subsequent update only - * notifies this observer if a tracked property actually changed. The proxy returned by - * {@link QueryObserver#trackResult} records reads on this observer. For `useQueries`, - * `QueriesObserver` records the same read on every observer in the group. - * @param key - The name of the property that was read. - */ - trackProp(key: keyof QueryObserverResult) { - this.#trackedProps.add(key) - } - - /** - * Returns the `Query` instance this observer is currently observing. - * @returns The observed query. - */ - getCurrentQuery(): Query { - return this.#currentQuery - } - - /** - * Refetches the observed query and returns a promise that resolves with - * the resulting `QueryObserverResult`. - * @param options - Set `cancelRefetch` to `false` to keep a running fetch instead of cancelling - * it, and `throwOnError` to `true` to reject when the refetch fails. - * @returns A promise that resolves with the result after the refetch. - * @example - * ```ts - * const result = await observer.refetch({ cancelRefetch: false }) - * console.log(result.data) - * ``` - */ - refetch( - options: RefetchOptions = {}, - ): Promise> { - return this.fetch(options) - } - - /** - * 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 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 observer.fetchOptimistic({ - * queryKey: ['posts', 2], - * queryFn: () => fetchPost(2), - * }) - * console.log(result.data) - * ``` - */ - fetchOptimistic( - options: ObserverOptionsInput< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >, - ): Promise> { - const defaultedOptions = this.#client.defaultQueryOptions(options) - - const query = this.#client - .getQueryCache() - .build(this.#client, defaultedOptions) - - const cached = Promise.withResolvers>() - const unsubscribe = this.#client.getQueryCache().subscribe((event) => { - if ( - event.type === 'updated' && - event.query.queryHash === query.queryHash && - query.state.data !== undefined - ) { - unsubscribe() - cached.resolve(this.createResult(query, defaultedOptions)) - } - }) - - return Promise.race([ - query - .fetch(defaultedOptions) - .then(() => { - const result = this.createResult(query, defaultedOptions) - // Resolve the cache wait when the fetch succeeds. - cached.resolve(result) - return result - }) - .finally(unsubscribe), - cached.promise, - ]) - } - - /** - * Fetches the observed query and updates the result once the fetch settles. Used by `refetch` and, - * in `InfiniteQueryObserver`, to fetch more pages. - * @param fetchOptions - Options for this fetch. `cancelRefetch` defaults to `true`. - * @returns A promise that resolves with the updated result. - */ - protected fetch( - fetchOptions: ObserverFetchOptions, - ): Promise> { - return this.#executeFetch({ - ...fetchOptions, - cancelRefetch: fetchOptions.cancelRefetch ?? true, - }).then(() => { - this.updateResult() - return this.#currentResult - }) - } - - #executeFetch( - fetchOptions?: Omit, - ): Promise { - // Make sure we reference the latest query as the current one might have been removed - this.#updateQuery() - - // Fetch - let promise: Promise = this.#currentQuery.fetch( - this.options, - fetchOptions, - ) - - if (!fetchOptions?.throwOnError) { - promise = promise.catch(noop) - } - - return promise - } - - #shouldScheduleTimer(timeout: unknown): timeout is number { - return ( - !isServerEnvironment() && - resolveQueryValue(this.options.enabled, this.#currentQuery) !== false && - isValidTimeout(timeout) - ) - } - - #updateStaleTimeout(): void { - this.#clearStaleTimeout() - const staleTime = resolveQueryValue( - this.options.staleTime, - this.#currentQuery, - ) - - if (this.#currentResult.isStale || !this.#shouldScheduleTimer(staleTime)) { - return - } - - const time = timeUntilStale(this.#currentResult.dataUpdatedAt, staleTime) - - // The timeout is sometimes triggered 1 ms before the stale time expiration. - // To mitigate this issue we always add 1 ms to the timeout. - const timeout = time + 1 - - this.#staleTimeoutId = timeoutManager.setTimeout(() => { - if (!this.#currentResult.isStale) { - this.updateResult() - } - }, timeout) - } - - #computeRefetchInterval() { - return ( - resolveQueryValue(this.options.refetchInterval, this.#currentQuery) ?? - false - ) - } - - #updateRefetchInterval(nextInterval: number | false): void { - this.#clearRefetchInterval() - - this.#currentRefetchInterval = nextInterval - - if ( - this.#currentRefetchInterval === 0 || - !this.#shouldScheduleTimer(this.#currentRefetchInterval) - ) { - return - } - - this.#refetchIntervalId = timeoutManager.setInterval(() => { - if ( - this.options.refetchIntervalInBackground || - focusManager.isFocused() - ) { - this.#executeFetch() - } - }, this.#currentRefetchInterval) - } - - #updateTimers(): void { - this.#updateStaleTimeout() - this.#updateRefetchInterval(this.#computeRefetchInterval()) - } - - #clearStaleTimeout(): void { - if (this.#staleTimeoutId !== undefined) { - timeoutManager.clearTimeout(this.#staleTimeoutId) - this.#staleTimeoutId = undefined - } - } - - #clearRefetchInterval(): void { - if (this.#refetchIntervalId !== undefined) { - timeoutManager.clearInterval(this.#refetchIntervalId) - this.#refetchIntervalId = undefined - } - } - - #resolvePlaceholder( - options: QueryObserverOptionsBase< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >, - previousResultData: TData | undefined, - context = this.#resultContext, - ) { - const { placeholderData, structuralSharing } = options - const memo = context.placeholder - const previousQuery = this.#lastQueryWithDefinedData - const previousState = previousQuery?.state - const key = { - placeholderData, - structuralSharing, - previousQuery, - previousState, - previousOptions: previousQuery?.options, - } - if (shallowEqualObjects(key, memo?.key)) { - return memo - } - - let failure: ProjectionFailure | undefined - let input: TQueryData | undefined - let sourceQuery: typeof previousQuery - if (typeof placeholderData === 'function') { - try { - input = ( - placeholderData as unknown as PlaceholderDataFunction< - TQueryFnData, - TError, - TQueryData, - TQueryKey - > - )(previousState?.data, previousQuery) - } catch (error) { - failure = { error: error as TError, errorUpdatedAt: Date.now() } - } - if (previousState?.data !== undefined) { - sourceQuery = previousQuery - } - } else { - input = placeholderData - } - - if (input !== undefined) { - input = replaceData( - previousResultData, - input as unknown, - options, - ) as TQueryData - } - return input !== undefined || failure - ? { key, input, sourceQuery, failure } - : undefined - } - - /** - * Computes the result for a query and options from the query's state, applying `select`, - * `placeholderData`, and the derived flags. Subclasses override it to add their own fields. - * @param query - The query to compute the result for. - * @param options - The observer options to compute the result with. - * @param context - The selection and placeholder state reused between computations. - * @param prevResult - The previous result used for structural sharing. - * @returns The computed result. - */ - protected createResult( - query: Query, - options: QueryObserverOptionsBase< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >, - context = this.#resultContext, - prevResult = this.#currentResult as - | QueryObserverResult - | undefined, - ): QueryObserverResult { - const prevQuery = this.#currentQuery - const prevOptions = this.options - const queryChange = query !== prevQuery - const queryInitialState = queryChange - ? query.state - : this.#currentQueryInitialState - - const { state } = query - const fetchOptimistically = - options._optimisticResults && - (this.hasListeners() - ? shouldFetchOptionally(query, prevQuery, options, prevOptions) - : shouldFetchOnMount(query, options)) - const newState = fetchOptimistically - ? { ...state, ...fetchState(state.data, query.options) } - : state - const fetchStatus = - options._optimisticResults === 'isRestoring' - ? 'idle' - : newState.fetchStatus - const selectedQuery = context.selected?.query - if (selectedQuery && selectedQuery.state.data === undefined) { - context.selected = undefined - // Keep a cached error stable, but a successful selection needs its data. - if (!context.selection?.failure) { - context.selection = undefined - } - } - - const { placeholderData, select, structuralSharing } = options - if ( - newState.data === undefined && - newState.status === 'pending' && - placeholderData !== undefined - ) { - context.placeholder = this.#resolvePlaceholder( - options, - prevResult?.data, - context, - ) - } else { - context.placeholder = undefined - } - - const placeholder = context.placeholder - const input = placeholder ? placeholder.input : newState.data - if (!select || input === undefined) { - context.selection = undefined - } else { - const key = { input, select, structuralSharing } - if (!shallowEqualObjects(key, context.selection?.key)) { - try { - const data = replaceData(prevResult?.data, select(input), options) - context.selected = { - data, - query: placeholder ? placeholder.sourceQuery : query, - } - context.selection = { key } - } catch (error) { - context.selection = { - key, - failure: { - error: error as TError, - errorUpdatedAt: Date.now(), - }, - } - } - } - } - - const failure = placeholder?.failure ?? context.selection?.failure - const data = context.selection - ? context.selected?.data - : (input as unknown as TData | undefined) - const isPlaceholderData = - placeholder !== undefined && input !== undefined && !failure - const { error, errorUpdatedAt } = failure ?? newState - const status = failure - ? 'error' - : isPlaceholderData - ? 'success' - : newState.status - const isFetching = fetchStatus === 'fetching' - const isPending = status === 'pending' - const isError = status === 'error' - - const isLoading = isPending && isFetching - const hasData = data !== undefined - - const result: QueryObserverBaseResult = { - status, - fetchStatus, - isPending, - isSuccess: status === 'success', - isError, - isLoading, - data, - dataUpdatedAt: newState.dataUpdatedAt, - error, - errorUpdatedAt, - failureCount: newState.fetchFailureCount, - failureReason: newState.fetchFailureReason, - errorUpdateCount: newState.errorUpdateCount, - isFetched: query.isFetched(), - isFetchedAfterMount: - newState.dataUpdateCount > queryInitialState.dataUpdateCount || - newState.errorUpdateCount > queryInitialState.errorUpdateCount, - isFetching, - isRefetching: isFetching && !isPending, - isLoadingError: isError && !hasData, - isPaused: fetchStatus === 'paused', - isPlaceholderData, - isRefetchError: isError && hasData, - isStale: isStale(query, options), - refetch: this.refetch, - isEnabled: resolveQueryValue(options.enabled, query) !== false, - } - - const nextResult = result as QueryObserverResult - - return nextResult - } - - /** - * Recomputes and stores the current result from the current query/options, notifying listeners - * if it changed. Framework adapters call this right after subscribing to make sure no query - * update was missed in the gap between creating the observer and subscribing to it. - */ - updateResult(): void { - const prevResult = this.#currentResult as - | QueryObserverResult - | undefined - - const nextResult = this.createResult(this.#currentQuery, this.options) - - if (this.#currentQuery.state.data !== undefined) { - this.#lastQueryWithDefinedData = this.#currentQuery - } - - // Only notify and update result if something has changed - if (shallowEqualObjects(nextResult, prevResult)) { - return - } - - this.#currentResult = nextResult - - const shouldNotifyListeners = (): boolean => { - if (!prevResult) { - return true - } - - const { notifyOnChangeProps } = this.options - - if ( - notifyOnChangeProps === 'all' || - (notifyOnChangeProps !== 'none' && !this.#trackedProps.size) - ) { - return true - } - - if ( - this.options.throwOnError && - this.#currentResult.error !== prevResult.error - ) { - return true - } - - if (notifyOnChangeProps === 'none') { - return false - } - - for (const key of this.#trackedProps) { - if (this.#currentResult[key] !== prevResult[key]) { - return true - } - } - return false - } - - const notifyListeners = shouldNotifyListeners() - - notifyManager.batch(() => { - // First, trigger the listeners - if (notifyListeners) { - this.listeners.forEach((listener) => { - listener(this.#currentResult) - }) - } - - // Then the cache listeners - this.#client.getQueryCache().notify({ - query: this.#currentQuery, - type: 'observerResultsUpdated', - }) - }) - } - - #updateQuery(): void { - const query = this.#client.getQueryCache().build(this.#client, this.options) - - if (query === this.#currentQuery) { - return - } - - const prevQuery = this.#currentQuery as - | Query - | undefined - this.#currentQuery = query - this.#currentQueryInitialState = query.state - - if (this.hasListeners()) { - prevQuery?.removeObserver(this) - query.addObserver(this) - } - } - - /** - * Updates the observer's result when the observed query changes, and reschedules its timers if it - * has listeners. - * @internal - */ - onQueryUpdate(): void { - this.updateResult() - - if (this.hasListeners()) { - this.#updateTimers() - } - } -} - -/** - * Checks whether a query has no data yet and should do its initial load when an observer mounts. - * @param query - The query to check. - * @param options - The observer options. - * @returns `true` if the query is enabled, has no data, and isn't in an error state with - * `retryOnMount: false`. - */ -function shouldLoadOnMount( - query: Query, - options: QueryObserverOptionsBase, -): boolean { - return ( - resolveQueryValue(options.enabled, query) !== false && - query.state.data === undefined && - !( - query.state.status === 'error' && - resolveQueryValue(options.retryOnMount, query) === false - ) - ) -} - -/** - * Checks whether a query should fetch when an observer mounts: either for its initial load, or - * because it has data and `refetchOnMount` asks for a refetch. - * @param query - The query to check. - * @param options - The observer options. - * @returns `true` if the query should fetch on mount. - */ -function shouldFetchOnMount( - query: Query, - options: QueryObserverOptionsBase, -): boolean { - return ( - shouldLoadOnMount(query, options) || - (query.state.data !== undefined && - shouldFetchOn(query, options, options.refetchOnMount)) - ) -} - -/** - * Checks whether a query should fetch for a `refetchOnMount`, `refetchOnWindowFocus`, or - * `refetchOnReconnect` option. - * @param query - The query to check. - * @param options - The observer options. - * @param field - The value of the option to check. - * @returns `true` if the query is enabled, not static, and the option is `'always'`, or is not - * `false` and the query is stale. - */ -function shouldFetchOn( - query: Query, - options: QueryObserverOptionsBase, - field: (typeof options)['refetchOnMount'] & - (typeof options)['refetchOnWindowFocus'] & - (typeof options)['refetchOnReconnect'], -) { - if ( - resolveQueryValue(options.enabled, query) !== false && - resolveQueryValue(options.staleTime, query) !== 'static' - ) { - const value = resolveQueryValue(field, query) - - return value === 'always' || (value !== false && isStale(query, options)) - } - return false -} - -/** - * Checks whether a query should fetch after the observer's options change. - * @param query - The query observed with the new options. - * @param prevQuery - The query observed with the previous options. - * @param options - The new observer options. - * @param prevOptions - The previous observer options. - * @returns `true` if the query changed or was disabled before, it isn't a suspense query in an - * error state, and it is stale. - */ -function shouldFetchOptionally( - query: Query, - prevQuery: Query, - options: QueryObserverOptionsBase, - prevOptions: QueryObserverOptionsBase, -): boolean { - return ( - (query !== prevQuery || - resolveQueryValue(prevOptions.enabled, query) === false) && - (!options.suspense || query.state.status !== 'error') && - isStale(query, options) - ) -} - -/** - * Checks whether a query is stale for the given observer options. - * @param query - The query to check. - * @param options - The observer options, whose `enabled` and `staleTime` are used. - * @returns `true` if the query is enabled and its data is stale for `staleTime`. - */ -function isStale( - query: Query, - options: QueryObserverOptionsBase, -): boolean { - return ( - resolveQueryValue(options.enabled, query) !== false && - query.isStaleByTime(resolveQueryValue(options.staleTime, query)) - ) -} - -export type { QueryObserverResultReader } from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/removable.ts b/packages/react-query-no-core/src/runtime/removable.ts deleted file mode 100644 index d6356c73845..00000000000 --- a/packages/react-query-no-core/src/runtime/removable.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { isServer as isServerEnvironment } from './environmentManager' -import { timeoutManager } from './timeoutManager' -import { isValidTimeout } from './utils' -import type { ManagedTimerId } from './timeoutManager' - -/** - * The base class for cache entries that are garbage collected once nothing is using them — - * `Query` and `Mutation` both extend it. `gcTime` controls how long an unused entry is kept. - */ -export abstract class Removable { - gcTime!: number - #gcTimeout?: ManagedTimerId - - /** - * Clears the pending garbage collection timeout, so the entry is no longer scheduled for removal. - * A subclass may override this to release what it holds on to as well — `Query` also cancels any - * in-flight fetch. - */ - destroy(): void { - this.clearGcTimeout() - } - - /** - * Schedules the entry to be removed from its cache after `gcTime`, replacing any timeout scheduled - * before. Nothing is scheduled if `gcTime` is `Infinity`. - */ - protected scheduleGc(): void { - this.clearGcTimeout() - - if (isValidTimeout(this.gcTime)) { - this.#gcTimeout = timeoutManager.setTimeout(() => { - this.optionalRemove() - }, this.gcTime) - } - } - - /** - * Updates `gcTime`, keeping the longest one seen so far. Without a value, it defaults to 5 minutes - * on the client and `Infinity` on the server. - * @param newGcTime - The `gcTime` from the latest options, if any. - */ - protected updateGcTime(newGcTime: number | undefined): void { - // Default to 5 minutes (Infinity for server-side) if no gcTime is set - this.gcTime = Math.max( - this.gcTime || 0, - newGcTime ?? (isServerEnvironment() ? Infinity : 5 * 60 * 1000), - ) - } - - /** - * Cancels the scheduled removal, if there is one. - */ - protected clearGcTimeout() { - if (this.#gcTimeout !== undefined) { - timeoutManager.clearTimeout(this.#gcTimeout) - this.#gcTimeout = undefined - } - } - - /** - * Called when the garbage collection timeout fires. Subclasses remove the entry from its cache - * unless it is still in use, e.g. because it has observers. - */ - protected abstract optionalRemove(): void -} diff --git a/packages/react-query-no-core/src/runtime/retryer.ts b/packages/react-query-no-core/src/runtime/retryer.ts deleted file mode 100644 index 5ac6a5eece1..00000000000 --- a/packages/react-query-no-core/src/runtime/retryer.ts +++ /dev/null @@ -1,241 +0,0 @@ -import { isServer as isServerEnvironment } from './environmentManager' -import { focusManager } from './focusManager' -import { onlineManager } from './onlineManager' -import { noop, sleep } from './utils' -import type { - Retryer, - RetryerConfig, - RetryerStatus, -} from '@tanstack/query-types/bindings' -import type { CancelOptions, DefaultError, NetworkMode } from './types' - -/** - * Applies exponential backoff with jitter. The base delay starts at 1 second - * and doubles for each retry, up to 30 seconds. - * @param failureCount - The number of previous failures. Starts at 0 for the first retry. - * @returns A random delay from 80% to 100% of the base delay, in milliseconds. - */ -function defaultRetryDelay(failureCount: number) { - const baseDelay = Math.min(1000 * 2 ** failureCount, 30000) - const maxJitter = baseDelay * 0.2 - return baseDelay - Math.floor(Math.random() * (maxJitter + 1)) -} - -/** - * Checks whether a fetch can run for the given network mode. - * @param networkMode - The `networkMode` option. Defaults to `'online'`. - * @returns `true` if the network mode is not `'online'`, or if it is and the client is online. - */ -export function canFetch(networkMode: NetworkMode | undefined): boolean { - return (networkMode ?? 'online') === 'online' - ? onlineManager.isOnline() - : true -} - -/** - * The error thrown by a `Retryer` (and surfaced to `query.promise`/`mutation`) when a fetch is cancelled, e.g. via - * `query.cancel()`. `revert`, if `true`, tells the caller to restore the state the query was in before the fetch - * started instead of surfacing the error. `silent`, if `true`, tells the caller to suppress this error and instead - * resolve with the promise of the fetch that triggered the cancellation. - * @example - * ```ts - * query.cancel() - * - * try { - * await query.promise - * } catch (error) { - * if (error instanceof CancelledError) { - * // the fetch was cancelled, e.g. via `query.cancel()` - * } - * } - * ``` - */ -export class CancelledError extends Error { - revert?: boolean - silent?: boolean - constructor(options?: CancelOptions) { - super('CancelledError') - this.revert = options?.revert - this.silent = options?.silent - } -} - -/** - * Creates a retryer, which runs a function and retries it on failure according to the `retry` and - * `retryDelay` options. It pauses while the network mode doesn't allow fetching or `canRun` returns - * `false`, and can be cancelled. Queries and mutations use it to run their `queryFn` and - * `mutationFn`. - * @param config - The function to run, the retry options, and the callbacks for failures, pausing, - * continuing, and cancellation. - * @returns The retryer, whose `promise` settles with the result of the function. - */ -export function createRetryer( - config: RetryerConfig, -): Retryer { - let isRetryCancelled = false - let failureCount = 0 - let continueFn: ((value?: unknown) => void) | undefined - let status: RetryerStatus = 'pending' - const { - promise, - resolve: promiseResolve, - reject: promiseReject, - } = Promise.withResolvers() - promise.catch(noop) - - const isResolved = () => status !== 'pending' - - const cancel = (cancelOptions?: CancelOptions): void => { - if (!isResolved()) { - const error = new CancelledError(cancelOptions) as TError - reject(error) - - config.onCancel?.(error) - } - } - const cancelRetry = () => { - isRetryCancelled = true - } - - const continueRetry = () => { - isRetryCancelled = false - } - - const canContinue = () => - focusManager.isFocused() && - (config.networkMode === 'always' || onlineManager.isOnline()) && - config.canRun() - - const canStart = () => canFetch(config.networkMode) && config.canRun() - - const resolve = (value: any) => { - if (!isResolved()) { - continueFn?.() - status = 'resolved' - promiseResolve(value) - } - } - - const reject = (value: any) => { - if (!isResolved()) { - continueFn?.() - status = 'rejected' - promiseReject(value) - } - } - - const pause = (canResume: () => boolean) => { - return new Promise((continueResolve) => { - continueFn = (value) => { - if (isResolved() || canResume()) { - continueResolve(value) - } - } - config.onPause?.() - }).then(() => { - continueFn = undefined - if (!isResolved()) { - config.onContinue?.() - } - }) - } - - // Create loop function - const run = () => { - // Do nothing if already resolved - if (isResolved()) { - return - } - - let promiseOrValue: any - - // we can re-use config.initialPromise on the first call of run() - const initialPromise = - failureCount === 0 ? config.initialPromise : undefined - - // Execute query - try { - promiseOrValue = initialPromise ?? config.fn() - } catch (error) { - promiseOrValue = Promise.reject(error) - } - - Promise.resolve(promiseOrValue) - .then(resolve) - .catch((error) => { - // Stop if the fetch is already resolved - if (isResolved()) { - return - } - - // Do we need to retry the request? - const retry = config.retry ?? (isServerEnvironment() ? 0 : 3) - const retryDelay = config.retryDelay ?? defaultRetryDelay - const delay = - typeof retryDelay === 'function' - ? retryDelay(failureCount, error) - : retryDelay - const shouldRetry = - retry === true || - (typeof retry === 'number' && failureCount < retry) || - (typeof retry === 'function' && retry(failureCount, error)) - - if (isRetryCancelled || !shouldRetry) { - // We are done if the query does not need to be retried - reject(error) - return - } - - failureCount++ - - // Notify on fail - config.onFail?.(failureCount, error) - - // Delay - sleep(delay) - // Pause if the document is not visible or when the device is offline - .then(() => { - return isResolved() || canContinue() - ? undefined - : pause(canContinue) - }) - .then(() => { - if (isRetryCancelled) { - reject(error) - } else { - run() - } - }) - }) - } - - return { - promise, - status: () => status, - cancel, - continue: () => { - continueFn?.() - return promise - }, - cancelRetry, - continueRetry, - canStart, - start: () => { - // Start loop - if (canStart()) { - run() - } else { - // Waiting to start (e.g. queued behind a scope) does not depend on focus, - // only on the same conditions that allow starting in the first place - pause(canStart).then(run) - } - return promise - }, - } -} - -export type { - Retryer, - RetryValue, - RetryDelayValue, -} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/runtimeBinding.ts b/packages/react-query-no-core/src/runtime/runtimeBinding.ts deleted file mode 100644 index cbc72e7b585..00000000000 --- a/packages/react-query-no-core/src/runtime/runtimeBinding.ts +++ /dev/null @@ -1,47 +0,0 @@ -import type { RuntimeBinding } from '@tanstack/query-types/bindings' -import type { Mutation } from './mutation' -import type { MutationCache } from './mutationCache' -import type { MutationObserver } from './mutationObserver' -import type { Query } from './query' -import type { QueryCache } from './queryCache' -import type { QueryClient } from './queryClient' -import type { QueryObserver } from './queryObserver' - -/** Binds shared option and callback types to the concrete classes in this runtime. */ -export interface QueryRuntime extends RuntimeBinding { - /** {@inheritDoc RuntimeBinding.QueryClient} */ - QueryClient: QueryClient - /** {@inheritDoc RuntimeBinding.QueryCache} */ - QueryCache: QueryCache - /** {@inheritDoc RuntimeBinding.MutationCache} */ - MutationCache: MutationCache - /** {@inheritDoc RuntimeBinding.Query} */ - Query: Query< - this['queryFnData'], - this['error'], - this['data'], - this['queryKey'][0] - > - /** {@inheritDoc RuntimeBinding.Mutation} */ - Mutation: Mutation< - this['data'], - this['error'], - this['variables'], - this['onMutateResult'] - > - /** {@inheritDoc RuntimeBinding.QueryObserver} */ - QueryObserver: QueryObserver< - this['queryFnData'], - this['error'], - this['data'], - this['queryData'], - this['queryKey'][0] - > - /** {@inheritDoc RuntimeBinding.MutationObserver} */ - MutationObserver: MutationObserver< - this['data'], - this['error'], - this['variables'], - this['onMutateResult'] - > -} diff --git a/packages/react-query-no-core/src/runtime/subscribable.ts b/packages/react-query-no-core/src/runtime/subscribable.ts deleted file mode 100644 index 8b40e3ce868..00000000000 --- a/packages/react-query-no-core/src/runtime/subscribable.ts +++ /dev/null @@ -1,65 +0,0 @@ -/** - * The base class behind everything in Query that you can subscribe to: `QueryCache`, `MutationCache`, - * the observers, and the `FocusManager`/`OnlineManager` behind `focusManager` and `onlineManager`. - * Subclasses decide what a listener receives and when it is called. - */ -export class Subscribable< - // oxlint-disable-next-line typescript/no-unsafe-function-type -- also accepts construct signatures and functions with extra properties, which a call signature would reject - TListener extends Function, -> { - protected listeners = new Set() - - constructor() { - this.subscribe = this.subscribe.bind(this) - } - - /** - * Registers a listener to be called on every update this object notifies about. Returns a function - * that removes the listener again — call it to stop listening. The base class never drops a listener - * on its own, though some subclasses clear all of theirs in `destroy()`. - * @param listener - Called on each update, with whatever the subclass passes to its subscribers. - * @returns A function that removes the listener. - * @example - * ```ts - * const unsubscribe = subscribable.subscribe(() => { - * // react to the update - * }) - * - * unsubscribe() - * ``` - */ - subscribe(listener: TListener): () => void { - this.listeners.add(listener) - - this.onSubscribe() - - return () => { - this.listeners.delete(listener) - this.onUnsubscribe() - } - } - - /** - * Returns `true` while at least one listener is registered, `false` once they have all unsubscribed. - * @returns `true` if at least one listener is registered. - */ - hasListeners(): boolean { - return this.listeners.size > 0 - } - - /** - * Called after a listener is added. Does nothing here; subclasses override it, e.g. to start - * tracking what they observe once the first listener subscribes. - */ - protected onSubscribe(): void { - // Do nothing - } - - /** - * Called after a listener is removed. Does nothing here; subclasses override it, e.g. to clean up - * once the last listener unsubscribes. - */ - protected onUnsubscribe(): void { - // Do nothing - } -} diff --git a/packages/react-query-no-core/src/runtime/timeoutManager.ts b/packages/react-query-no-core/src/runtime/timeoutManager.ts deleted file mode 100644 index 855d3ea4924..00000000000 --- a/packages/react-query-no-core/src/runtime/timeoutManager.ts +++ /dev/null @@ -1,211 +0,0 @@ -import type { - ManagedTimerId, - SystemTimerId, - TimeoutCallback, - TimeoutProvider, -} from '@tanstack/query-types/bindings' - -export const defaultTimeoutProvider: TimeoutProvider = { - // We need the wrapper function syntax below instead of direct references to - // global setTimeout etc. - // - // BAD: `setTimeout: setTimeout` - // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)` - // - // If we use direct references here, then anything that wants to spy on or - // replace the global setTimeout (like tests) won't work since we'll already - // have a hard reference to the original implementation at the time when this - // file was imported. - setTimeout: (callback, delay) => setTimeout(callback, delay), - clearTimeout: (timeoutId) => - clearTimeout(timeoutId as SystemTimerId | undefined), - - setInterval: (callback, delay) => setInterval(callback, delay), - clearInterval: (intervalId) => - clearInterval(intervalId as SystemTimerId | undefined), -} - -/** - * Allows customization of how timeouts are created. - * - * `@tanstack/react-query-no-core` makes liberal use of timeouts to implement `staleTime` - * and `gcTime`. The default TimeoutManager provider uses the platform's global - * `setTimeout` implementation, which is known to have scalability issues with - * thousands of timeouts on the event loop. - * - * If you hit this limitation, consider providing a custom TimeoutProvider that - * coalesces timeouts. - */ -export class TimeoutManager implements Omit { - // We cannot have TimeoutManager as we must instantiate it with a concrete - // type at app boot; and if we leave that type, then any new timer provider - // would need to support the default provider's concrete timer ID, which is - // infeasible across environments. - // - // We settle for type safety for the TimeoutProvider type, and accept that - // this class is unsafe internally to allow for extension. - #provider: TimeoutProvider = defaultTimeoutProvider - #providerCalled = false - - /** - * `setTimeoutProvider` can be used to set a custom implementation of the - * `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval` functions, - * called a `TimeoutProvider`. - * - * This may be useful if you notice event loop performance issues with - * thousands of queries. A custom TimeoutProvider could also support timer - * delays longer than the global `setTimeout` maximum delay value of about - * 24 days. - * - * It is important to call `setTimeoutProvider` before creating a - * QueryClient or queries, so that the same provider is used consistently - * for all timers in the application, since different TimeoutProviders - * cannot cancel each others' timers. - * @param provider - The `TimeoutProvider` to use for all timers from now on. - * @example - * ```ts - * import { timeoutManager, QueryClient } from '@tanstack/react-query-no-core' - * import { CustomTimeoutProvider } from './CustomTimeoutProvider' - * - * timeoutManager.setTimeoutProvider(new CustomTimeoutProvider()) - * - * export const queryClient = new QueryClient() - * ``` - */ - setTimeoutProvider( - provider: TimeoutProvider, - ): void { - if (process.env.NODE_ENV !== 'production') { - if (this.#providerCalled && provider !== this.#provider) { - // After changing providers, `clearTimeout` will not work as expected for - // timeouts from the previous provider. - // - // Since they may allocate the same timeout ID, clearTimeout may cancel an - // arbitrary different timeout, or unexpected no-op. - // - // We could protect against this by mixing the timeout ID bits - // deterministically with some per-provider bits. - // - // We could internally queue `setTimeout` calls to `TimeoutManager` until - // some API call to set the initial provider. - console.error( - `[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`, - { previous: this.#provider, provider }, - ) - } - } - - this.#provider = provider - if (process.env.NODE_ENV !== 'production') { - this.#providerCalled = false - } - } - - /** - * `setTimeout` schedules a callback to run after approximately `delay` - * milliseconds, like the global `setTimeout` function. The callback can be - * canceled with `clearTimeout`. - * - * It returns a timer ID, which may be a number or an object that can be - * coerced to a number via `Symbol.toPrimitive`. - * @param callback - The function to call when the timeout elapses. - * @param delay - The time to wait before calling `callback`, in milliseconds. - * @returns The timer ID, to pass to {@link TimeoutManager#clearTimeout}. - * @example - * ```ts - * import { timeoutManager } from '@tanstack/react-query-no-core' - * - * const timeoutId = timeoutManager.setTimeout( - * () => console.log('ran at:', new Date()), - * 1000, - * ) - * - * const timeoutIdNumber: number = Number(timeoutId) - * ``` - */ - setTimeout(callback: TimeoutCallback, delay: number): ManagedTimerId { - if (process.env.NODE_ENV !== 'production') { - this.#providerCalled = true - } - return this.#provider.setTimeout(callback, delay) - } - - /** - * `clearTimeout` cancels a timeout callback scheduled with `setTimeout`, - * like the global `clearTimeout` function. It should be called with a - * timer ID returned by `setTimeout`. - * @param timeoutId - The timer ID returned by `setTimeout`, or `undefined`. - * @example - * ```ts - * import { timeoutManager } from '@tanstack/react-query-no-core' - * - * const timeoutId = timeoutManager.setTimeout( - * () => console.log('ran at:', new Date()), - * 1000, - * ) - * - * timeoutManager.clearTimeout(timeoutId) - * ``` - */ - clearTimeout(timeoutId: ManagedTimerId | undefined): void { - this.#provider.clearTimeout(timeoutId) - } - - /** - * `setInterval` schedules a callback to be called approximately every - * `delay` milliseconds, like the global `setInterval` function. - * - * Like `setTimeout`, it returns a timer ID, which may be a number or an - * object that can be coerced to a number via `Symbol.toPrimitive`. - * @param callback - The function to call on every interval. - * @param delay - The time between calls, in milliseconds. - * @returns The timer ID, to pass to {@link TimeoutManager#clearInterval}. - * @example - * ```ts - * import { timeoutManager } from '@tanstack/react-query-no-core' - * - * const intervalId = timeoutManager.setInterval( - * () => console.log('ran at:', new Date()), - * 1000, - * ) - * ``` - */ - setInterval(callback: TimeoutCallback, delay: number): ManagedTimerId { - if (process.env.NODE_ENV !== 'production') { - this.#providerCalled = true - } - return this.#provider.setInterval(callback, delay) - } - - /** - * `clearInterval` can be used to cancel an interval, like the global - * `clearInterval` function. It should be called with an interval ID - * returned by `setInterval`. - * @param intervalId - The timer ID returned by `setInterval`, or `undefined`. - * @example - * ```ts - * import { timeoutManager } from '@tanstack/react-query-no-core' - * - * const intervalId = timeoutManager.setInterval( - * () => console.log('ran at:', new Date()), - * 1000, - * ) - * - * timeoutManager.clearInterval(intervalId) - * ``` - */ - clearInterval(intervalId: ManagedTimerId | undefined): void { - this.#provider.clearInterval(intervalId) - } -} - -/** - * Singleton instance of {@link TimeoutManager}, used throughout TanStack Query to schedule and cancel timers. - */ -export const timeoutManager = new TimeoutManager() - -export type { - TimeoutCallback, - ManagedTimerId, - TimeoutProvider, -} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/types.ts b/packages/react-query-no-core/src/runtime/types.ts deleted file mode 100644 index df37aeba7d3..00000000000 --- a/packages/react-query-no-core/src/runtime/types.ts +++ /dev/null @@ -1,450 +0,0 @@ -import type * as Shared from '@tanstack/query-types/bindings' -import type { - DefaultError, - InfiniteData, - QueryKey, -} from '@tanstack/query-types/bindings' -import type { QueryRuntime } from './runtimeBinding' - -export const dataTagSymbol: Shared.dataTagSymbol = Symbol.for( - '@tanstack/query/dataTagSymbol', -) as Shared.dataTagSymbol -/** - * The type of the `dataTagSymbol` key, under which a {@link DataTag} stores its data type. - */ -export type dataTagSymbol = typeof dataTagSymbol -export const dataTagErrorSymbol: Shared.dataTagErrorSymbol = Symbol.for( - '@tanstack/query/dataTagErrorSymbol', -) as Shared.dataTagErrorSymbol -/** - * The type of the `dataTagErrorSymbol` key, under which a {@link DataTag} stores its error type. - */ -export type dataTagErrorSymbol = typeof dataTagErrorSymbol -export const unsetMarker: Shared.UnsetMarker = Symbol.for( - '@tanstack/query/unsetMarker', -) as Shared.UnsetMarker - -/** {@inheritDoc Shared.QueryFunction} */ -export type QueryFunction< - T = unknown, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.QueryFunction - -/** {@inheritDoc Shared.StaleTimeFunction} */ -export type StaleTimeFunction< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = Shared.StaleTimeFunction< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey -> - -/** {@inheritDoc Shared.QueryBooleanOption} */ -export type QueryBooleanOption< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = Shared.QueryBooleanOption< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey -> - -/** {@inheritDoc Shared.QueryPersister} */ -export type QueryPersister< - T = unknown, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.QueryPersister - -/** {@inheritDoc Shared.QueryFunctionContext} */ -export type QueryFunctionContext< - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.QueryFunctionContext - -// oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes every function-like value, including constructors, from the value branch - -/** {@inheritDoc Shared.PlaceholderDataFunction} */ -export type PlaceholderDataFunction< - TQueryFnData = unknown, - TError = DefaultError, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = Shared.PlaceholderDataFunction< - QueryRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey -> - -/** {@inheritDoc Shared.QueryOptions} */ -export type QueryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.QueryOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.ThrowOnError} */ -export type ThrowOnError< - TQueryFnData, - TError, - TQueryData, - TQueryKey extends QueryKey, -> = Shared.ThrowOnError< - QueryRuntime, - TQueryFnData, - TError, - TQueryData, - TQueryKey -> - -/** {@inheritDoc Shared.QueryObserverOptionsBase} */ -export type QueryObserverOptionsBase< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.QueryObserverOptionsBase< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.QueryObserverOptions} */ -export type QueryObserverOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.QueryObserverOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.DefaultedQueryObserverOptions} */ -export type DefaultedQueryObserverOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.DefaultedQueryObserverOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.InfiniteQueryObserverOptions} */ -export type InfiniteQueryObserverOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> = Shared.InfiniteQueryObserverOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.DefaultedInfiniteQueryObserverOptions} */ -export type DefaultedInfiniteQueryObserverOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> = Shared.DefaultedInfiniteQueryObserverOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.QueryExecuteOptions} */ -export type QueryExecuteOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = never, -> = Shared.QueryExecuteOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.InfiniteQueryExecuteOptions} */ -export type InfiniteQueryExecuteOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> = Shared.InfiniteQueryExecuteOptions< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> - -/** {@inheritDoc Shared.InvalidateQueryFilters} */ -export type InvalidateQueryFilters = - Shared.InvalidateQueryFilters - -/** {@inheritDoc Shared.RefetchQueryFilters} */ -export type RefetchQueryFilters = - Shared.RefetchQueryFilters - -/** {@inheritDoc Shared.MutationFunctionContext} */ -export type MutationFunctionContext = - Shared.MutationFunctionContext - -/** {@inheritDoc Shared.MutationFunction} */ -export type MutationFunction< - TData = unknown, - TVariables = unknown, -> = Shared.MutationFunction - -/** {@inheritDoc Shared.MutationOptions} */ -export type MutationOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationOptions< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutationObserverOptions} */ -export type MutationObserverOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationObserverOptions< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutateOptions} */ -export type MutateOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutateOptions< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutateFunctionRest} */ -export type MutateFunctionRest< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutateFunctionRest< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutateFunction} */ -export type MutateFunction< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutateFunction< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutationObserverBaseResult} */ -export type MutationObserverBaseResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationObserverBaseResult< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutationObserverIdleResult} */ -export type MutationObserverIdleResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationObserverIdleResult< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutationObserverLoadingResult} */ -export type MutationObserverLoadingResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationObserverLoadingResult< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutationObserverErrorResult} */ -export type MutationObserverErrorResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationObserverErrorResult< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutationObserverSuccessResult} */ -export type MutationObserverSuccessResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationObserverSuccessResult< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.MutationObserverResult} */ -export type MutationObserverResult< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = Shared.MutationObserverResult< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -/** {@inheritDoc Shared.QueryClientConfig} */ -export type QueryClientConfig = Shared.QueryClientConfig - -/** {@inheritDoc Shared.DefaultOptions} */ -export type DefaultOptions = Shared.DefaultOptions< - QueryRuntime, - TError -> - -export type { - OmitKeyof, - DefaultError, - QueryKey, - InferDataFromTag, - InferErrorFromTag, - StaleTime, - InitialDataFunction, - EqualityFn, - CacheKeyConfig, - InfiniteData, - QueryMeta, - NetworkMode, - InfiniteQueryPageParamsOptions, - WithRequired, - RefetchOptions, - InvalidateOptions, - ResetOptions, - FetchNextPageOptions, - FetchPreviousPageOptions, - QueryObserverBaseResult, - QueryObserverResult, - InfiniteQueryObserverBaseResult, - InfiniteQueryObserverResult, - MutationKey, - MutationMeta, - CancelOptions, - SetDataOptions, -} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/runtime/utils.ts b/packages/react-query-no-core/src/runtime/utils.ts deleted file mode 100644 index 7a666f2aa50..00000000000 --- a/packages/react-query-no-core/src/runtime/utils.ts +++ /dev/null @@ -1,746 +0,0 @@ -import { identity } from './identity' -import { timeoutManager } from './timeoutManager' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - DefaultQueryFn, - SkipToken, - Updater, -} from '@tanstack/query-types/bindings' -import type { Mutation } from './mutation' -import type { FetchOptions, Query } from './query' -import type { QueryRuntime } from './runtimeBinding' -import type { - CacheKeyConfig, - DefaultError, - EqualityFn, - MutationKey, - QueryFunction, - QueryKey, - QueryOptions, -} from './types' - -/** {@inheritDoc Shared.QueryFilters} */ -export type QueryFilters = - Shared.QueryFilters - -/** {@inheritDoc Shared.MutationFilters} */ -export type MutationFilters< - TData = unknown, - TError = DefaultError, - TVariables = unknown, - TOnMutateResult = unknown, -> = Shared.MutationFilters< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult -> - -// UTILS - -/** - * A function that does nothing. - */ -export function noop(): void -export function noop(): undefined -export function noop() {} - -/** - * Resolves an {@link Updater}: calls it with `input` if it is a function, otherwise returns it as - * is. - * @param updater - The new value, or a function that receives `input` and returns the new value. - * @param input - The current value, passed to `updater` if it is a function. - * @returns The new value. - */ -export function functionalUpdate( - updater: Updater, - input: TInput, -): TOutput { - return typeof updater === 'function' - ? (updater as (_: TInput) => TOutput)(input) - : updater -} - -/** - * Checks whether a value can be used as a timeout: a non-negative, finite number. - * @param value - The value to check. - * @returns `true` if `value` is a number that is `>= 0` and not `Infinity`. - */ -export function isValidTimeout(value: unknown): value is number { - return typeof value === 'number' && value >= 0 && value !== Infinity -} - -/** - * Calculates how long until data updated at `updatedAt` becomes stale. - * @param updatedAt - The timestamp, in milliseconds, at which the data was last updated. - * @param staleTime - The time, in milliseconds, after which data is considered stale. Defaults to - * `0`. - * @returns The remaining time in milliseconds, or `0` if the data is already stale. - */ -export function timeUntilStale(updatedAt: number, staleTime?: number): number { - return Math.max(updatedAt + (staleTime || 0) - Date.now(), 0) -} - -/** - * Resolves an option that can be given either as a value or as a function of the query, such as - * `staleTime`. - * @param value - The option value, or a function that receives `query` and returns the value. - * @param query - The query passed to `value` if it is a function. - * @returns The resolved value, or `undefined` if `value` is `undefined`. - */ -export function resolveQueryValue< - TValue, - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - value: - | undefined - | TValue - | ((query: Query) => TValue), - query: Query, -): TValue | undefined { - return typeof value === 'function' - ? ( - value as ( - query: Query, - ) => TValue - )(query) - : value -} - -/** - * Checks whether a query matches the given {@link QueryFilters}. - * Every filter that is specified must match; filters that are left unspecified are ignored. - * @param filters - The filters to check the query against. - * @param query - The query to check. - * @param keyConfig - The cache configuration for key comparison and hashing. - * @returns `true` if the query matches every specified filter. - * @example - * ```ts - * const queryCache = queryClient.getQueryCache() - * - * const matchingQueries = queryCache - * .getAll() - * .filter((query) => matchQuery({ queryKey: ['posts'] }, query)) - * ``` - */ -export function matchQuery( - filters: QueryFilters, - query: Query, - keyConfig?: CacheKeyConfig, -): boolean { - const { - type = 'all', - exact, - fetchStatus, - predicate, - queryKey, - stale, - } = filters - - if (queryKey) { - if (exact) { - if (query.queryHash !== hashKeyByOptions(queryKey, keyConfig)) { - return false - } - } else if ( - !partialMatchKey(query.queryKey, queryKey, keyConfig?.equalityFn) - ) { - return false - } - } - - if (type !== 'all') { - const isActive = query.isActive() - if (type === 'active' && !isActive) { - return false - } - if (type === 'inactive' && isActive) { - return false - } - } - - if (typeof stale === 'boolean' && query.isStale() !== stale) { - return false - } - - if (fetchStatus && fetchStatus !== query.state.fetchStatus) { - return false - } - - if (predicate && !predicate(query)) { - return false - } - - return true -} - -/** - * Checks whether a mutation matches the given {@link MutationFilters}. - * Every filter that is specified must match; filters that are left unspecified are ignored. - * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match. - * @param filters - The filters to check the mutation against. - * @param mutation - The mutation to check. - * @param keyConfig - The cache configuration for key comparison and hashing. - * @returns `true` if the mutation matches every specified filter. - * @example - * ```ts - * const mutationCache = queryClient.getMutationCache() - * - * const matchingMutations = mutationCache - * .getAll() - * .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation)) - * ``` - */ -export function matchMutation( - filters: MutationFilters, - mutation: Mutation, - keyConfig?: CacheKeyConfig, -): boolean { - const { exact, status, predicate, mutationKey } = filters - if (mutationKey) { - if (!mutation.options.mutationKey) { - return false - } - if (exact) { - if ( - hashKeyByOptions(mutation.options.mutationKey, keyConfig) !== - hashKeyByOptions(mutationKey, keyConfig) - ) { - return false - } - } else if ( - !partialMatchKey( - mutation.options.mutationKey, - mutationKey, - keyConfig?.equalityFn, - ) - ) { - return false - } - } - - if (status && mutation.state.status !== status) { - return false - } - - if (predicate && !predicate(mutation)) { - return false - } - - return true -} - -/** - * Hashes a cache key with the cache's `hashFn`, falling back to {@link hashKey}. - * @param cacheKey - The query or mutation key to hash. - * @param keyConfig - The cache configuration that may provide a custom `hashFn`. - * @returns The hash, a string that identifies the key in the cache. - */ -export function hashKeyByOptions< - TCacheKey extends ReadonlyArray = ReadonlyArray, ->( - cacheKey: TCacheKey, - keyConfig: CacheKeyConfig | undefined, -): string { - const hashFn = keyConfig?.hashFn ?? hashKey - return hashFn(cacheKey) -} - -/** - * Default query & mutation keys hash function. - * Hashes the value into a stable hash. - * @param queryKey - The query or mutation key to hash. - * @returns The stable hash of the key, as a JSON string. - * @example - * ```ts - * // Object keys are sorted, so key order doesn't affect the hash: - * hashKey(['todos', { page: 1, filter: 'done' }]) // === '["todos",{"filter":"done","page":1}]' - * ``` - */ -export function hashKey(queryKey: QueryKey | MutationKey): string { - return JSON.stringify(queryKey, (_, val) => - isPlainObject(val) - ? Object.keys(val) - .sort() - .reduce((result, key) => { - result[key] = val[key] - return result - }, {} as any) - : val, - ) -} - -const defaultEqualityFn: EqualityFn = (a, b) => a === b - -/** - * Checks if key `b` partially matches with key `a`. - * @param a - The key to check, e.g. a query's own key. - * @param b - The (partial) key to match against `a`. - * @param equalityFn - Compares individual key values. Defaults to strict equality. - * @returns `true` if every array element or object property in `b` matches the one at the same - * position in `a`. - */ -export function partialMatchKey( - a: QueryKey, - b: QueryKey, - equalityFn?: EqualityFn, -): boolean -export function partialMatchKey( - a: unknown, - b: unknown, - equalityFn?: EqualityFn, -): boolean -export function partialMatchKey( - a: any, - b: any, - equalityFn: EqualityFn = defaultEqualityFn, -): boolean { - if (equalityFn(a, b)) { - return true - } - - if (typeof a !== typeof b) { - return false - } - - if (isPlainArray(a) && isPlainArray(b)) { - if (b.length > a.length) return false - for (let i = 0; i < b.length; i++) { - if (!partialMatchKey(a[i], b[i], equalityFn)) { - return false - } - } - return true - } - - if (isPlainObject(a) && isPlainObject(b)) { - const bKeys = Object.keys(b) - for (const key of bKeys) { - if (!partialMatchKey(a[key], b[key], equalityFn)) { - return false - } - } - return true - } - - return false -} - -/** - * This function returns `a` if `b` is deeply equal. - * If not, it will replace any deeply equal children of `b` with those of `a`. - * This can be used for structural sharing between JSON values for example. - * An optional equality function can be used for custom value types. - * @param a - The previous value, whose deeply equal parts are reused. - * @param b - The new value. - * @param equalityFn - Compares values for structural sharing. Defaults to strict equality. - * @returns `a` if `b` is deeply equal to it, otherwise `b` with its deeply equal parts replaced by - * those of `a`. - */ -export function replaceEqualDeep( - a: unknown, - b: T, - equalityFn?: EqualityFn, -): T -export function replaceEqualDeep( - a: any, - b: any, - equalityFn: EqualityFn = defaultEqualityFn, -): any { - return replaceEqualDeepInternal(a, b, equalityFn, 0) -} - -/** - * Reuses deeply equal values while limiting recursion to 500 levels. - * @param a - The previous value. - * @param b - The new value. - * @param equalityFn - Compares values for structural sharing. - * @param depth - The current recursion depth. - * @returns The new value with deeply equal parts of the previous value reused. - */ -function replaceEqualDeepInternal( - a: any, - b: any, - equalityFn: EqualityFn, - depth: number, -): any { - if (equalityFn(a, b)) { - return a - } - - if (depth > 500) return b - - const array = isPlainArray(a) && isPlainArray(b) - - if (!array && !(isPlainObject(a) && isPlainObject(b))) return b - - const aItems = array ? a : Object.keys(a) - const aSize = aItems.length - const bItems = array ? b : Object.keys(b) - const bSize = bItems.length - const copy: any = array ? new Array(bSize) : {} - - let equalItems = 0 - - for (let i = 0; i < bSize; i++) { - const key: any = array ? i : bItems[i] - const aItem = a[key] - const bItem = b[key] - - if (equalityFn(aItem, bItem)) { - copy[key] = aItem - if (array ? i < aSize : Object.hasOwn(a, key)) equalItems++ - continue - } - - if ( - aItem === null || - bItem === null || - typeof aItem !== 'object' || - typeof bItem !== 'object' - ) { - copy[key] = bItem - continue - } - - const v = replaceEqualDeepInternal(aItem, bItem, equalityFn, depth + 1) - copy[key] = v - if (v === aItem) equalItems++ - } - - return aSize === bSize && equalItems === aSize ? a : copy -} - -/** - * Shallow compare objects. - * @param a - The first object. - * @param b - The second object, or `undefined`. - * @returns `true` if both objects have the same keys, with strictly equal values for each key. - */ -export function shallowEqualObjects>( - a: T, - b: T | undefined, -): boolean { - if (!b || Object.keys(a).length !== Object.keys(b).length) { - return false - } - - for (const key of Object.keys(a)) { - if (!Object.hasOwn(b, key) || a[key] !== b[key]) { - return false - } - } - - return true -} - -/** - * Checks whether a value is an array with no holes and no extra properties. - * @param value - The value to check. - * @returns `true` if `value` is an array whose number of own keys equals its `length`. - */ -export function isPlainArray(value: unknown): value is Array { - return Array.isArray(value) && value.length === Object.keys(value).length -} - -// Copied from: https://github.com/jonschlinkert/is-plain-object -/** - * Checks whether a value is a plain object, e.g. created with an object literal or - * `Object.create(null)`. - * @param o - The value to check. - * @returns `true` if `o` is a plain object. - */ -export function isPlainObject(o: any): o is Record { - if (!hasObjectPrototype(o)) { - return false - } - - // If has no constructor - const objectPrototype = Object.getPrototypeOf(o) - const ctor = objectPrototype?.constructor - if (ctor === undefined) { - return true - } - - if (typeof ctor !== 'function') { - return false - } - - // If has modified prototype - const prot = ctor.prototype - if (!hasObjectPrototype(prot)) { - return false - } - - // If constructor does not have an Object-specific method - if (!prot.hasOwnProperty('isPrototypeOf')) { - return false - } - - // Handles Objects created by Object.create() - if (objectPrototype !== Object.prototype) { - return false - } - - // Most likely a plain Object - return true -} - -/** - * Checks whether a value's `Object.prototype.toString` tag is `[object Object]`. - * @param o - The value to check. - * @returns `true` if the tag is `[object Object]`. - */ -function hasObjectPrototype(o: any): boolean { - return Object.prototype.toString.call(o) === '[object Object]' -} - -/** - * Waits for the given time, using the configured {@link timeoutManager}. - * @param timeout - The time to wait, in milliseconds. - * @returns A promise that resolves after `timeout` milliseconds. - */ -export function sleep(timeout: number): Promise { - return new Promise((resolve) => { - timeoutManager.setTimeout(resolve, timeout) - }) -} - -/** - * Applies a query's `structuralSharing` option when writing new data. - * @param prevData - The previously cached data. - * @param data - The new data. - * @param options - The query options, whose `structuralSharing` decides how the data is merged. - * @returns The result of a custom `structuralSharing` function, `data` with its unchanged parts - * replaced by those of `prevData` by default, or `data` as is if `structuralSharing` is `false`. - * @throws {Error} The error from the default structural sharing, e.g. when the data is not JSON serializable. - * Outside production, it is also logged to the console. - */ -export function replaceData< - TData, - TOptions extends QueryOptions, ->(prevData: TData | undefined, data: TData, options: TOptions): TData { - if (typeof options.structuralSharing === 'function') { - return options.structuralSharing(prevData, data) as TData - } else if (options.structuralSharing !== false) { - if (process.env.NODE_ENV !== 'production') { - try { - return replaceEqualDeep(prevData, data) - } catch (error) { - console.error( - `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`, - ) - - // Prevent the replaceEqualDeep from being called again down below. - throw error - } - } - // Structurally share data between prev and new data if needed - return replaceEqualDeep(prevData, data) - } - return data -} - -/** - * Intended to be passed as a query's `placeholderData` option, for example - * `placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new - * query key is fetching, it keeps displaying the previously fetched data until the new data arrives. - * @param previousData - The data of the previous query key, passed by the observer. - * @returns The previous data, unchanged. - * @example - * ```ts - * new QueryObserver(queryClient, { - * queryKey: ['posts', page], - * queryFn: () => fetchPosts(page), - * placeholderData: keepPreviousData, - * }) - * ``` - */ -export const keepPreviousData: ( - previousData: T | undefined, -) => T | undefined = identity - -/** - * Adds an item to one end of a new array. If the result exceeds `max`, removes - * excess items from the opposite end. - * @param items - The current items. - * @param item - The value to add. - * @param max - The maximum number of items to keep. Omit it or use `0` for no limit. - * @param prepend - Pass `true` to add at the start. The default is to add at the end. - * @returns A new array with `item` added. - */ -export function addToArray( - items: Array, - item: T, - max?: number, - prepend?: boolean, -): Array { - const newItems = prepend ? [item, ...items] : [...items, item] - if (max && newItems.length > max) { - return prepend ? newItems.slice(0, max) : newItems.slice(-max) - } - return newItems -} - -/** - * Sentinel value that can be passed as a query's `queryFn` to conditionally disable the query (equivalent - * to `enabled: false`) while preserving full type inference for the query's data. Unlike `enabled: false`, - * a query disabled via `skipToken` cannot be triggered with `refetch`. - * @example - * ```ts - * new QueryObserver(queryClient, { - * queryKey: ['post', postId], - * queryFn: postId != null ? () => fetchPost(postId) : skipToken, - * }) - * ``` - */ -export const skipToken: SkipToken = Symbol.for( - '@tanstack/query/skipToken', -) as SkipToken - -/** - * Pass this as `queryFn` to use the query function configured on the client. - * The defaults for the query key take precedence over the client's global query defaults. - * If no query function is configured, a fetch fails with a `Missing queryFn` error. - */ -export const defaultQueryFn: DefaultQueryFn = Symbol.for( - '@tanstack/query/defaultQueryFn', -) as DefaultQueryFn - -/** - * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from - * an `initialPromise`, that promise is returned instead. If there is no usable `queryFn`, the returned - * function rejects with a `Missing queryFn` error. - * @param options - The query options with the `queryFn`, and the `queryHash` used in error messages. - * @param fetchOptions - The fetch options, which may carry an `initialPromise`. - * @returns The function to call for the fetch. - */ -export function ensureQueryFn< - TQueryFnData = unknown, - TQueryKey extends QueryKey = QueryKey, ->( - options: { - queryFn?: - | QueryFunction - | SkipToken - | DefaultQueryFn - queryHash?: string - }, - fetchOptions?: FetchOptions, -): QueryFunction { - if (process.env.NODE_ENV !== 'production') { - if (options.queryFn === skipToken) { - console.error( - `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`, - ) - } - } - - // if we attempt to retry a fetch that was triggered from an initialPromise - // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise - // if an observer has already mounted, we will be able to retry with that queryFn - if (!options.queryFn && fetchOptions?.initialPromise) { - return () => fetchOptions.initialPromise! - } - - if ( - !options.queryFn || - options.queryFn === skipToken || - options.queryFn === defaultQueryFn - ) { - return () => - Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`)) - } - - return options.queryFn -} - -/** - * Resolves a `throwOnError` option to a boolean. - * If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller, - * additional context such as the query or mutation) and its result is returned, allowing the throwing - * behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined` - * resolves to `false`). - * @param throwOnError - The `throwOnError` option: a boolean, a function that decides per error, or - * `undefined`. - * @param params - The arguments passed to `throwOnError` if it is a function. - * @returns Whether the error should be thrown. - * @example - * ```ts - * const throwOnError = - * query.state.error && typeof options.throwOnError === 'function' - * ? shouldThrowError(options.throwOnError, [query.state.error, query]) - * : options.throwOnError - * ``` - */ -export function shouldThrowError) => boolean>( - throwOnError: boolean | T | undefined, - params: Parameters, -): boolean { - // Allow throwOnError function to override throwing behavior on a per-error basis - if (typeof throwOnError === 'function') { - return throwOnError(...params) - } - - return !!throwOnError -} - -export const fetchSignal: Shared.FetchSignal = Symbol.for( - '@tanstack/query/fetchSignal', -) as Shared.FetchSignal - -/** - * Adds a lazy `signal` getter to an object, such as a query function context. The first time - * `signal` is read, `onCancelled` is registered for the signal's `abort` event (or called right - * away if it is already aborted), so cancellation is only tracked when the signal is actually used. - * @param object - The object to add the `signal` property to. - * @param getSignal - Returns the `AbortSignal`. Called once, when `signal` is first read. - * @param onCancelled - Called when the signal is aborted, if `signal` was read. - * @param internalSignal - The fetch signal to forward without consuming the getter. - * @returns The same object, with the `signal` property added. - */ -export function addConsumeAwareSignal( - object: T, - getSignal: () => AbortSignal, - onCancelled: () => void, - internalSignal?: AbortSignal, -): T & { signal: AbortSignal } { - let consumed = false - let signal: AbortSignal | undefined - - Object.defineProperties(object, { - [fetchSignal]: { value: internalSignal }, - signal: { - enumerable: true, - get: () => { - signal ??= getSignal() - if (consumed) { - return signal - } - - consumed = true - if (signal.aborted) { - onCancelled() - } else { - signal.addEventListener('abort', onCancelled, { once: true }) - } - - return signal - }, - }, - }) - - return object as T & { signal: AbortSignal } -} - -export type { - Updater, - QueryTypeFilter, - SkipToken, - DefaultQueryFn, - FetchSignalContext, -} from '@tanstack/query-types/bindings' diff --git a/packages/react-query-no-core/src/types.ts b/packages/react-query-no-core/src/types.ts deleted file mode 100644 index de88256c368..00000000000 --- a/packages/react-query-no-core/src/types.ts +++ /dev/null @@ -1,473 +0,0 @@ -/* istanbul ignore file */ - -import type { - DefaultError, - DefinedInfiniteQueryObserverResult, - DefinedQueryObserverResult, - DistributiveOmit, - InfiniteData, - InfiniteQueryObserverPlaceholderResult, - InfiniteQueryObserverResult, - OmitKeyof, - Override, - QueryKey, - QueryObserverPlaceholderResult, - QueryObserverResult, - SkipToken, -} from '@tanstack/query-types/bindings' -import type { - InfiniteQueryExecuteOptions, - InfiniteQueryObserverOptions, - MutateFunction, - MutationObserverOptions, - MutationObserverResult, - QueryExecuteOptions, - QueryObserverOptions, -} from './runtime/types' - -/** - * {@link UseBaseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't - * relevant, e.g. when accepting options for any query in a helper function. - */ -export type AnyUseBaseQueryOptions = UseBaseQueryOptions< - any, - any, - any, - any, - any -> -/** - * The options shared by `useQuery` and `useSuspenseQuery`. Extends {@link QueryObserverOptions} from - * `@tanstack/query-core` with the `react-query`-specific `subscribed` option. - * @template TQueryFnData - The type your `queryFn` resolves to. - * @template TError - The type of errors your `queryFn` may throw. - * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no - * `select` is used. - * @template TQueryData - The type of the data actually held in the query cache — the input to `select` and - * `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`. - * @template TQueryKey - The type of your `queryKey`. - */ -export interface UseBaseQueryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> extends QueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey -> { - /** - * Set this to `false` to unsubscribe this observer from updates to the query cache. - * @defaultValue true - */ - subscribed?: boolean -} - -/** - * The options accepted by `usePrefetchQuery` — everything you can pass to `queryClient.query`, with a - * required `queryFn`. Pass `defaultQueryFn` to use the client defaults. - * @template TQueryFnData - The type your `queryFn` resolves to. - * @template TError - The type of errors your `queryFn` may throw. - * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no - * `select` is used. - * @template TQueryData - The type of the data actually held in the query cache — the input to `select` and - * `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`. - * @template TQueryKey - The type of your `queryKey`. - */ -export type UsePrefetchQueryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = DistributiveOmit< - QueryExecuteOptions, - 'queryFn' -> & { - /** - * Pass a query function or `defaultQueryFn` to use the client defaults. Prefetch hooks do not accept `skipToken`. - */ - queryFn: Exclude< - QueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >['queryFn'], - SkipToken | undefined - > -} - -/** - * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `queryClient.infiniteQuery`, - * with a required `queryFn`. Pass `defaultQueryFn` to use the client defaults. - * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. - * @template TError - The type of errors your `queryFn` may throw. - * @template TData - The type `data` ends up as after `select` runs. Defaults to `InfiniteData`, - * the shape of all fetched pages plus their page params — a prefetch never reads `data` back out, so this - * parameter only matters if you reuse these options elsewhere with `select` applied. - * @template TQueryKey - The type of your `queryKey`. - * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. - */ -export type UsePrefetchInfiniteQueryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> = DistributiveOmit< - InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - 'queryFn' -> & { - /** - * Pass a query function or `defaultQueryFn` to use the client defaults. Prefetch hooks do not accept `skipToken`. - */ - queryFn: Exclude< - InfiniteQueryExecuteOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >['queryFn'], - SkipToken | undefined - > -} - -/** - * {@link UseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't - * relevant, e.g. when accepting options for any query in a helper function. - */ -export type AnyUseQueryOptions = UseQueryOptions -/** - * The options accepted by `useQuery`. Same as {@link UseBaseQueryOptions}, minus `suspense` (which - * `react-query` derives from which hook you call rather than exposing as an option). - * @template TQueryFnData - The type your `queryFn` resolves to. - * @template TError - The type of errors your `queryFn` may throw. - * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no - * `select` is used. - * @template TQueryKey - The type of your `queryKey`. - */ -export interface UseQueryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> extends OmitKeyof< - UseBaseQueryOptions, - 'suspense' -> {} - -/** - * {@link UseSuspenseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't - * relevant, e.g. when accepting options for any query in a helper function. - */ -export type AnyUseSuspenseQueryOptions = UseSuspenseQueryOptions< - any, - any, - any, - any -> -/** - * Options for a `useSuspenseQuery` call whose data is defined. The options match those of - * {@link UseQueryOptions} except for `throwOnError` and `enabled`. - * Use the other overload for a query function that can be `skipToken`. - * @template TQueryFnData - The type your `queryFn` resolves to. - * @template TError - The type of errors your `queryFn` may throw. - * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no - * `select` is used. - * @template TQueryKey - The type of your `queryKey`. - */ -export interface UseSuspenseQueryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> extends OmitKeyof< - UseQueryOptions, - 'queryFn' | 'enabled' | 'throwOnError' -> { - /** - * The query function. Use `defaultQueryFn` to use the client's configured function. - */ - queryFn: Exclude< - UseQueryOptions['queryFn'], - SkipToken - > -} - -/** - * {@link UseInfiniteQueryOptions} with all type parameters set to `any`, useful when the specific types aren't - * relevant, e.g. when accepting options for any query in a helper function. - */ -export type AnyUseInfiniteQueryOptions = UseInfiniteQueryOptions< - any, - any, - any, - any, - any -> -/** - * The options accepted by `useInfiniteQuery`. Extends {@link InfiniteQueryObserverOptions} from - * `@tanstack/query-core` with the `react-query`-specific `subscribed` option, minus `suspense` (which - * `react-query` derives from which hook you call rather than exposing as an option). - * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. - * @template TError - The type of errors your `queryFn` may throw. - * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, - * the shape of all fetched pages plus their page params. - * @template TQueryKey - The type of your `queryKey`. - * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. - */ -export interface UseInfiniteQueryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> extends OmitKeyof< - InfiniteQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - 'suspense' -> { - /** - * Set this to `false` to unsubscribe this observer from updates to the query cache. - * @defaultValue true - */ - subscribed?: boolean -} - -/** - * {@link UseSuspenseInfiniteQueryOptions} with all type parameters set to `any`, useful when the specific types - * aren't relevant, e.g. when accepting options for any query in a helper function. - */ -export type AnyUseSuspenseInfiniteQueryOptions = - UseSuspenseInfiniteQueryOptions -/** - * The options accepted by `useSuspenseInfiniteQuery`. Same as {@link UseInfiniteQueryOptions}, except for - * `enabled` and `throwOnError`. If `placeholderData` provides data, the query can render while the fetch runs. - * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. - * @template TError - The type of errors your `queryFn` may throw. - * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, - * the shape of all fetched pages plus their page params. - * @template TQueryKey - The type of your `queryKey`. - * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. - */ -export interface UseSuspenseInfiniteQueryOptions< - TQueryFnData = unknown, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, -> extends OmitKeyof< - UseInfiniteQueryOptions, - 'queryFn' | 'enabled' | 'throwOnError' -> { - /** - * The query function. Use `defaultQueryFn` to use the client defaults. Use the other overload when the function can be `skipToken`. - */ - queryFn: Exclude< - UseInfiniteQueryOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >['queryFn'], - SkipToken - > -} - -/** - * The result of `useQuery` when `initialData` isn't set — `data` may be `undefined` while the query is - * `pending`. Re-exports {@link QueryObserverResult} from `@tanstack/query-core`. `useInfiniteQuery` returns - * {@link UseInfiniteQueryResult} instead. - * @template TData - The type `data` ends up as after `select` runs. - * @template TError - The type of errors your `queryFn` may throw. - */ -export type UseBaseQueryResult< - TData = unknown, - TError = DefaultError, -> = QueryObserverResult - -/** - * The result of `useQuery`. Same as {@link UseBaseQueryResult}. - * @template TData - The type `data` ends up as after `select` runs. - * @template TError - The type of errors your `queryFn` may throw. - */ -export type UseQueryResult< - TData = unknown, - TError = DefaultError, -> = UseBaseQueryResult - -/** The result of `useSuspenseQuery`, including defined placeholder data when configured. */ -export type UseSuspenseQueryResult = - | DefinedQueryObserverResult - | QueryObserverPlaceholderResult - -/** - * The result of `useQuery` when `initialData` is set. The `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`). - * Re-exports {@link DefinedQueryObserverResult} from `@tanstack/query-core`. - * @template TData - The type `data` ends up as after `select` runs. - * @template TError - The type of errors your `queryFn` may throw. - */ -export type DefinedUseQueryResult< - TData = unknown, - TError = DefaultError, -> = DefinedQueryObserverResult - -/** - * The result of `useInfiniteQuery` when `initialData` isn't set — `data` may be `undefined` while the query is - * `pending`. Re-exports {@link InfiniteQueryObserverResult} from `@tanstack/query-core`. - * @template TData - The type `data` ends up as after `select` runs. - * @template TError - The type of errors your `queryFn` may throw. - */ -export type UseInfiniteQueryResult< - TData = unknown, - TError = DefaultError, -> = InfiniteQueryObserverResult - -/** - * The result of `useInfiniteQuery` when `initialData` is set — `data` is never `undefined` (unless a - * `select` changes `TData` to include `undefined`). Re-exports {@link DefinedInfiniteQueryObserverResult} - * from `@tanstack/query-core`. - * @template TData - The type `data` ends up as after `select` runs. - * @template TError - The type of errors your `queryFn` may throw. - */ -export type DefinedUseInfiniteQueryResult< - TData = unknown, - TError = DefaultError, -> = DefinedInfiniteQueryObserverResult - -/** - * The result of `useSuspenseInfiniteQuery`, including defined placeholder data when configured. - * @template TData - The type `data` ends up as after `select` runs. - * @template TError - The type of errors your `queryFn` may throw. - */ -export type UseSuspenseInfiniteQueryResult< - TData = unknown, - TError = DefaultError, -> = - | DefinedInfiniteQueryObserverResult - | InfiniteQueryObserverPlaceholderResult - -/** - * {@link UseMutationOptions} with all type parameters set to `any`, useful when the specific types aren't - * relevant, e.g. when accepting options for any mutation in a helper function. - */ -export type AnyUseMutationOptions = UseMutationOptions -/** - * The options accepted by `useMutation`. Same as {@link MutationObserverOptions} from `@tanstack/query-core`, - * minus the internal `_defaulted` flag. - * @template TData - The type your mutation function resolves to. - * @template TError - The type of errors your mutation function may throw. - * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. - * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as - * their `onMutateResult` parameter — useful for optimistic-update rollback data. - */ -export interface UseMutationOptions< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> extends OmitKeyof< - MutationObserverOptions, - '_defaulted' -> {} - -/** - * The type of `mutate`, as returned by `useMutation`. Forwards the variables (and an optional per-call - * `onSuccess`/`onError`/`onSettled`) to the underlying `mutate` call. Fire-and-forget — errors are surfaced - * through the mutation result instead of being thrown by `mutate`, unless `throwOnError` makes `useMutation` - * rethrow them. - * @template TData - The type your mutation function resolves to. - * @template TError - The type of errors your mutation function may throw. - * @template TVariables - The type of the variable passed to `mutate`. - * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as - * their `onMutateResult` parameter — useful for optimistic-update rollback data. - */ -export type UseMutateFunction< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = ( - ...args: Parameters< - MutateFunction - > -) => void - -/** - * The type of `mutateAsync`, as returned by `useMutation`. Similar to {@link UseMutateFunction}, but returns a - * promise which can be awaited. - * @template TData - The type your mutation function resolves to. - * @template TError - The type of errors your mutation function may throw. - * @template TVariables - The type of the variable passed to `mutateAsync`. - * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as - * their `onMutateResult` parameter — useful for optimistic-update rollback data. - */ -export type UseMutateAsyncFunction< - TData = unknown, - TError = DefaultError, - TVariables = void, - TOnMutateResult = unknown, -> = MutateFunction - -/** - * The result of `useMutation`. Same as {@link MutationObserverResult} from `@tanstack/query-core`, with - * `mutate` narrowed to the fire-and-forget {@link UseMutateFunction} signature, plus the added `mutateAsync`. - * @template TData - The type your mutation function resolves to. - * @template TError - The type of errors your mutation function may throw. - * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. - * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as - * their `onMutateResult` parameter — useful for optimistic-update rollback data. - */ -export type UseBaseMutationResult< - TData = unknown, - TError = DefaultError, - TVariables = unknown, - TOnMutateResult = unknown, -> = Override< - MutationObserverResult, - { mutate: UseMutateFunction } -> & { - /** - * Similar to `mutate`, but returns a promise which can be awaited. - */ - mutateAsync: UseMutateAsyncFunction< - TData, - TError, - TVariables, - TOnMutateResult - > -} - -/** - * The result of `useMutation`. Same as {@link UseBaseMutationResult}. - * @template TData - The type your mutation function resolves to. - * @template TError - The type of errors your mutation function may throw. - * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. - * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as - * their `onMutateResult` parameter — useful for optimistic-update rollback data. - */ -export type UseMutationResult< - TData = unknown, - TError = DefaultError, - TVariables = unknown, - TOnMutateResult = unknown, -> = UseBaseMutationResult diff --git a/packages/react-query-no-core/src/useBaseQuery.ts b/packages/react-query-no-core/src/useBaseQuery.ts deleted file mode 100644 index 7216bf66c41..00000000000 --- a/packages/react-query-no-core/src/useBaseQuery.ts +++ /dev/null @@ -1,146 +0,0 @@ -'use client' -import * as React from 'react' -import { useIsRestoring } from './IsRestoringProvider' -import { useQueryClient } from './QueryClientProvider' -import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary' -import { - ensurePreventErrorBoundaryRetry, - getHasError, - useClearResetErrorBoundary, -} from './errorBoundaryUtils' -import { useObserverSnapshot } from './useObserverSnapshot' -import type { - QueryKey, - QueryObserverResult, -} from '@tanstack/query-types/bindings' -import type { QueryClient } from './runtime/queryClient' -import type { QueryObserver } from './runtime/queryObserver' -import type { suspenseQueryPolicy } from './suspense' -import type { UseBaseQueryOptions } from './types' - -/** - * Base implementation shared by `useQuery`, `useInfiniteQuery`, `useSuspenseQuery`, and - * `useSuspenseInfiniteQuery`. - * @param options - The options passed to the calling hook. - * @param Observer - The query observer class (`QueryObserver` or - * `InfiniteQueryObserver`). - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest - * context will be used. - * @param suspense - Render policy used by the dedicated Suspense hooks. - * @returns The query result, tracking which properties are read unless `notifyOnChangeProps` is - * set. - * @throws {Error} If `options` is not an object (outside production), or the query error when it should be - * thrown to the nearest error boundary (see `throwOnError`). While suspending, it throws a promise instead. - */ -export function useBaseQuery< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey extends QueryKey, ->( - options: UseBaseQueryOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey - >, - Observer: typeof QueryObserver, - queryClient?: QueryClient, - suspense?: typeof suspenseQueryPolicy, -): QueryObserverResult { - if (process.env.NODE_ENV !== 'production') { - if (typeof options !== 'object' || Array.isArray(options)) { - throw new Error( - 'Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object', - ) - } - } - - const isRestoring = useIsRestoring() - const errorResetBoundary = useQueryErrorResetBoundary() - const client = useQueryClient(queryClient) - const defaultedOptions = client.defaultQueryOptions({ - ...options, - suspense: !!suspense, - }) - - const query = client - .getQueryCache() - .get( - defaultedOptions.queryHash, - ) - - if (process.env.NODE_ENV !== 'production') { - if (!defaultedOptions.queryFn) { - console.error( - `[${defaultedOptions.queryHash}]: No query function was provided or configured in the query defaults. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`, - ) - } - } - - const subscribed = options.subscribed !== false - - // Make sure results are optimistically set in fetching state before subscribing or updating options - defaultedOptions._optimisticResults = isRestoring - ? 'isRestoring' - : subscribed - ? 'optimistic' - : undefined - - suspense?.prepare(defaultedOptions) - ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query) - useClearResetErrorBoundary(errorResetBoundary) - - const [observer] = React.useState( - () => - new Observer( - client, - defaultedOptions, - ), - ) - - const reader = observer.createResultReader(defaultedOptions) - - suspense?.readQuery( - defaultedOptions, - reader, - observer, - client, - errorResetBoundary, - ) - - const result = useObserverSnapshot( - observer, - reader, - !isRestoring && subscribed, - refreshQuery, - ) - - // Handle error boundary - if ( - getHasError({ - result, - errorResetBoundary, - throwOnError: defaultedOptions.throwOnError, - query, - suspense: defaultedOptions.suspense, - }) - ) { - throw result.error - } - - // Handle result property usage tracking - return !defaultedOptions.notifyOnChangeProps - ? observer.trackResult(result) - : result -} - -/** - * Refreshes the query after the observer subscribes. - * @param observer - The observer that was subscribed. - */ -function refreshQuery(observer: Pick): void { - observer.updateResult() -} diff --git a/packages/react-query-no-core/src/useMutationState.ts b/packages/react-query-no-core/src/useMutationState.ts deleted file mode 100644 index 07a2523779c..00000000000 --- a/packages/react-query-no-core/src/useMutationState.ts +++ /dev/null @@ -1,204 +0,0 @@ -'use client' -import * as React from 'react' -import { useQueryClient } from './QueryClientProvider' -import { notifyManager } from './runtime/notifyManager' -import { replaceEqualDeep } from './runtime/utils' -import type { MutationState } from '@tanstack/query-types/bindings' -import type { Mutation } from './runtime/mutation' -import type { MutationCache } from './runtime/mutationCache' -import type { QueryClient } from './runtime/queryClient' -import type { MutationFilters } from './runtime/utils' - -/** - * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending` - * (useful for app-wide loading indicators). - * @param filters - The {@link MutationFilters} to narrow down the matched mutations. - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will - * be used. - * @returns Will be the `number` of the mutations that your application currently has `pending`. - * @example - * ```tsx - * import { useIsMutating } from '@tanstack/react-query-no-core' - * - * function PostsMutatingIndicator() { - * // How many mutations matching the posts prefix are in progress? - * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] }) - * - * return isMutatingPosts ? Saving posts... : null - * } - * ``` - */ -export function useIsMutating( - filters?: Omit, - queryClient?: QueryClient, -): number { - const client = useQueryClient(queryClient) - return useMutationState( - { filters: { ...filters, status: 'pending' } }, - client, - ).length -} - -type MutationTypeFromResult = [TResult] extends [ - MutationState< - infer TData, - infer TError, - infer TVariables, - infer TOnMutateResult - >, -] - ? Mutation - : Mutation - -type MutationStateOptions< - TResult = MutationState, - TMutation extends Mutation = - MutationTypeFromResult, -> = { - filters?: MutationFilters - select?: (mutation: TMutation) => TResult -} - -/** - * Creates snapshot getters that share equal selected results across renders. - * A new getter is created on each render. Each getter caches its snapshot until the matching mutations - * or their states change. - * @returns A factory for snapshot getters with a shared result cache. - */ -function createSnapshotFactory< - TResult = MutationState, - TMutation extends Mutation = - MutationTypeFromResult, ->() { - let previousResult: Array | undefined - - return ( - mutationCache: MutationCache, - options: MutationStateOptions, - ) => { - let inputs: Array = [] - let snapshot: Array | undefined - - return (): Array => { - const mutations = mutationCache.findAll(options.filters) - const nextInputs = mutations.flatMap((mutation) => [ - mutation, - mutation.state, - ]) - - if ( - !snapshot || - nextInputs.length !== inputs.length || - nextInputs.some((input, index) => !Object.is(input, inputs[index])) - ) { - inputs = nextInputs - snapshot = replaceEqualDeep( - previousResult, - mutations.map( - (mutation): TResult => - (options.select - ? options.select(mutation as TMutation) - : mutation.state) as TResult, - ), - ) - previousResult = snapshot - } - - return snapshot - } - } -} - -/** - * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass - * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation - * state. - * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the - * mutation state. - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will - * be used. - * @returns Will be an Array of whatever `select` returns for each matching mutation. - * @example - * Get all variables of all running mutations: - * ```tsx - * import { useMutationState } from '@tanstack/react-query-no-core' - * - * function PendingPosts() { - * const pendingVariables = useMutationState({ - * filters: { status: 'pending' }, - * select: (mutation) => mutation.state.variables, - * }) - * - * return <>{pendingVariables.length} posts saving... - * } - * ``` - * @example - * Get all data for specific mutations via the `mutationKey`: - * ```tsx - * import { useMutation, useMutationState } from '@tanstack/react-query-no-core' - * - * const mutationKey = ['posts'] - * - * function Posts() { - * // Some mutation that we want to get the state for - * const mutation = useMutation({ - * mutationKey, - * mutationFn: createPosts, - * }) - * - * const savedPosts = useMutationState({ - * // this mutation key needs to match the mutation key of the given mutation (see above) - * filters: { mutationKey, status: 'success' }, - * select: (mutation) => mutation.state.data, - * }) - * - * return ( - * - * ) - * } - * ``` - * @example - * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new - * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the - * last item that `useMutationState` returns to get the latest successful invocation: - * ```tsx - * import { useMutationState } from '@tanstack/react-query-no-core' - * - * function LatestPost() { - * const savedPosts = useMutationState({ - * filters: { mutationKey: ['posts'], status: 'success' }, - * select: (mutation) => mutation.state.data, - * }) - * - * const latestSavedPost = savedPosts[savedPosts.length - 1] - * - * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'} - * } - * ``` - */ -export function useMutationState< - TResult = MutationState, - TMutation extends Mutation = - MutationTypeFromResult, ->( - options: MutationStateOptions = {}, - queryClient?: QueryClient, -): Array { - const mutationCache = useQueryClient(queryClient).getMutationCache() - const [createSnapshot] = React.useState(() => - createSnapshotFactory(), - ) - const getSnapshot = createSnapshot(mutationCache, options) - - return React.useSyncExternalStore( - React.useCallback( - (onStoreChange) => - mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)), - [mutationCache], - ), - getSnapshot, - getSnapshot, - ) -} diff --git a/packages/react-query-no-core/src/useObserverSnapshot.ts b/packages/react-query-no-core/src/useObserverSnapshot.ts deleted file mode 100644 index b02245410f1..00000000000 --- a/packages/react-query-no-core/src/useObserverSnapshot.ts +++ /dev/null @@ -1,43 +0,0 @@ -'use client' -import * as React from 'react' -import { notifyManager } from './runtime/notifyManager' -import { noop } from './runtime/utils' -import type { QueryObserverResultReader } from './runtime/queryObserver' - -interface ObserverStore { - subscribe: (listener: () => void) => () => void -} - -/** - * Commits a reader and subscribes React to its cached snapshots. - * @param observer - The observer that owns the subscription. - * @param reader - The reader scoped to the current render options. - * @param subscribed - Whether this render subscribes to updates. - * @param refresh - Includes updates that occurred before the subscription started. - * @returns The current snapshot. - */ -export function useObserverSnapshot( - observer: TObserver, - reader: QueryObserverResultReader, - subscribed: boolean, - refresh: (observer: TObserver) => void, -): TResult { - React.useEffect(() => { - reader.commit() - }, [reader]) - - return React.useSyncExternalStore( - React.useCallback( - (onStoreChange) => { - const unsubscribe = subscribed - ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) - : noop - refresh(observer) - return unsubscribe - }, - [observer, subscribed, refresh], - ), - reader.getSnapshot, - reader.getSnapshot, - ) -} diff --git a/packages/react-query-no-core/src/usePrefetchInfiniteQuery.tsx b/packages/react-query-no-core/src/usePrefetchInfiniteQuery.tsx deleted file mode 100644 index 04d1db27fbe..00000000000 --- a/packages/react-query-no-core/src/usePrefetchInfiniteQuery.tsx +++ /dev/null @@ -1,72 +0,0 @@ -import { useQueryClient } from './QueryClientProvider' -import { noop } from './runtime/utils' -import type { - DefaultError, - InfiniteData, - QueryKey, -} from '@tanstack/query-types/bindings' -import type { QueryClient } from './runtime/queryClient' -import type { UsePrefetchInfiniteQueryOptions } from './types' - -/** - * `usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render, - * before a suspense boundary that wraps a component that uses `useSuspenseInfiniteQuery`. You can pass - * everything to `usePrefetchInfiniteQuery` that you can pass to `queryClient.infiniteQuery`, though - * `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required. Pass `defaultQueryFn` to use the client defaults. - * - * `getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages, - * as well as pageParam information, and should return a single variable that will be passed to your query - * function as `context.pageParam`. Return `undefined` or `null` to indicate there is no next page available. - * - * The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left - * over from a previous attempt — so calling this on every render is cheap and won't refetch data that's - * already there or already in flight. - * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `queryClient.infiniteQuery`. - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will - * be used. - * @example - * ```tsx - * import { Suspense } from 'react' - * import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/react-query-no-core' - * - * const projectsOptions = infiniteQueryOptions({ - * queryKey: ['projects'], - * queryFn: ({ pageParam }) => fetchProjects(pageParam), - * initialPageParam: 0, - * getNextPageParam: (lastPage) => lastPage.nextId, - * }) - * - * function App() { - * // Fire the prefetch during render, before the suspense boundary below. - * usePrefetchInfiniteQuery(projectsOptions) - * - * return ( - * Loading projects...}> - * - * - * ) - * } - * ``` - */ -export function usePrefetchInfiniteQuery< - TQueryFnData = unknown, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, ->( - options: UsePrefetchInfiniteQueryOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - queryClient?: QueryClient, -): void { - const client = useQueryClient(queryClient) - - if (!client.getQueryState(options.queryKey)) { - void client.infiniteQuery(options).catch(noop) - } -} diff --git a/packages/react-query-no-core/src/useQueries.ts b/packages/react-query-no-core/src/useQueries.ts deleted file mode 100644 index b642c72e1b6..00000000000 --- a/packages/react-query-no-core/src/useQueries.ts +++ /dev/null @@ -1,482 +0,0 @@ -'use client' -import * as React from 'react' -import { useIsRestoring } from './IsRestoringProvider' -import { useQueryClient } from './QueryClientProvider' -import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary' -import { - ensurePreventErrorBoundaryRetry, - getHasError, - useClearResetErrorBoundary, -} from './errorBoundaryUtils' -import { QueriesObserver } from './runtime/queriesObserver' -import { useObserverSnapshot } from './useObserverSnapshot' -import type { - DefaultError, - OmitKeyof, - QueriesObserverOptions, - QueriesPlaceholderDataFunction, - QueryKey, -} from '@tanstack/query-types/bindings' -import type { QueryClient } from './runtime/queryClient' -import type { - QueryFunction, - QueryObserverOptions, - ThrowOnError, -} from './runtime/types' -import type { suspenseQueriesPolicy } from './suspense' -import type { - DefinedUseQueryResult, - UseQueryOptions, - UseQueryResult, -} from './types' - -// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`. -// `placeholderData` function always gets undefined passed -type UseQueryOptionsForUseQueries< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = OmitKeyof< - UseQueryOptions, - 'placeholderData' | 'subscribed' -> & { - placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction -} - -// Avoid TS depth-limit error in case of large array literal -type MAXIMUM_DEPTH = 20 - -// Widen the type of the symbol to enable type inference even if skipToken is not immutable. -type SkipTokenForUseQueries = symbol - -type GetUseQueryOptionsForUseQueries = - // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData } - T extends { - queryFnData: infer TQueryFnData - error?: infer TError - data: infer TData - } - ? UseQueryOptionsForUseQueries - : T extends { queryFnData: infer TQueryFnData; error?: infer TError } - ? UseQueryOptionsForUseQueries - : T extends { data: infer TData; error?: infer TError } - ? UseQueryOptionsForUseQueries - : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData] - T extends [infer TQueryFnData, infer TError, infer TData] - ? UseQueryOptionsForUseQueries - : T extends [infer TQueryFnData, infer TError] - ? UseQueryOptionsForUseQueries - : T extends [infer TQueryFnData] - ? UseQueryOptionsForUseQueries - : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided - T extends { - queryFn?: - | QueryFunction - | SkipTokenForUseQueries - select?: (data: any) => infer TData - throwOnError?: ThrowOnError - } - ? UseQueryOptionsForUseQueries< - TQueryFnData, - unknown extends TError ? DefaultError : TError, - unknown extends TData ? TQueryFnData : TData, - TQueryKey - > - : // Fallback - UseQueryOptionsForUseQueries - -// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult -type GetDefinedOrUndefinedQueryResult = T extends { - initialData?: infer TInitialData -} - ? unknown extends TInitialData - ? UseQueryResult - : TInitialData extends TData - ? DefinedUseQueryResult - : TInitialData extends () => infer TInitialDataResult - ? unknown extends TInitialDataResult - ? UseQueryResult - : TInitialDataResult extends TData - ? DefinedUseQueryResult - : UseQueryResult - : UseQueryResult - : UseQueryResult - -type GetUseQueryResult = - // Part 1: responsible for mapping explicit type parameter to function result, if object - T extends { queryFnData: any; error?: infer TError; data: infer TData } - ? GetDefinedOrUndefinedQueryResult - : T extends { queryFnData: infer TQueryFnData; error?: infer TError } - ? GetDefinedOrUndefinedQueryResult - : T extends { data: infer TData; error?: infer TError } - ? GetDefinedOrUndefinedQueryResult - : // Part 2: responsible for mapping explicit type parameter to function result, if tuple - T extends [any, infer TError, infer TData] - ? GetDefinedOrUndefinedQueryResult - : T extends [infer TQueryFnData, infer TError] - ? GetDefinedOrUndefinedQueryResult - : T extends [infer TQueryFnData] - ? GetDefinedOrUndefinedQueryResult - : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided - T extends { - queryFn?: - | QueryFunction - | SkipTokenForUseQueries - select?: (data: any) => infer TData - throwOnError?: ThrowOnError - } - ? GetDefinedOrUndefinedQueryResult< - T, - unknown extends TData ? TQueryFnData : TData, - unknown extends TError ? DefaultError : TError - > - : // Fallback - UseQueryResult - -/** - * The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's - * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements — past that, a tuple falls - * back to a single homogeneous options type. - * - * An opaque array (e.g. `unknown[]`) is returned as-is; a non-tuple array whose element type structurally - * matches a query options object is mapped per-element instead, still inferring each entry individually; any - * other non-tuple array — one whose element type doesn't match the expected options shape — falls back to - * that same homogeneous options type too. - * @template T - The type of the `queries` array as written at the call site. - * @template TResults - The internal accumulator that this type builds during recursion. It is not meant - * to be set explicitly. - * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not - * meant to be set explicitly. - */ -export type QueriesOptions< - T extends Array, - TResults extends Array = [], - TDepth extends ReadonlyArray = [], -> = TDepth['length'] extends MAXIMUM_DEPTH - ? Array - : T extends [] - ? [] - : T extends [infer Head] - ? [...TResults, GetUseQueryOptionsForUseQueries] - : T extends [infer Head, ...infer Tails] - ? QueriesOptions< - [...Tails], - [...TResults, GetUseQueryOptionsForUseQueries], - [...TDepth, 1] - > - : ReadonlyArray extends T - ? T - : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type! - // use this to infer the param types in the case of Array.map() argument - T extends Array< - UseQueryOptionsForUseQueries< - infer TQueryFnData, - infer TError, - infer TData, - infer TQueryKey - > - > - ? Array< - UseQueryOptionsForUseQueries< - TQueryFnData, - TError, - TData, - TQueryKey - > - > - : // Fallback - Array - -/** - * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each - * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped - * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a - * single homogeneous {@link UseQueryResult} type. - * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}. - * @template TResults - The internal accumulator that this type builds during recursion. It is not meant - * to be set explicitly. - * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not - * meant to be set explicitly. - */ -export type QueriesResults< - T extends Array, - TResults extends Array = [], - TDepth extends ReadonlyArray = [], -> = TDepth['length'] extends MAXIMUM_DEPTH - ? Array - : T extends [] - ? [] - : T extends [infer Head] - ? [...TResults, GetUseQueryResult] - : T extends [infer Head, ...infer Tails] - ? QueriesResults< - [...Tails], - [...TResults, GetUseQueryResult], - [...TDepth, 1] - > - : { [K in keyof T]: GetUseQueryResult } - -type UseQueriesInput, TCombinedResult> = { - /** - * An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and - * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and - * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData` - * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function. - */ - queries: - | readonly [...QueriesOptions] - | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries }] - /** - * Use this to combine the results of the queries into a single value. The result will be structurally - * shared to be as referentially stable as possible. - */ - combine?: (result: QueriesResults) => TCombinedResult - /** - * Set this to `false` to unsubscribe this observer from updates to the query cache. - * @defaultValue true - */ - subscribed?: boolean -} - -/** - * The `useQueries` hook can be used to fetch a variable number of queries. - * - * The `queries` key accepts an array with query option objects mostly identical to `useQuery` — the top-level - * `subscribed` option isn't accepted per query (see `placeholderData` below for another difference). A custom - * `QueryClient` is supplied once, as `useQueries`' own top-level second argument, rather than per query. - * - * Having the same query key more than once in the array of query objects may cause some data to be shared - * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired - * structure. - * - * The `combine` option can be used to combine the results of the queries into a single value. The result will - * be structurally shared to be as referentially stable as possible. - * @param options - The `queries` array to run, and the optional `combine` and `subscribed` options. - * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context - * will be used. - * @returns The combined result. Without `combine`, this is an array with all the query results, in the same - * order as the input. When `combine` is provided, this is the value returned by `combine` instead. - * @throws {Error} The error of the first query that should be thrown to the nearest error boundary (see - * `throwOnError`). While suspending, it throws a promise instead. - * @remarks The `combine` function only re-runs if it changed referentially, or if any of the query results - * changed. An inlined `combine` function, as shown in the example below, therefore runs on every render — wrap - * it in `useCallback`, or extract it to a stable function reference if it doesn't have any dependencies, to - * avoid that. - * - * Unlike `useQuery`, `useQueries` cannot infer the `data` argument of an _inline_ `select` from its sibling - * `queryFn`. Because `useQueries` infers the type of the whole `queries` array at once, the `select` parameter - * of a query object written inline cannot be contextually typed from that same object's `queryFn`, so it falls - * back to `unknown` — a [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate - * the `select` parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in - * a single object _before_ it reaches `useQueries`, to work around this — see the example below. The same - * limitation applies to {@link useSuspenseQueries}. - * - * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from - * previously rendered queries, because the number of queries can differ between renders. - * @example - * ```tsx - * import { useQueries } from '@tanstack/react-query-no-core' - * - * function Posts({ ids }: { ids: Array }) { - * const postQueries = useQueries({ - * queries: ids.map((id) => ({ - * queryKey: ['post', id], - * queryFn: () => fetchPost(id), - * staleTime: Infinity, - * })), - * }) - * - * return ( - *
      - * {postQueries.map((query, index) => { - * if (query.isPending) return
    • Loading...
    • - * if (query.isError) return
    • Error: {query.error.message}
    • - * return
    • {query.data.title}
    • - * })} - *
    - * ) - * } - * ``` - * @example - * Combining results into a single value: - * ```tsx - * import { useQueries } from '@tanstack/react-query-no-core' - * - * function Posts({ ids }: { ids: Array }) { - * const { data, isPending, isError } = useQueries({ - * queries: ids.map((id) => ({ - * queryKey: ['post', id], - * queryFn: () => fetchPost(id), - * })), - * combine: (postQueries) => { - * return { - * data: postQueries.map((query) => query.data), - * isPending: postQueries.some((query) => query.isPending), - * isError: postQueries.some((query) => query.isError), - * } - * }, - * }) - * - * if (isPending) return 'Loading...' - * if (isError) return 'Error loading posts' - * - * return ( - *
      - * {data.map((post) => ( - *
    • {post?.title}
    • - * ))} - *
    - * ) - * } - * ``` - * @example - * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding - * `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is - * resolved before it reaches `useQueries`: - * ```tsx - * import { queryOptions, useQueries } from '@tanstack/react-query-no-core' - * - * const postOptions = (id: number) => - * queryOptions({ - * queryKey: ['post', id], - * queryFn: () => fetchPost(id), - * }) - * - * function PostTitle({ id }: { id: number }) { - * const [{ data: broken }] = useQueries({ - * queries: [ - * { - * ...postOptions(id), - * // ❌ `data` is `unknown` here - * select: (data) => data.title, - * }, - * ], - * }) - * - * const [{ data: fixed }] = useQueries({ - * queries: [ - * queryOptions({ - * ...postOptions(id), - * // ✅ `data` is `Post` - * select: (data) => data.title, - * }), - * ], - * }) - * - * return

    {fixed}

    - * } - * ``` - */ -export function useQueries< - T extends Array, - TCombinedResult = QueriesResults, ->( - options: UseQueriesInput, - queryClient?: QueryClient, -): TCombinedResult { - return useBaseQueries(options, queryClient) -} - -/** - * Reads and subscribes to multiple queries. The dedicated Suspense hook can - * supply a render-time policy. - * @param options - The queries, combiner, and subscription setting. - * @param queryClient - The client to use in place of the nearest provider. - * @param suspense - The policy that prepares and reads queries during render. - * @returns The individual query results or the combined result. - * @throws {Error} The first query error configured to reach the error boundary. - */ -export function useBaseQueries< - T extends Array, - TCombinedResult = QueriesResults, ->( - { queries, ...options }: UseQueriesInput, - queryClient?: QueryClient, - suspense?: typeof suspenseQueriesPolicy, -): TCombinedResult { - const client = useQueryClient(queryClient) - const isRestoring = useIsRestoring() - const errorResetBoundary = useQueryErrorResetBoundary() - const subscribed = options.subscribed !== false - - const defaultedQueries = React.useMemo( - () => - queries.map((opts) => { - const defaultedOptions = client.defaultQueryOptions({ - ...opts, - suspense: !!suspense, - } as QueryObserverOptions) - - // Make sure the results are already in fetching state before subscribing or updating options - defaultedOptions._optimisticResults = isRestoring - ? 'isRestoring' - : subscribed - ? 'optimistic' - : undefined - - return defaultedOptions - }), - [queries, client, isRestoring, subscribed, suspense], - ) - - defaultedQueries.forEach((queryOptions) => { - suspense?.prepare(queryOptions) - const query = client.getQueryCache().get(queryOptions.queryHash) - ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query) - }) - - useClearResetErrorBoundary(errorResetBoundary) - - const [observer] = React.useState( - () => - new QueriesObserver( - client, - defaultedQueries, - options as QueriesObserverOptions, - ), - ) - - const reader = observer.createResultReader( - defaultedQueries, - options as QueriesObserverOptions, - ) - suspense?.readQueries(defaultedQueries, reader, client, errorResetBoundary) - - const results = useObserverSnapshot( - observer, - reader, - !isRestoring && subscribed, - refreshQueries, - ) - - const firstErrorResult = results.find((result, index) => { - const query = defaultedQueries[index] - return ( - query && - getHasError({ - result, - errorResetBoundary, - throwOnError: query.throwOnError, - query: client.getQueryCache().get(query.queryHash), - suspense: query.suspense, - }) - ) - }) - - if (firstErrorResult) { - throw firstErrorResult.error - } - - return reader.combineResult(results) -} - -/** - * Refreshes each query after the group subscribes. - * @param observer - The observer that was subscribed. - */ -function refreshQueries(observer: Pick): void { - observer - .getObservers() - .forEach((queryObserver) => queryObserver.updateResult()) -} diff --git a/packages/react-query-no-core/src/useQuery.ts b/packages/react-query-no-core/src/useQuery.ts deleted file mode 100644 index fadc6d866dc..00000000000 --- a/packages/react-query-no-core/src/useQuery.ts +++ /dev/null @@ -1,298 +0,0 @@ -'use client' -import { QueryObserver } from './runtime/queryObserver' -import { useBaseQuery } from './useBaseQuery' -import type { DefaultError, QueryKey } from '@tanstack/query-types/bindings' -import type { - DefinedInitialDataOptions, - UndefinedInitialDataOptions, -} from './queryOptions' -import type { QueryClient } from './runtime/queryClient' -import type { - DefinedUseQueryResult, - UseQueryOptions, - UseQueryResult, -} from './types' - -/** - * This overload is selected when `initialData` is known to be defined, so the resulting `data` is typed as never - * `undefined` (unless a `select` changes `TData` to include `undefined`). At runtime, `data` is still `undefined` - * if `select` throws on its first call. - * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `useQuery`, with `initialData` known to be defined. - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will - * be used. - * @returns The current query result, typed so that `status` is `success` or `error` (`status` never - * resolves to `pending` in this overload's type, since `initialData` guarantees data upfront). `status` is - * `error` if the query has an error from a fetch that failed after its retries or if `select` threw, and - * `success` otherwise. `isSuccess`/`isError` are derived booleans for convenience. - * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`. - * @example - * ```tsx - * import { useQuery } from '@tanstack/react-query-no-core' - * - * function Posts() { - * // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, - * // so the list stays visible alongside the error. - * const { data, isError, error } = useQuery({ - * queryKey: ['posts'], - * queryFn: fetchPosts, - * initialData: [], - * }) - * - * return ( - *
    - * {isError ? Error: {error.message} : null} - *
      - * {data.map((post) =>
    • {post.title}
    • )} - *
    - *
    - * ) - * } - * ``` - */ -export function useQuery< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - options: DefinedInitialDataOptions, - queryClient?: QueryClient, -): DefinedUseQueryResult - -/** - * This overload is selected when `initialData` is omitted, may be `undefined`, or is a function that may - * return `undefined`, so the resulting `data` can be `undefined`. - * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will - * be used. - * @returns The current query result. `status` is `error` if the query has an error from a fetch that failed - * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns - * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError` - * are derived booleans for convenience. - * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`. - * @example - * ```tsx - * import { useQuery } from '@tanstack/react-query-no-core' - * - * function Posts() { - * const { status, data, error, isFetching } = useQuery({ - * queryKey: ['posts'], - * queryFn: fetchPosts, - * }) - * - * if (status === 'pending') return 'Loading...' - * if (status === 'error') return Error: {error.message} - * - * return ( - *
    - *
      - * {data.map((post) => ( - *
    • {post.title}
    • - * ))} - *
    - *
    {isFetching ? 'Background Updating...' : ' '}
    - *
    - * ) - * } - * ``` - * @example - * The same query, checking `isPending`/`isError` instead of `status` — pick whichever reads better to you: - * ```tsx - * import { useQuery } from '@tanstack/react-query-no-core' - * - * function Posts() { - * const { isPending, isError, data, error } = useQuery({ - * queryKey: ['posts'], - * queryFn: fetchPosts, - * }) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return ( - *
      - * {data.map((post) =>
    • {post.title}
    • )} - *
    - * ) - * } - * ``` - */ -export function useQuery< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - options: UndefinedInitialDataOptions, - queryClient?: QueryClient, -): UseQueryResult - -/** - * Fallback overload for options whose `initialData` presence isn't statically known — for example, an - * object typed as {@link UseQueryOptions} rather than an object literal. Prefer one of the other overloads - * when possible, since they infer whether `data` can be `undefined` from `initialData` directly. - * @param options - The {@link UseQueryOptions} to use — everything you can pass to `useQuery`. - * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will - * be used. - * @returns The current query result. `status` is `error` if the query has an error from a fetch that failed - * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns - * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError` - * are derived booleans for convenience. - * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`. - * @example - * ```tsx - * import { useQuery } from '@tanstack/react-query-no-core' - * - * function Posts() { - * const { status, data, error, isFetching } = useQuery({ - * queryKey: ['posts'], - * queryFn: fetchPosts, - * }) - * - * if (status === 'pending') return 'Loading...' - * if (status === 'error') return Error: {error.message} - * - * return ( - *
    - *
      - * {data.map((post) => ( - *
    • {post.title}
    • - * ))} - *
    - *
    {isFetching ? 'Background Updating...' : ' '}
    - *
    - * ) - * } - * ``` - * @example - * `select` derives whatever `data` a component needs from the cached value, without changing what's - * actually stored in the cache — the cache still holds the full `Post[]`, but `data` here is a `number`: - * ```tsx - * import { useQuery } from '@tanstack/react-query-no-core' - * - * function PostCount() { - * const { data, isPending, isError, error } = useQuery({ - * queryKey: ['posts'], - * queryFn: fetchPosts, - * select: (posts) => posts.length, - * }) - * - * if (isPending) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return {data} posts - * } - * ``` - * @example - * A dependent query, only enabled once `postId` is set — use `isLoading`, not `isPending`, so the - * loading state doesn't show while the query is disabled: - * ```tsx - * import { useQuery } from '@tanstack/react-query-no-core' - * - * function Post({ postId }: { postId: number | undefined }) { - * const { data, isLoading, isError, error } = useQuery({ - * queryKey: ['post', postId], - * queryFn: () => fetchPost(postId!), - * enabled: postId != null, - * }) - * - * if (postId == null) return 'Select a post' - * if (isLoading) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return

    {data?.title}

    - * } - * ``` - * @example - * The same dependent query, type safe: `skipToken` disables the query without needing the - * non-null assertion above, since `queryFn` is only ever called when `postId` is defined. - * `refetch` doesn't work while `queryFn` is `skipToken` — use `enabled: false` instead if you - * need to trigger the query manually: - * ```tsx - * import { skipToken, useQuery } from '@tanstack/react-query-no-core' - * - * function Post({ postId }: { postId: number | undefined }) { - * const { data, isLoading, isError, error } = useQuery({ - * queryKey: ['post', postId], - * queryFn: postId != null ? () => fetchPost(postId) : skipToken, - * }) - * - * if (postId == null) return 'Select a post' - * if (isLoading) return 'Loading...' - * if (isError) return Error: {error.message} - * - * return

    {data?.title}

    - * } - * ``` - * @example - * Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries - * over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was - * fetched rather than from now: - * ```tsx - * import { useQuery, useQueryClient } from '@tanstack/react-query-no-core' - * - * function Post({ postId }: { postId: number }) { - * const queryClient = useQueryClient() - * - * const { data, isError, error } = useQuery({ - * queryKey: ['post', postId], - * queryFn: () => fetchPost(postId), - * initialData: () => - * queryClient - * .getQueryData>(['posts']) - * ?.find((post) => post.id === postId), - * initialDataUpdatedAt: () => - * queryClient.getQueryState(['posts'])?.dataUpdatedAt, - * }) - * - * if (isError) return Error: {error.message} - * - * return

    {data?.title}

    - * } - * ``` - * @example - * Paginated data, keeping the previous page's data visible while the next page loads: - * ```tsx - * import { keepPreviousData, useQuery } from '@tanstack/react-query-no-core' - * import { useState } from 'react' - * - * function Posts() { - * const [page, setPage] = useState(0) - * - * const { data, isPlaceholderData, isError, error } = useQuery({ - * queryKey: ['posts', page], - * queryFn: () => fetchPosts(page), - * placeholderData: keepPreviousData, - * }) - * - * if (isError) return Error: {error.message} - * - * return ( - *
    - *
      - * {data?.map((post) =>
    • {post.title}
    • )} - *
    - * - *
    - * ) - * } - * ``` - */ -export function useQuery< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, ->( - options: UseQueryOptions, - queryClient?: QueryClient, -): UseQueryResult - -export function useQuery(options: UseQueryOptions, queryClient?: QueryClient) { - return useBaseQuery(options, QueryObserver, queryClient) -} diff --git a/packages/react-query-no-core/src/useSuspenseQueries.ts b/packages/react-query-no-core/src/useSuspenseQueries.ts deleted file mode 100644 index 75f72b38067..00000000000 --- a/packages/react-query-no-core/src/useSuspenseQueries.ts +++ /dev/null @@ -1,547 +0,0 @@ -'use client' -import { skipToken } from './runtime/utils' -import { defaultThrowOnError, suspenseQueriesPolicy } from './suspense' -import { useBaseQueries } from './useQueries' -import type { - DefaultError, - OmitKeyof, - QueriesPlaceholderDataFunction, - QueryKey, -} from '@tanstack/query-types/bindings' -import type { QueryClient } from './runtime/queryClient' -import type { QueryFunction, ThrowOnError } from './runtime/types' -import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types' - -// `placeholderData` functions in useQueries never receive previous query data. -type UseSuspenseQueryOptionsForUseSuspenseQueries< - TQueryFnData = unknown, - TError = DefaultError, - TData = TQueryFnData, - TQueryKey extends QueryKey = QueryKey, -> = OmitKeyof< - UseSuspenseQueryOptions, - 'placeholderData' -> & { - placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction -} - -// Avoid TS depth-limit error in case of large array literal -type MAXIMUM_DEPTH = 20 - -// Widen the type of the symbol to enable type inference even if skipToken is not immutable. -type SkipTokenForUseQueries = symbol - -type GetUseSuspenseQueryOptions = - // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData } - T extends { - queryFnData: infer TQueryFnData - error?: infer TError - data: infer TData - } - ? UseSuspenseQueryOptionsForUseSuspenseQueries - : T extends { queryFnData: infer TQueryFnData; error?: infer TError } - ? UseSuspenseQueryOptionsForUseSuspenseQueries - : T extends { data: infer TData; error?: infer TError } - ? UseSuspenseQueryOptionsForUseSuspenseQueries - : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData] - T extends [infer TQueryFnData, infer TError, infer TData] - ? UseSuspenseQueryOptionsForUseSuspenseQueries< - TQueryFnData, - TError, - TData - > - : T extends [infer TQueryFnData, infer TError] - ? UseSuspenseQueryOptionsForUseSuspenseQueries - : T extends [infer TQueryFnData] - ? UseSuspenseQueryOptionsForUseSuspenseQueries - : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided - T extends { - queryFn?: - | QueryFunction - | SkipTokenForUseQueries - select?: (data: any) => infer TData - throwOnError?: ThrowOnError - } - ? UseSuspenseQueryOptionsForUseSuspenseQueries< - TQueryFnData, - TError, - TData, - TQueryKey - > - : T extends { - queryFn?: - | QueryFunction - | SkipTokenForUseQueries - throwOnError?: ThrowOnError - } - ? UseSuspenseQueryOptionsForUseSuspenseQueries< - TQueryFnData, - TError, - TQueryFnData, - TQueryKey - > - : // Fallback - UseSuspenseQueryOptionsForUseSuspenseQueries - -type GetUseSuspenseQueryResult = - // Part 1: responsible for mapping explicit type parameter to function result, if object - T extends { queryFnData: any; error?: infer TError; data: infer TData } - ? UseSuspenseQueryResult - : T extends { queryFnData: infer TQueryFnData; error?: infer TError } - ? UseSuspenseQueryResult - : T extends { data: infer TData; error?: infer TError } - ? UseSuspenseQueryResult - : // Part 2: responsible for mapping explicit type parameter to function result, if tuple - T extends [any, infer TError, infer TData] - ? UseSuspenseQueryResult - : T extends [infer TQueryFnData, infer TError] - ? UseSuspenseQueryResult - : T extends [infer TQueryFnData] - ? UseSuspenseQueryResult - : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided - T extends { - queryFn?: - | QueryFunction - | SkipTokenForUseQueries - select?: (data: any) => infer TData - throwOnError?: ThrowOnError - } - ? UseSuspenseQueryResult< - unknown extends TData ? TQueryFnData : TData, - unknown extends TError ? DefaultError : TError - > - : T extends { - queryFn?: - | QueryFunction - | SkipTokenForUseQueries - throwOnError?: ThrowOnError - } - ? UseSuspenseQueryResult< - TQueryFnData, - unknown extends TError ? DefaultError : TError - > - : // Fallback - UseSuspenseQueryResult - -/** - * The `queries` array accepted by `useSuspenseQueries`. Recursively unwraps each tuple element so every - * entry's `queryFn`/`select` are inferred individually, up to 20 elements — past that, a tuple falls back to - * a single homogeneous {@link UseSuspenseQueryOptions} type. - * - * An opaque array (e.g. `unknown[]`) is returned as-is; a non-tuple array whose element type structurally - * matches a query options object is mapped per-element instead, still inferring each entry individually; any - * other non-tuple array — one whose element type doesn't match the expected options shape — falls back to - * that same homogeneous options type too. - * @template T - The type of the `queries` array as written at the call site. - * @template TResults - The internal accumulator that this type builds during recursion. It is not meant - * to be set explicitly. - * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not - * meant to be set explicitly. - */ -export type SuspenseQueriesOptions< - T extends Array, - TResults extends Array = [], - TDepth extends ReadonlyArray = [], -> = TDepth['length'] extends MAXIMUM_DEPTH - ? Array - : T extends [] - ? [] - : T extends [infer Head] - ? [...TResults, GetUseSuspenseQueryOptions] - : T extends [infer Head, ...infer Tails] - ? SuspenseQueriesOptions< - [...Tails], - [...TResults, GetUseSuspenseQueryOptions], - [...TDepth, 1] - > - : Array extends T - ? T - : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type! - // use this to infer the param types in the case of Array.map() argument - T extends Array< - UseSuspenseQueryOptionsForUseSuspenseQueries< - infer TQueryFnData, - infer TError, - infer TData, - infer TQueryKey - > - > - ? Array< - UseSuspenseQueryOptionsForUseSuspenseQueries< - TQueryFnData, - TError, - TData, - TQueryKey - > - > - : // Fallback - Array - -/** - * The result type returned by `useSuspenseQueries`, when no `combine` is provided. Mirrors - * {@link SuspenseQueriesOptions}: each tuple element's result type is inferred individually, up to 20 elements. - * A non-tuple array is mapped per-element instead, still inferring each entry individually; only past 20 - * elements does this fall back to a single homogeneous {@link UseSuspenseQueryResult} type. - * @template T - The type of the `queries` array, as inferred by {@link SuspenseQueriesOptions}. - * @template TResults - The internal accumulator that this type builds during recursion. It is not meant - * to be set explicitly. - * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not - * meant to be set explicitly. - */ -export type SuspenseQueriesResults< - T extends Array, - TResults extends Array = [], - TDepth extends ReadonlyArray = [], -> = TDepth['length'] extends MAXIMUM_DEPTH - ? Array - : T extends [] - ? [] - : T extends [infer Head] - ? [...TResults, GetUseSuspenseQueryResult] - : T extends [infer Head, ...infer Tails] - ? SuspenseQueriesResults< - [...Tails], - [...TResults, GetUseSuspenseQueryResult], - [...TDepth, 1] - > - : { [K in keyof T]: GetUseSuspenseQueryResult } - -/** - * The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed` - * option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`. - * @param options - The `queries` array to run in Suspense, and an optional `combine` function. - * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context - * will be used. - * @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be - * defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived - * flags set accordingly). - * - * Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone - * stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid - * this, make sure to set a high enough `staleTime`. Cancellation does not work. - * @example - * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is - * required around ``. A failed background refetch instead continues to render the cached data. - * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: - * ```tsx - * import { Suspense } from 'react' - * import { ErrorBoundary } from 'react-error-boundary' - * import { - * QueryErrorResetBoundary, - * useSuspenseQueries, - * } from '@tanstack/react-query-no-core' - * - * function Posts({ ids }: { ids: Array }) { - * // Every result is guaranteed to be defined — no per-query `isPending` check needed. - * const postQueries = useSuspenseQueries({ - * queries: ids.map((id) => ({ - * queryKey: ['post', id], - * queryFn: () => fetchPost(id), - * })), - * }) - * - * return ( - *
      - * {postQueries.map((query) => ( - *
    • {query.data.title}
    • - * ))} - *
    - * ) - * } - * - * function App() { - * return ( - * - * {({ reset }) => ( - * ( - *
    - * There was an error! - * - *
    - * )} - * > - * Loading posts...}> - * - * - *
    - * )} - *
    - * ) - * } - * ``` - * @example - * Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so - * they fetch in parallel rather than suspending one after another: - * ```tsx - * import { Suspense } from 'react' - * import { ErrorBoundary } from 'react-error-boundary' - * import { - * QueryErrorResetBoundary, - * useSuspenseQueries, - * } from '@tanstack/react-query-no-core' - * - * function Dashboard() { - * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({ - * queries: [ - * { queryKey: ['users'], queryFn: fetchUsers }, - * { queryKey: ['teams'], queryFn: fetchTeams }, - * { queryKey: ['projects'], queryFn: fetchProjects }, - * ], - * }) - * - * return ( - *
    - * - * - * - *
    - * ) - * } - * - * function App() { - * return ( - * - * {({ reset }) => ( - * ( - *
    - * There was an error! - * - *
    - * )} - * > - * Loading dashboard...}> - * - * - *
    - * )} - *
    - * ) - * } - * ``` - * @example - * `combine`s the results into a single boolean, so `Refresh` only re-renders when that boolean changes, - * not on every individual query update. This overload is the only one that accepts `combine`: - * ```tsx - * import { Suspense } from 'react' - * import { ErrorBoundary } from 'react-error-boundary' - * import { - * QueryErrorResetBoundary, - * useSuspenseQueries, - * } from '@tanstack/react-query-no-core' - * - * function Refresh() { - * const anyFetching = useSuspenseQueries({ - * queries: [ - * { queryKey: ['users'], queryFn: fetchUsers }, - * { queryKey: ['teams'], queryFn: fetchTeams }, - * ], - * combine: (results) => results.some((result) => result.isFetching), - * }) - * - * return anyFetching ? Refreshing… : null - * } - * - * function App() { - * return ( - * - * {({ reset }) => ( - * ( - *
    - * There was an error! - * - *
    - * )} - * > - * Loading dashboard...}> - * - * - *
    - * )} - *
    - * ) - * } - * ``` - */ -export function useSuspenseQueries< - T extends Array, - TCombinedResult = SuspenseQueriesResults, ->( - options: { - /** - * An array with query option objects identical to `useSuspenseQuery`. - */ - queries: - | readonly [...SuspenseQueriesOptions] - | readonly [...{ [K in keyof T]: GetUseSuspenseQueryOptions }] - /** - * Use this to combine the results of the queries into a single value. The result will be structurally - * shared to be as referentially stable as possible. - */ - combine?: (result: SuspenseQueriesResults) => TCombinedResult - }, - queryClient?: QueryClient, -): TCombinedResult - -/** - * The options for `useSuspenseQueries` are the same as for `useQueries`, except that the top-level `subscribed` - * option isn't supported, and each `query` can't have `throwOnError`, `enabled`, or `placeholderData`. - * @param options - The `queries` array to run in Suspense, and an optional `combine` function. - * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context - * will be used. - * @returns The same structure as `useQueries`, except that for each `query`, `data` is guaranteed to be - * defined, `isPlaceholderData` is missing, and `status` is either `success` or `error` (with the derived - * flags set accordingly). - * - * Caveat: the component will only re-mount after all queries have finished loading. Hence, if a query has gone - * stale in the time it took for all the queries to complete, it will be fetched again at re-mount. To avoid - * this, make sure to set a high enough `staleTime`. Cancellation does not work. - * @example - * The query error is thrown if a fetch fails and no cached data exists yet, so an error boundary is - * required around ``. A failed background refetch instead continues to render the cached data. - * Use {@link QueryErrorResetBoundary} to let the user retry after such an error: - * ```tsx - * import { Suspense } from 'react' - * import { ErrorBoundary } from 'react-error-boundary' - * import { - * QueryErrorResetBoundary, - * useSuspenseQueries, - * } from '@tanstack/react-query-no-core' - * - * function Posts({ ids }: { ids: Array }) { - * // Every result is guaranteed to be defined — no per-query `isPending` check needed. - * const postQueries = useSuspenseQueries({ - * queries: ids.map((id) => ({ - * queryKey: ['post', id], - * queryFn: () => fetchPost(id), - * })), - * }) - * - * return ( - *
      - * {postQueries.map((query) => ( - *
    • {query.data.title}
    • - * ))} - *
    - * ) - * } - * - * function App() { - * return ( - * - * {({ reset }) => ( - * ( - *
    - * There was an error! - * - *
    - * )} - * > - * Loading posts...}> - * - * - *
    - * )} - *
    - * ) - * } - * ``` - * @example - * Several different queries — use `useSuspenseQueries` instead of multiple `useSuspenseQuery` calls, so - * they fetch in parallel rather than suspending one after another: - * ```tsx - * import { Suspense } from 'react' - * import { ErrorBoundary } from 'react-error-boundary' - * import { - * QueryErrorResetBoundary, - * useSuspenseQueries, - * } from '@tanstack/react-query-no-core' - * - * function Dashboard() { - * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({ - * queries: [ - * { queryKey: ['users'], queryFn: fetchUsers }, - * { queryKey: ['teams'], queryFn: fetchTeams }, - * { queryKey: ['projects'], queryFn: fetchProjects }, - * ], - * }) - * - * return ( - *
    - * - * - * - *
    - * ) - * } - * - * function App() { - * return ( - * - * {({ reset }) => ( - * ( - *
    - * There was an error! - * - *
    - * )} - * > - * Loading dashboard...}> - * - * - *
    - * )} - *
    - * ) - * } - * ``` - */ -export function useSuspenseQueries< - T extends Array, - TCombinedResult = SuspenseQueriesResults, ->( - options: { - /** - * An array with query option objects identical to `useSuspenseQuery`. - */ - queries: readonly [...SuspenseQueriesOptions] - /** - * Use this to combine the results of the queries into a single value. The result will be structurally - * shared to be as referentially stable as possible. - */ - combine?: (result: SuspenseQueriesResults) => TCombinedResult - }, - queryClient?: QueryClient, -): TCombinedResult - -export function useSuspenseQueries(options: any, queryClient?: QueryClient) { - return useBaseQueries( - { - ...options, - queries: options.queries.map((query: any) => { - if (process.env.NODE_ENV !== 'production') { - if (query.queryFn === skipToken) { - console.error('skipToken is not allowed for useSuspenseQueries') - } - } - - return { - ...query, - throwOnError: defaultThrowOnError, - enabled: true, - } - }), - }, - queryClient, - suspenseQueriesPolicy, - ) -} diff --git a/packages/react-query-no-core/tsconfig.json b/packages/react-query-no-core/tsconfig.json deleted file mode 100644 index 4ad3357ad95..00000000000 --- a/packages/react-query-no-core/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "compilerOptions": { - "outDir": "./dist-ts", - "rootDir": ".", - "jsx": "react-jsx" - }, - "include": [ - "src", - "test-setup.ts", - "*.config.ts", - "*.config.js", - "package.json" - ] -} diff --git a/packages/react-query-no-core/tsconfig.legacy.json b/packages/react-query-no-core/tsconfig.legacy.json deleted file mode 100644 index 20f2156d95b..00000000000 --- a/packages/react-query-no-core/tsconfig.legacy.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "jsx": "react-jsx", - "outDir": "./dist-ts/legacy" - }, - "include": ["src"], - "exclude": ["src/__tests__"] -} diff --git a/packages/react-query-no-core/tsconfig.prod.json b/packages/react-query-no-core/tsconfig.prod.json deleted file mode 100644 index 2bb29fdf02a..00000000000 --- a/packages/react-query-no-core/tsconfig.prod.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "extends": "./tsconfig.json", - "compilerOptions": { - "incremental": false, - "composite": false, - "rootDir": "../../" - }, - "include": ["src"], - "exclude": ["src/__tests__"] -} diff --git a/packages/react-query-no-core/tsdown.config.ts b/packages/react-query-no-core/tsdown.config.ts deleted file mode 100644 index f5cddcb4317..00000000000 --- a/packages/react-query-no-core/tsdown.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { defineConfig } from 'tsdown' -import { getTsdownConfig } from './root.tsdown.config.js' - -export default defineConfig({ - ...getTsdownConfig({ entry: ['src/index.ts'] }), - // Keep React client directives on the hooks and providers that own them. - unbundle: true, -}) diff --git a/packages/react-query-pluggable/README.md b/packages/react-query-pluggable/README.md new file mode 100644 index 00000000000..fc3a6113d2d --- /dev/null +++ b/packages/react-query-pluggable/README.md @@ -0,0 +1,168 @@ +# @tanstack/react-query-pluggable + +An experimental ESM React Query adapter for React 19. A `QueryClient` holds cache state and configuration. Import client operations and optional query features where you use them. + +The adapter uses `@tanstack/query-core` for fetching retries, cancellation, garbage collection, key comparison and structural sharing. It also uses the same focus, online, timeout and environment managers as the other adapters. Configuring one of those managers affects every adapter that uses that copy of core. + +```tsx +import { + QueryClient, + QueryClientProvider, + refetchInterval, + useQuery, +} from '@tanstack/react-query-pluggable' + +const client = new QueryClient() + +function Orders() { + const { data } = useQuery({ + queryKey: ['orders'], + queryFn: fetchOrders, + refetchInterval: refetchInterval(3000), + }) + return

    {data?.length} orders

    +} + +export function App() { + return ( + + + + ) +} +``` + +`useQuery`, `useInfiniteQuery`, `useSuspenseQuery` and `useSuspenseInfiniteQuery` accept the same helper, as do query defaults. Pass a callback to compute the next interval from the cached query. Return `false` or `undefined` to stop polling. + +```ts +useQuery({ + queryKey: ['job', jobId], + queryFn: () => fetchJob(jobId), + refetchInterval: (query) => + query.state.data?.status === 'complete' ? false : refetchInterval(3000), +}) +``` + +Polling runs while an enabled observer has subscribers and the window is focused. Set `refetchIntervalInBackground: true` to keep polling in the background. Each observer manages its own timer, including when several observers share a client default. + +## Choosing how a query renders + +`useQuery(query(options))` returns a pending result while an uncached query loads. Pass +`suspenseQuery(options)` to the same hook to show the nearest React `` fallback +until data is available. Both readers use the same client and cache key. The `query` export +is an alias of `queryOptions`. Only `suspenseQuery` imports the single-query Suspense policy. + +```tsx +import { query, suspenseQuery, useQuery } from '@tanstack/react-query-pluggable' + +const postOptions = (id: number) => + query({ queryKey: ['post', id], queryFn: () => fetchPost(id) }) + +function PostPreview({ id }: { id: number }) { + const post = useQuery(postOptions(id)) + return

    {post.isPending ? 'Loading…' : post.data?.title}

    +} + +// Render inside Loading…

    }>. +function PostTitle({ id }: { id: number }) { + const post = useQuery(suspenseQuery(postOptions(id))) + return

    {post.data.title}

    +} +``` + +The Suspense policy sends a failed query without cached data to the nearest error boundary. +Passing `skipToken` skips the fetch and can yield undefined data. `useSuspenseQuery(options)` +is a shorthand for `useQuery(suspenseQuery(options))`. + +### Paginated queries with the same hook + +Build the observer with `infiniteQuery`. Wrap those options in `suspenseQuery` when React +should show a parent fallback while loading the first page. Both forms expose `fetchNextPage`, +`hasNextPage`, and the cached `pages` and `pageParams`. + +```tsx +import { + infiniteQuery, + suspenseQuery, + useQuery, +} from '@tanstack/react-query-pluggable' + +const postPages = infiniteQuery({ + queryKey: ['posts', 'pages'], + initialPageParam: 0, + queryFn: ({ pageParam }) => fetchPostPage(pageParam), + getNextPageParam: (lastPage) => lastPage.nextCursor, +}) + +function Posts() { + const result = useQuery(suspenseQuery(postPages)) + return ( + <> + {result.data.pages.map((page) => ( + + ))} + + + ) +} +``` + +Use `useQuery(postPages)` to handle the pending state inside the component. Outside React, import +`fetchInfiniteQuery` to fetch and cache pages by calling `fetchInfiniteQuery(client, postPages)`. + +## Selecting and keeping data + +`select` maps the cached value for one observer. `placeholderData` supplies a temporary value for a pending query. Wrap a typed selector in `select(getTitle)`, or use the tuple form to infer an inline callback's argument from the query. For example, this hook keeps displaying the previous post title while the next post loads. + +```tsx +import { + keepPreviousData, + placeholderData, + select, + useQuery, +} from '@tanstack/react-query-pluggable' + +function usePostTitle(id: number) { + return useQuery({ + queryKey: ['post', id], + queryFn: () => fetchPost(id), // Promise<{ title: string }> + select: [select, (post) => post.title], + placeholderData: placeholderData(keepPreviousData), + }) +} +``` + +## Client operations + +The `QueryClient` constructor creates the state shared by hooks, providers and imperative callers. All operations on that client are named functions. Pass the client first, followed by the arguments you would pass to the v6 method. + +```ts +import { + fetchQuery, + fetchInfiniteQuery, + getQueryData, + invalidateQueries, + setQueryData, +} from '@tanstack/react-query-pluggable' + +const order = await fetchQuery(client, orderOptions) +const cached = getQueryData(client, orderOptions.queryKey) +setQueryData(client, orderOptions.queryKey, updatedOrder) +await fetchInfiniteQuery(client, orderPageOptions) +await invalidateQueries(client, { queryKey: ['orders'] }) +``` + +For example, `client.query(options)` becomes `fetchQuery(client, options)` and `client.clear()` becomes `clearQueryClient(client)`. The provider manages mounting for React users. Integrations that managed the v6 lifecycle directly can call `mountQueryClient(client)` and `unmountQueryClient(client)`. The same client-first convention applies to defaults, mutation resumption and bulk cache operations. + +Use `getQueryCache(client)` and `getMutationCache(client)` for direct cache access. Cache objects keep methods such as `.subscribe(listener)`, `.find(filters)`, and `.getAll()`. The stock `@tanstack/query-persist-client-core` subscription calls `client.getQueryCache()` and `client.getMutationCache()`. A custom persistence integration for this adapter must subscribe through the named accessors and use this adapter’s `hydrate` and `dehydrate`. + +## Mutations + +`useMutation`, `useMutationState`, and `useIsMutating` acquire the client's mutation cache on demand. `getMutationCache(client)` creates a default cache on first use or returns a cache supplied to the constructor. A query-only app can omit the mutation cache implementation. + +Pass `scope: serialScope('orders')` to `useMutation` to run mutations with that ID one at a time within a cache. The scope ID survives dehydration and hydration. The `queryOptions`, `infiniteQueryOptions`, and `mutationOptions` helpers preserve their TypeScript inference and share one JavaScript identity function. diff --git a/packages/react-query-no-core-pluggable/oxlint.config.ts b/packages/react-query-pluggable/oxlint.config.ts similarity index 100% rename from packages/react-query-no-core-pluggable/oxlint.config.ts rename to packages/react-query-pluggable/oxlint.config.ts diff --git a/packages/react-query-no-core-pluggable/package.json b/packages/react-query-pluggable/package.json similarity index 92% rename from packages/react-query-no-core-pluggable/package.json rename to packages/react-query-pluggable/package.json index bb44c15d920..e6a08663d84 100644 --- a/packages/react-query-no-core-pluggable/package.json +++ b/packages/react-query-pluggable/package.json @@ -1,5 +1,5 @@ { - "name": "@tanstack/react-query-no-core-pluggable", + "name": "@tanstack/react-query-pluggable", "version": "5.108.4", "description": "Experimental ESM React Query adapter with per-option features and tree-shakable cache operations", "author": "tannerlinsley", @@ -7,7 +7,7 @@ "repository": { "type": "git", "url": "git+https://github.com/TanStack/query.git", - "directory": "packages/react-query-no-core-pluggable" + "directory": "packages/react-query-pluggable" }, "homepage": "https://tanstack.com/query", "funding": { @@ -49,13 +49,16 @@ "!src/__tests__" ], "dependencies": { - "@tanstack/query-types": "workspace:*" + "@tanstack/query-core": "workspace:*" }, "devDependencies": { "@eslint-react/eslint-plugin": "catalog:", + "@testing-library/react": "catalog:", "@types/react": "catalog:", + "@types/react-dom": "catalog:", "eslint-plugin-react-hooks": "catalog:", "react": "catalog:", + "react-dom": "catalog:", "typescript": "catalog:" }, "peerDependencies": { diff --git a/packages/query-types/root.oxlint.config.ts b/packages/react-query-pluggable/root.oxlint.config.ts similarity index 100% rename from packages/query-types/root.oxlint.config.ts rename to packages/react-query-pluggable/root.oxlint.config.ts diff --git a/packages/query-types/root.tsdown.config.js b/packages/react-query-pluggable/root.tsdown.config.js similarity index 100% rename from packages/query-types/root.tsdown.config.js rename to packages/react-query-pluggable/root.tsdown.config.js diff --git a/packages/react-query-no-core-pluggable/src/HydrationBoundary.tsx b/packages/react-query-pluggable/src/HydrationBoundary.tsx similarity index 93% rename from packages/react-query-no-core-pluggable/src/HydrationBoundary.tsx rename to packages/react-query-pluggable/src/HydrationBoundary.tsx index d88e7601a54..cc55339b646 100644 --- a/packages/react-query-no-core-pluggable/src/HydrationBoundary.tsx +++ b/packages/react-query-pluggable/src/HydrationBoundary.tsx @@ -2,7 +2,8 @@ import * as React from 'react' import { useQueryClient } from './QueryClientProvider' import { hydrateQueries } from './runtime/hydration' -import type { DehydratedState, OmitKeyof } from '@tanstack/query-types/bindings' +import { getQueryCache } from './runtime/queryClient' +import type { DehydratedState, OmitKeyof } from '@tanstack/query-core' import type { HydrateOptions } from './runtime/hydration' import type { QueryClient } from './runtime/queryClient' @@ -49,7 +50,7 @@ export interface HydrationBoundaryProps { * after commit. * @example * ```tsx - * import { HydrationBoundary } from '@tanstack/react-query-no-core-pluggable' + * import { HydrationBoundary } from '@tanstack/react-query-pluggable' * * function App() { * return ... @@ -58,13 +59,12 @@ export interface HydrationBoundaryProps { * @example * Server-side prefetch handed off to the client via `dehydrate`: * ```tsx - * import { HydrationBoundary, dehydrate, noop } from '@tanstack/react-query-no-core-pluggable' + * import { HydrationBoundary, dehydrate, noop, fetchQuery } from '@tanstack/react-query-pluggable' * * async function ServerComponent() { * const queryClient = getQueryClient() * - * await queryClient - * .query({ + * await fetchQuery(queryClient, { * queryKey: ['posts'], * queryFn: fetchPosts, * }) @@ -95,7 +95,7 @@ export const HydrationBoundary = ({ // Hydrate existing queries after commit so an aborted transition cannot update them. const hydrationQueue: DehydratedState['queries'] | undefined = React.useMemo(() => { - const queryCache = client.getQueryCache() + const queryCache = getQueryCache(client) const newQueries: DehydratedState['queries'] = [] const existingQueries: DehydratedState['queries'] = [] diff --git a/packages/react-query-no-core-pluggable/src/IsRestoringProvider.ts b/packages/react-query-pluggable/src/IsRestoringProvider.ts similarity index 100% rename from packages/react-query-no-core-pluggable/src/IsRestoringProvider.ts rename to packages/react-query-pluggable/src/IsRestoringProvider.ts diff --git a/packages/react-query-no-core-pluggable/src/QueryClientProvider.tsx b/packages/react-query-pluggable/src/QueryClientProvider.tsx similarity index 88% rename from packages/react-query-no-core-pluggable/src/QueryClientProvider.tsx rename to packages/react-query-pluggable/src/QueryClientProvider.tsx index e307347cfea..3e3f822d84d 100644 --- a/packages/react-query-no-core-pluggable/src/QueryClientProvider.tsx +++ b/packages/react-query-pluggable/src/QueryClientProvider.tsx @@ -1,5 +1,6 @@ 'use client' import * as React from 'react' +import { mountQueryClient, unmountQueryClient } from './runtime/queryClient' import type { QueryClient } from './runtime/queryClient' /** @@ -49,14 +50,14 @@ export type QueryClientProviderProps = { /** * Use the `QueryClientProvider` component to connect and provide a `QueryClient` to your application. Also - * calls `client.mount()`/`client.unmount()` as this component mounts/unmounts, which subscribes the client to + * calls `mountQueryClient(client)`/`unmountQueryClient(client)` as this component mounts/unmounts, which subscribes the client to * focus/online events (resuming any paused mutations and refetching as needed when the app regains focus or * comes back online). * @param props - The `client` to provide, and the `children` that get access to it. * @returns The provided `children`, wrapped so they can read the `QueryClient` via `useQueryClient`. * @example * ```tsx - * import { QueryClient, QueryClientProvider } from '@tanstack/react-query-no-core-pluggable' + * import { QueryClient, QueryClientProvider } from '@tanstack/react-query-pluggable' * * const queryClient = new QueryClient() * @@ -70,9 +71,9 @@ export const QueryClientProvider = ({ children, }: QueryClientProviderProps): React.JSX.Element => { React.useEffect(() => { - client.mount() + mountQueryClient(client) return () => { - client.unmount() + unmountQueryClient(client) } }, [client]) diff --git a/packages/react-query-no-core/src/QueryErrorResetBoundary.tsx b/packages/react-query-pluggable/src/QueryErrorResetBoundary.tsx similarity index 99% rename from packages/react-query-no-core/src/QueryErrorResetBoundary.tsx rename to packages/react-query-pluggable/src/QueryErrorResetBoundary.tsx index 41e745b6579..a8835dea36b 100644 --- a/packages/react-query-no-core/src/QueryErrorResetBoundary.tsx +++ b/packages/react-query-pluggable/src/QueryErrorResetBoundary.tsx @@ -78,7 +78,7 @@ const QueryErrorResetBoundaryContext = React.createContext(createValue()) * @example * ```tsx * import { ErrorBoundary } from 'react-error-boundary' - * import { useQueryErrorResetBoundary } from '@tanstack/react-query-no-core' + * import { useQueryErrorResetBoundary } from '@tanstack/react-query-pluggable' * * function App({ children }: { children: React.ReactNode }) { * const { reset } = useQueryErrorResetBoundary() @@ -134,7 +134,7 @@ export interface QueryErrorResetBoundaryProps { * @example * ```tsx * import { ErrorBoundary } from 'react-error-boundary' - * import { QueryErrorResetBoundary } from '@tanstack/react-query-no-core' + * import { QueryErrorResetBoundary } from '@tanstack/react-query-pluggable' * * function App() { * return ( diff --git a/packages/react-query-no-core-pluggable/src/__tests__/cacheOperations.test.ts b/packages/react-query-pluggable/src/__tests__/cacheOperations.test.ts similarity index 68% rename from packages/react-query-no-core-pluggable/src/__tests__/cacheOperations.test.ts rename to packages/react-query-pluggable/src/__tests__/cacheOperations.test.ts index 4aac92faf61..2c37ab62532 100644 --- a/packages/react-query-no-core-pluggable/src/__tests__/cacheOperations.test.ts +++ b/packages/react-query-pluggable/src/__tests__/cacheOperations.test.ts @@ -6,15 +6,20 @@ import { removeQueries, setQueriesData, } from '..' +import { + getQueryData, + getQueryState, + setQueryData, +} from '../runtime/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'] } - client.setQueryData(['posts', 1], 2) - client.setQueryData(['posts', 2], 3) - otherClient.setQueryData(['posts', 1], 10) + 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([ @@ -22,9 +27,9 @@ describe('cache operations', () => { [['posts', 2], 6], ]) await invalidateQueries(client, { ...filters, refetchType: 'none' }) - expect(client.getQueryState(['posts', 1])?.isInvalidated).toBe(true) + expect(getQueryState(client, ['posts', 1])?.isInvalidated).toBe(true) removeQueries(client, filters) expect(getQueriesData(client, filters)).toStrictEqual([]) - expect(otherClient.getQueryData(['posts', 1])).toBe(10) + expect(getQueryData(otherClient, ['posts', 1])).toBe(10) }) }) diff --git a/packages/react-query-no-core-pluggable/src/__tests__/infiniteQuery.test.ts b/packages/react-query-pluggable/src/__tests__/fetchInfiniteQuery.test.ts similarity index 75% rename from packages/react-query-no-core-pluggable/src/__tests__/infiniteQuery.test.ts rename to packages/react-query-pluggable/src/__tests__/fetchInfiniteQuery.test.ts index 9cf9afe9e57..c21430a261e 100644 --- a/packages/react-query-no-core-pluggable/src/__tests__/infiniteQuery.test.ts +++ b/packages/react-query-pluggable/src/__tests__/fetchInfiniteQuery.test.ts @@ -2,13 +2,18 @@ import { describe, expect, expectTypeOf, it, vi } from 'vitest' import { QueryClient, dehydrate, + fetchInfiniteQuery, hydrate, - infiniteQuery, refetchQueries, } from '..' +import { + clearQueryClient, + getQueryData, + setQueryDefaults, +} from '../runtime/queryClient' import type { InfiniteData } from '..' -describe('infiniteQuery', () => { +describe('fetchInfiniteQuery', () => { it('refetches hydrated pages before any observer subscribes', async () => { const server = new QueryClient() const client = new QueryClient() @@ -24,25 +29,25 @@ describe('infiniteQuery', () => { pages: 2, } - const promise = infiniteQuery(server, options) + const promise = fetchInfiniteQuery(server, options) expectTypeOf(promise).toEqualTypeOf>>() expect( fetchPage.mock.calls.map(([context]) => context.pageParam), ).toStrictEqual([0]) await promise - client.setQueryDefaults(queryKey, options) + 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(client.getQueryData(queryKey)).toStrictEqual({ + expect(getQueryData(client, queryKey)).toStrictEqual({ pages: [0, 1], pageParams: [0, 1], }) - client.clear() - server.clear() + clearQueryClient(client) + clearQueryClient(server) }) }) diff --git a/packages/react-query-no-core-pluggable/src/__tests__/getMutationCache.test.ts b/packages/react-query-pluggable/src/__tests__/getMutationCache.test.ts similarity index 77% rename from packages/react-query-no-core-pluggable/src/__tests__/getMutationCache.test.ts rename to packages/react-query-pluggable/src/__tests__/getMutationCache.test.ts index 3286b5a33aa..386ebc48fbc 100644 --- a/packages/react-query-no-core-pluggable/src/__tests__/getMutationCache.test.ts +++ b/packages/react-query-pluggable/src/__tests__/getMutationCache.test.ts @@ -7,20 +7,27 @@ import { getMutationCache, hydrate, } from '..' -import { mutationCacheKey } from '../runtime/queryClient' +import { + clearQueryClient, + getQueryData, + isMutating, + mutationCacheKey, + resumePausedMutations, + setQueryData, +} from '../runtime/queryClient' describe('getMutationCache', () => { it('keeps query-only hydration, resume and clear free of mutation caches', async () => { const server = new QueryClient() const client = new QueryClient() - server.setQueryData(['books'], ['Dune']) + setQueryData(server, ['books'], ['Dune']) hydrate(client, dehydrate(server)) - expect(client.getQueryData(['books'])).toStrictEqual(['Dune']) - expect(client.isMutating()).toBe(0) - await expect(client.resumePausedMutations()).resolves.toStrictEqual([]) - client.clear() - expect(client.getQueryData(['books'])).toBeUndefined() + 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() }) @@ -40,7 +47,7 @@ describe('getMutationCache', () => { 'Dune', ]) expect(otherCache.getAll()).toStrictEqual([]) - first.clear() + clearQueryClient(first) expect(cache.getAll()).toStrictEqual([]) expect(getMutationCache(first)).toBe(cache) }) @@ -58,7 +65,7 @@ describe('getMutationCache', () => { expect(onSuccess).toHaveBeenCalledTimes(1) expect(getMutationCache(client)).toBe(cache) expect(cache.find({ mutationKey: ['save'] })?.state.data).toBe('saved') - client.clear() + clearQueryClient(client) expect(cache.getAll()).toStrictEqual([]) }) }) diff --git a/packages/react-query-no-core-pluggable/src/__tests__/projection.test-d.ts b/packages/react-query-pluggable/src/__tests__/projection.test-d.ts similarity index 100% rename from packages/react-query-no-core-pluggable/src/__tests__/projection.test-d.ts rename to packages/react-query-pluggable/src/__tests__/projection.test-d.ts diff --git a/packages/react-query-no-core-pluggable/src/__tests__/projection.test.ts b/packages/react-query-pluggable/src/__tests__/projection.test.ts similarity index 87% rename from packages/react-query-no-core-pluggable/src/__tests__/projection.test.ts rename to packages/react-query-pluggable/src/__tests__/projection.test.ts index 5c69a2149a5..f4f5f82d34d 100644 --- a/packages/react-query-no-core-pluggable/src/__tests__/projection.test.ts +++ b/packages/react-query-pluggable/src/__tests__/projection.test.ts @@ -1,5 +1,10 @@ import { describe, expect, it, vi } from 'vitest' import { QueryClient, QueryObserver, placeholderData, select } from '..' +import { + getQueryData, + setQueryData, + setQueryDefaults, +} from '../runtime/queryClient' describe('projection options', () => { it('reuses a stable selector and placeholder factory when option pairs are recreated', () => { @@ -22,7 +27,7 @@ describe('projection options', () => { observer.setOptions(options()) expect(placeholder).toHaveBeenCalledTimes(1) expect(count).toHaveBeenCalledTimes(1) - client.setQueryData(['count'], { count: 2 }) + setQueryData(client, ['count'], { count: 2 }) observer.setOptions(options()) expect(observer.getCurrentResult()).toMatchObject({ data: 2, @@ -36,7 +41,7 @@ describe('projection options', () => { if (typeof value !== 'number') throw new TypeError('Expected a number') return value * 2 } - client.setQueryDefaults(['entry'], { select: select(transform) }) + setQueryDefaults(client, ['entry'], { select: select(transform) }) const a = new QueryObserver(client, { queryKey: ['entry', 'a'], queryFn: () => 2, @@ -53,6 +58,6 @@ describe('projection options', () => { data: undefined, error: expect.any(TypeError), }) - expect(client.getQueryData(['entry', 'b'])).toBe('invalid') + expect(getQueryData(client, ['entry', 'b'])).toBe('invalid') }) }) diff --git a/packages/react-query-pluggable/src/__tests__/queryBuilders.test.ts b/packages/react-query-pluggable/src/__tests__/queryBuilders.test.ts new file mode 100644 index 00000000000..a05c4b96446 --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/queryBuilders.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from 'vitest' +import { query, queryOptions, skipToken, suspenseQuery } from '..' + +describe('query render modes', () => { + it('keeps ordinary query options by reference and scopes Suspense to the consumer', () => { + const options = queryOptions({ queryKey: ['post'], queryFn: () => 'Dune' }) + expect(query(options)).toBe(options) + expect(suspenseQuery(options).renderPolicy).toBeDefined() + expect( + suspenseQuery({ ...options, queryFn: skipToken }).renderPolicy, + ).toBeUndefined() + expect(options).not.toHaveProperty('renderPolicy') + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/queryModes.test-d.ts b/packages/react-query-pluggable/src/__tests__/queryModes.test-d.ts new file mode 100644 index 00000000000..fe4c6abab49 --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/queryModes.test-d.ts @@ -0,0 +1,63 @@ +import { describe, expectTypeOf, it } from 'vitest' +import { + infiniteQuery, + query, + select, + skipToken, + suspenseQuery, + useQuery, +} from '..' +import type { InfiniteData } from '..' + +describe('query render modes', () => { + it('infers data for each render mode from the same query', () => { + const options = { queryKey: ['post'], queryFn: () => ({ title: 'Dune' }) } + expectTypeOf(useQuery(query(options)).data).toEqualTypeOf< + { title: string } | undefined + >() + expectTypeOf(useQuery(suspenseQuery(options)).data).toEqualTypeOf<{ + title: string + }>() + const title = useQuery( + suspenseQuery({ ...options, select: [select, (post) => post.title] }), + ) + expectTypeOf(title.data).toEqualTypeOf() + const maybeFetch = Math.random() > 0.5 ? options.queryFn : skipToken + expectTypeOf( + useQuery(suspenseQuery({ ...options, queryFn: maybeFetch })).data, + ).toEqualTypeOf<{ title: string } | undefined>() + // @ts-expect-error Suspense manages whether the query runs. + suspenseQuery({ ...options, enabled: false }) + }) + + it('preserves page data, controls and selection in both infinite modes', () => { + const options = infiniteQuery({ + queryKey: ['pages'], + initialPageParam: 0, + queryFn: ({ pageParam }) => { + expectTypeOf(pageParam).toEqualTypeOf() + return String(pageParam) + }, + getNextPageParam: (_last, pages) => pages.length, + }) + const regular = useQuery(options) + expectTypeOf(regular.data).toEqualTypeOf< + InfiniteData | undefined + >() + expectTypeOf(regular.hasNextPage).toEqualTypeOf() + const suspended = useQuery(suspenseQuery(options)) + expectTypeOf(suspended.data).toEqualTypeOf>() + expectTypeOf(suspended.fetchNextPage).toEqualTypeOf< + typeof regular.fetchNextPage + >() + const selected = useQuery( + suspenseQuery( + infiniteQuery({ + ...options, + select: [select, (pages) => pages.pages.join(',')], + }), + ), + ) + expectTypeOf(selected.data).toEqualTypeOf() + }) +}) diff --git a/packages/react-query-pluggable/src/__tests__/queryModes.test.tsx b/packages/react-query-pluggable/src/__tests__/queryModes.test.tsx new file mode 100644 index 00000000000..1c4db68debc --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/queryModes.test.tsx @@ -0,0 +1,90 @@ +// @vitest-environment jsdom + +import { fireEvent, render, screen } from '@testing-library/react' +import * as React from 'react' +import { describe, expect, it, vi } from 'vitest' +import { + QueryClient, + QueryClientProvider, + infiniteQuery, + query, + suspenseQuery, + useQuery, +} from '..' +import { setQueryData } from '../runtime/queryClient' + +describe('query render modes', () => { + it('uses the same cached result when a reader starts suspending', () => { + const client = new QueryClient() + const queryFn = vi.fn<() => string>(() => 'fetched post') + const options = query({ queryKey: ['post'], queryFn, staleTime: Infinity }) + setQueryData(client, options.queryKey, 'cached post') + + function Post({ suspend }: { suspend: boolean }) { + const result = useQuery(suspend ? suspenseQuery(options) : options) + return

    {result.data}

    + } + + function App({ suspend }: { suspend: boolean }) { + return ( + + Loading post

    }> + +
    +
    + ) + } + + const view = render() + screen.getByText('cached post') + view.rerender() + screen.getByText('cached post') + expect(queryFn).not.toHaveBeenCalled() + view.unmount() + }) + + it('can switch the mounted hook to a paginated reader and back', async () => { + const client = new QueryClient() + const post = query({ queryKey: ['post'], queryFn: () => 'single post' }) + const pages = infiniteQuery({ + queryKey: ['pages'], + initialPageParam: 1, + queryFn: ({ pageParam }) => 'page ' + pageParam, + getNextPageParam: (_last, allPages) => allPages.length + 1, + }) + + function Reader({ paged }: { paged: boolean }) { + const result = useQuery(paged ? pages : post) + if ('fetchNextPage' in result) { + return ( + <> +

    {result.data?.pages.join(', ')}

    + + + ) + } + return

    {result.data}

    + } + + function App({ paged }: { paged: boolean }) { + return ( + + + + ) + } + + const view = render() + await screen.findByText('single post') + view.rerender() + await screen.findByText('page 1') + fireEvent.click(screen.getByRole('button', { name: 'Next page' })) + await screen.findByText('page 1, page 2') + view.rerender() + await screen.findByText('single post') + expect(screen.queryAllByRole('button')).toHaveLength(0) + view.unmount() + }) +}) diff --git a/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test-d.ts b/packages/react-query-pluggable/src/__tests__/refetchInterval.test-d.ts similarity index 100% rename from packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test-d.ts rename to packages/react-query-pluggable/src/__tests__/refetchInterval.test-d.ts diff --git a/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test.ts b/packages/react-query-pluggable/src/__tests__/refetchInterval.test.ts similarity index 98% rename from packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test.ts rename to packages/react-query-pluggable/src/__tests__/refetchInterval.test.ts index b9a89dc2a6c..7941a7e0480 100644 --- a/packages/react-query-no-core-pluggable/src/__tests__/refetchInterval.test.ts +++ b/packages/react-query-pluggable/src/__tests__/refetchInterval.test.ts @@ -4,8 +4,8 @@ import { QueryClient, QueryObserver, environmentManager, + fetchInfiniteQuery, focusManager, - infiniteQuery, refetchInterval, } from '..' @@ -140,7 +140,7 @@ describe('refetchInterval', () => { }) await expect(mutation.mutate()).resolves.toBe(42) await expect( - infiniteQuery(client, { + fetchInfiniteQuery(client, { queryKey: ['pages'], initialPageParam: 1, pages: 2, diff --git a/packages/react-query-no-core-pluggable/src/__tests__/serialScope.test.ts b/packages/react-query-pluggable/src/__tests__/serialScope.test.ts similarity index 88% rename from packages/react-query-no-core-pluggable/src/__tests__/serialScope.test.ts rename to packages/react-query-pluggable/src/__tests__/serialScope.test.ts index d01fc94e903..9eadfa5b8b3 100644 --- a/packages/react-query-no-core-pluggable/src/__tests__/serialScope.test.ts +++ b/packages/react-query-pluggable/src/__tests__/serialScope.test.ts @@ -7,6 +7,7 @@ import { onlineManager, serialScope, } from '..' +import { clearQueryClient, resumePausedMutations } from '../runtime/queryClient' describe('serialScope', () => { it('restores the queue from JSON and resumes its mutations in order', async () => { @@ -44,7 +45,7 @@ describe('serialScope', () => { hydrate(target, snapshot) onlineManager.setOnline(true) - const resumed = target.resumePausedMutations() + const resumed = resumePausedMutations(target) await started.promise expect(events).toStrictEqual(['start 1']) release.resolve() @@ -55,13 +56,13 @@ describe('serialScope', () => { 'start 2', 'finish 2', ]) - await source.resumePausedMutations() + await resumePausedMutations(source) await Promise.all([first, second]) } finally { release.resolve() onlineManager.setOnline(wasOnline) - source.clear() - target.clear() + clearQueryClient(source) + clearQueryClient(target) } }) }) diff --git a/packages/react-query-pluggable/src/__tests__/sharedCore.test.ts b/packages/react-query-pluggable/src/__tests__/sharedCore.test.ts new file mode 100644 index 00000000000..87f8b8fcd78 --- /dev/null +++ b/packages/react-query-pluggable/src/__tests__/sharedCore.test.ts @@ -0,0 +1,44 @@ +import { CancelledError, onlineManager } from '@tanstack/query-core' +import { describe, expect, it } from 'vitest' +import { QueryClient, cancelQueries } from '..' +import { + clearQueryClient, + fetchQuery, + getQueryState, + mountQueryClient, + unmountQueryClient, +} from '../runtime/queryClient' + +describe('shared query-core runtime', () => { + it('pauses when core goes offline and resumes when core reconnects', async () => { + const client = new QueryClient() + const wasOnline = onlineManager.isOnline() + mountQueryClient(client) + try { + onlineManager.setOnline(false) + const queryKey = ['connection'] + const pending = fetchQuery(client, { queryKey, queryFn: () => 'online' }) + expect(getQueryState(client, queryKey)?.fetchStatus).toBe('paused') + onlineManager.setOnline(true) + await expect(pending).resolves.toBe('online') + } finally { + unmountQueryClient(client) + onlineManager.setOnline(wasOnline) + clearQueryClient(client) + } + }) + + it('rejects cancelled queries with the core cancellation error', async () => { + const client = new QueryClient() + const queryKey = ['cancel'] + const pending = fetchQuery(client, { + queryKey, + queryFn: () => new Promise(() => {}), + }) + await Promise.all([ + expect(pending).rejects.toBeInstanceOf(CancelledError), + cancelQueries(client, { queryKey }), + ]) + clearQueryClient(client) + }) +}) diff --git a/packages/react-query-no-core-pluggable/src/errorBoundaryUtils.ts b/packages/react-query-pluggable/src/errorBoundaryUtils.ts similarity index 95% rename from packages/react-query-no-core-pluggable/src/errorBoundaryUtils.ts rename to packages/react-query-pluggable/src/errorBoundaryUtils.ts index 8ba639b93bc..8f5b4573fcc 100644 --- a/packages/react-query-no-core-pluggable/src/errorBoundaryUtils.ts +++ b/packages/react-query-pluggable/src/errorBoundaryUtils.ts @@ -1,10 +1,8 @@ 'use client' + +import { shouldThrowError } from '@tanstack/query-core/primitives' import * as React from 'react' -import { shouldThrowError } from './runtime/utils' -import type { - QueryKey, - QueryObserverResult, -} from '@tanstack/query-types/bindings' +import type { QueryKey, QueryObserverResult } from '@tanstack/query-core' import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' import type { Query } from './runtime/query' import type { diff --git a/packages/react-query-no-core-pluggable/src/index.ts b/packages/react-query-pluggable/src/index.ts similarity index 85% rename from packages/react-query-no-core-pluggable/src/index.ts rename to packages/react-query-pluggable/src/index.ts index af4348b29f1..d8addd25e16 100644 --- a/packages/react-query-no-core-pluggable/src/index.ts +++ b/packages/react-query-pluggable/src/index.ts @@ -1,9 +1,31 @@ /* istanbul ignore file */ // Public cache and observer API -export { focusManager } from './runtime/focusManager' -export type { FocusManager } from './runtime/focusManager' -export { environmentManager } from './runtime/environmentManager' +export { + focusManager, + environmentManager, + onlineManager, + CancelledError, + timeoutManager, + hashKey, + noop, + partialMatchKey, + replaceEqualDeep, + shouldThrowError, + defaultQueryFn, + skipToken, +} from '@tanstack/query-core/primitives' +export type { + FocusManager, + OnlineManager, + TimeoutManager, + ManagedTimerId, + TimeoutCallback, + TimeoutProvider, + DefaultQueryFn, + SkipToken, + Updater, +} from '@tanstack/query-core/primitives' export { defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, @@ -11,7 +33,9 @@ export { dehydrateQuery, hydrate, } from './runtime/hydration' -export { infiniteQuery } from './runtime/infiniteQuery' +export { infiniteQuery } from './infiniteQuery' +export type { InfiniteQueryMode } from './infiniteQuery' +export { fetchInfiniteQuery } from './runtime/fetchInfiniteQuery' export { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' export { MutationCache, getMutationCache } from './runtime/mutationCache' export type { @@ -20,15 +44,34 @@ export type { } from './runtime/mutationCache' export { MutationObserver } from './runtime/mutationObserver' export { defaultScheduler, notifyManager } from './runtime/notifyManager' -export { onlineManager } from './runtime/onlineManager' -export type { OnlineManager } from './runtime/onlineManager' export { QueriesObserver } from './runtime/queriesObserver' export { QueryCache } from './runtime/queryCache' export type { QueryCacheNotifyEvent, QueryCacheConfig, } from './runtime/queryCache' -export { QueryClient } from './runtime/queryClient' +export { + QueryClient, + mountQueryClient, + unmountQueryClient, + isFetching, + isMutating, + getQueryData, + setQueryData, + getQueryState, + fetchQuery, + resumePausedMutations, + getQueryCache, + getDefaultOptions, + setDefaultOptions, + setQueryDefaults, + getQueryDefaults, + setMutationDefaults, + getMutationDefaults, + defaultQueryOptions, + defaultMutationOptions, + clearQueryClient, +} from './runtime/queryClient' export { getQueriesData, setQueriesData, @@ -38,7 +81,7 @@ export { invalidateQueries, refetchQueries, } from './runtime/cacheOperations' -export type { QueryRuntime } from './runtime/runtimeBinding' + export { serialScope } from './runtime/serialScope' export type { SerialScope } from './runtime/serialScope' export { select } from './runtime/select' @@ -47,97 +90,8 @@ export type { Select, PlaceholderData } from './runtime/projectionTypes' export { refetchInterval } from './runtime/refetchInterval' export type { RefetchInterval } from './runtime/refetchInterval' export { QueryObserver } from './runtime/queryObserver' -export type { - QueryObserverResultReader, - ManagedTimerId, - TimeoutCallback, - TimeoutProvider, - DefaultQueryFn, - SkipToken, - Updater, - DehydratedState, - MutationState, - QueriesObserverOptions, - QueriesObserverResultReader, - QueryState, - NonUndefinedGuard, - DistributiveOmit, - OmitKeyof, - Override, - Register, - DefaultError, - QueryKey, - 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, - QueryObserverResult, - InfiniteQueryObserverBaseResult, - InfiniteQueryObserverPendingResult, - InfiniteQueryObserverLoadingResult, - InfiniteQueryObserverLoadingErrorResult, - InfiniteQueryObserverRefetchErrorResult, - InfiniteQueryObserverSuccessResult, - InfiniteQueryObserverPlaceholderResult, - DefinedInfiniteQueryObserverResult, - InfiniteQueryObserverResult, - MutationKey, - MutationStatus, - MutationScope, - MutationMeta, - CancelOptions, - SetDataOptions, - NotifyEventType, - NotifyEvent, -} from '@tanstack/query-types/bindings' -export { CancelledError } from './runtime/retryer' -export { timeoutManager } from './runtime/timeoutManager' -export type { TimeoutManager } from './runtime/timeoutManager' -export { - hashKey, - keepPreviousData, - matchMutation, - matchQuery, - noop, - partialMatchKey, - replaceEqualDeep, - shouldThrowError, - defaultQueryFn, - skipToken, -} from './runtime/utils' + +export { keepPreviousData, matchMutation, matchQuery } from './runtime/utils' export type { MutationFilters, QueryFilters } from './runtime/utils' export { streamedQuery } from './runtime/streamedQuery' export type { DehydrateOptions, HydrateOptions } from './runtime/hydration' @@ -210,6 +164,8 @@ export { useQueries } from './useQueries' export type { QueriesResults, QueriesOptions } from './useQueries' export { useQuery } from './useQuery' export { useSuspenseQuery } from './useSuspenseQuery' +export { suspenseQuery } from './suspenseQuery' +export type { SuspenseQueryMode, SuspenseQueryOptions } from './suspenseQuery' export { useSuspenseInfiniteQuery } from './useSuspenseInfiniteQuery' export { useSuspenseQueries } from './useSuspenseQueries' export type { @@ -218,7 +174,7 @@ export type { } from './useSuspenseQueries' export { usePrefetchQuery } from './usePrefetchQuery' export { usePrefetchInfiniteQuery } from './usePrefetchInfiniteQuery' -export { queryOptions } from './queryOptions' +export { queryOptions, queryOptions as query } from './queryOptions' export type { DefinedInitialDataOptions, UndefinedInitialDataOptions, @@ -255,3 +211,74 @@ export { useMutation } from './useMutation' export { mutationOptions } from './mutationOptions' export { useInfiniteQuery } from './useInfiniteQuery' export { useIsRestoring, IsRestoringProvider } from './IsRestoringProvider' + +export type { + QueryObserverResultReader, + DehydratedState, + MutationState, + QueriesObserverOptions, + QueriesObserverResultReader, + QueryState, + NonUndefinedGuard, + DistributiveOmit, + OmitKeyof, + Override, + Register, + DefaultError, + QueryKey, + 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, + QueryObserverResult, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverPendingResult, + InfiniteQueryObserverLoadingResult, + InfiniteQueryObserverLoadingErrorResult, + InfiniteQueryObserverRefetchErrorResult, + InfiniteQueryObserverSuccessResult, + InfiniteQueryObserverPlaceholderResult, + DefinedInfiniteQueryObserverResult, + InfiniteQueryObserverResult, + MutationKey, + MutationStatus, + MutationScope, + MutationMeta, + CancelOptions, + SetDataOptions, + NotifyEventType, + NotifyEvent, +} from '@tanstack/query-core' diff --git a/packages/react-query-pluggable/src/infiniteQuery.ts b/packages/react-query-pluggable/src/infiniteQuery.ts new file mode 100644 index 00000000000..bef674411f0 --- /dev/null +++ b/packages/react-query-pluggable/src/infiniteQuery.ts @@ -0,0 +1,85 @@ +import { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' +import type { DefaultError, InfiniteData, QueryKey } from '@tanstack/query-core' +import type { + DefinedInitialDataInfiniteOptions, + UnusedSkipTokenInfiniteOptions, +} from './infiniteQueryOptions' +import type { + AnyUseInfiniteQueryOptions, + UseInfiniteQueryOptions, +} from './types' + +/** Identifies options that read pages through an infinite query observer. */ +export interface InfiniteQueryMode { + /** The observer that adds pagination controls to the result. */ + readonly Observer: typeof InfiniteQueryObserver +} + +/** + * Configures a paginated query to read through `useQuery`. + * @param options - The page fetcher, initial page parameter and pagination callbacks. + * @returns The options with their matching observer. + */ +export function infiniteQuery< + TQueryFnData, + TPageParam = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, +>( + options: DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): DefinedInitialDataInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & + InfiniteQueryMode +export function infiniteQuery< + TQueryFnData, + TPageParam = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): UnusedSkipTokenInfiniteOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & + InfiniteQueryMode +export function infiniteQuery< + TQueryFnData, + TPageParam = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UseInfiniteQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, +): UseInfiniteQueryOptions & + InfiniteQueryMode +export function infiniteQuery(options: AnyUseInfiniteQueryOptions) { + return { ...options, Observer: InfiniteQueryObserver } +} diff --git a/packages/react-query-no-core/src/infiniteQueryOptions.ts b/packages/react-query-pluggable/src/infiniteQueryOptions.ts similarity index 96% rename from packages/react-query-no-core/src/infiniteQueryOptions.ts rename to packages/react-query-pluggable/src/infiniteQueryOptions.ts index 9ecbe9cb090..3216da8a03a 100644 --- a/packages/react-query-no-core/src/infiniteQueryOptions.ts +++ b/packages/react-query-pluggable/src/infiniteQueryOptions.ts @@ -7,8 +7,8 @@ import type { OmitKeyof, QueryKey, QueryKeyWithDataTag, - SkipToken, -} from '@tanstack/query-types/bindings' +} from '@tanstack/query-core' +import type { SkipToken } from '@tanstack/query-core/primitives' import type { UseInfiniteQueryOptions } from './types' /** @@ -61,16 +61,17 @@ export type UndefinedInitialDataInfiniteOptions< * @template TQueryKey - The type of your `queryKey`. * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page. */ -export type UnusedSkipTokenInfiniteOptions< +export interface UnusedSkipTokenInfiniteOptions< TQueryFnData, TError = DefaultError, TData = InfiniteData, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown, -> = OmitKeyof< +> extends OmitKeyof< UseInfiniteQueryOptions, 'queryFn' -> & { +> { + /** The query function or the configured client default. */ queryFn: Exclude< UseInfiniteQueryOptions< TQueryFnData, @@ -121,7 +122,7 @@ export type DefinedInitialDataInfiniteOptions< type InfiniteQueryOptionsFn = { /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `fetchInfiniteQuery(client, options)`. * `options.queryKey` is required and is the query key to generate options for. * * This overload is selected when `initialData` is known to be defined. @@ -132,7 +133,7 @@ type InfiniteQueryOptionsFn = { * @see {@link useInfiniteQuery} to run an infinite query with these options. * @example * ```tsx - * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core' + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-pluggable' * * export const projectsOptions = infiniteQueryOptions({ * queryKey: ['projects'], @@ -183,7 +184,7 @@ type InfiniteQueryOptionsFn = { /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `fetchInfiniteQuery(client, options)`. * `options.queryKey` is required and is the query key to generate options for. * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. * @returns The same options object, typed so that `queryKey` carries the inferred data type. @@ -193,7 +194,7 @@ type InfiniteQueryOptionsFn = { * @example * A parameterized factory, so the same options object can be reused per `postId`: * ```tsx - * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core' + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-pluggable' * * export const commentsOptions = (postId: string) => * infiniteQueryOptions({ @@ -242,7 +243,7 @@ type InfiniteQueryOptionsFn = { /** * You can generally pass everything to `infiniteQueryOptions` that you can also pass to `useInfiniteQuery`. - * These options can be shared across hooks and imperative APIs such as `queryClient.infiniteQuery`. + * These options can be shared across hooks and imperative APIs such as `fetchInfiniteQuery(client, options)`. * `options.queryKey` is required and is the query key to generate options for. * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to `useInfiniteQuery`. * @returns The same options object, typed so that `queryKey` carries the inferred data type. @@ -252,7 +253,7 @@ type InfiniteQueryOptionsFn = { * @example * A parameterized factory, so the same options object can be reused per `postId`: * ```tsx - * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-no-core' + * import { infiniteQueryOptions, useInfiniteQuery } from '@tanstack/react-query-pluggable' * * export const commentsOptions = (postId: string) => * infiniteQueryOptions({ diff --git a/packages/react-query-no-core/src/mutationOptions.ts b/packages/react-query-pluggable/src/mutationOptions.ts similarity index 98% rename from packages/react-query-no-core/src/mutationOptions.ts rename to packages/react-query-pluggable/src/mutationOptions.ts index a126abd7e93..91e9ab212fd 100644 --- a/packages/react-query-no-core/src/mutationOptions.ts +++ b/packages/react-query-pluggable/src/mutationOptions.ts @@ -1,5 +1,5 @@ import { identity } from './runtime/identity' -import type { DefaultError, WithRequired } from '@tanstack/query-types/bindings' +import type { DefaultError, WithRequired } from '@tanstack/query-core' import type { UseMutationOptions } from './types' type MutationOptionsFn = { @@ -14,7 +14,7 @@ type MutationOptionsFn = { * @example * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator: * ```tsx - * import { mutationOptions, useMutationState } from '@tanstack/react-query-no-core' + * import { mutationOptions, useMutationState } from '@tanstack/react-query-pluggable' * * const createPostOptions = mutationOptions({ * mutationKey: ['posts', 'create'], @@ -57,7 +57,7 @@ type MutationOptionsFn = { * @see {@link useMutation} to run the mutation these options describe. * @example * ```tsx - * import { mutationOptions, useMutation } from '@tanstack/react-query-no-core' + * import { mutationOptions, useMutation } from '@tanstack/react-query-pluggable' * * export const createPostOptions = mutationOptions({ * mutationFn: createPost, diff --git a/packages/react-query-no-core/src/queryOptions.ts b/packages/react-query-pluggable/src/queryOptions.ts similarity index 93% rename from packages/react-query-no-core/src/queryOptions.ts rename to packages/react-query-pluggable/src/queryOptions.ts index 2290631e0dc..616e93e043c 100644 --- a/packages/react-query-no-core/src/queryOptions.ts +++ b/packages/react-query-pluggable/src/queryOptions.ts @@ -1,14 +1,13 @@ import { identity } from './runtime/identity' import type { DefaultError, - DefaultQueryFn, InitialDataFunction, NonUndefinedGuard, OmitKeyof, QueryKey, QueryKeyWithDataTag, - SkipToken, -} from '@tanstack/query-types/bindings' +} from '@tanstack/query-core' +import type { DefaultQueryFn, SkipToken } from '@tanstack/query-core/primitives' import type { QueryFunction } from './runtime/types' import type { UseQueryOptions } from './types' @@ -49,15 +48,16 @@ export type UndefinedInitialDataOptions< * @template TData - The type `data` ends up as after `select` runs. * @template TQueryKey - The type of your `queryKey`. */ -export type UnusedSkipTokenOptions< +export interface UnusedSkipTokenOptions< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> = OmitKeyof< +> extends OmitKeyof< UseQueryOptions, 'queryFn' -> & { +> { + /** The query function or the configured client default. */ queryFn: Exclude< UseQueryOptions['queryFn'], SkipToken @@ -94,7 +94,7 @@ export type DefinedInitialDataOptions< type QueryOptionsFn = { /** * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can - * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * be shared across hooks and imperative APIs such as `fetchQuery`. `options.queryKey` is required and * is the query key to generate options for. * * This overload is selected when `initialData` is known to be defined, so the resulting `data` is never @@ -105,7 +105,7 @@ type QueryOptionsFn = { * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern. * @example * ```tsx - * import { queryOptions, useQuery } from '@tanstack/react-query-no-core' + * import { queryOptions, useQuery } from '@tanstack/react-query-pluggable' * * export const postsOptions = queryOptions({ * queryKey: ['posts'], @@ -141,7 +141,7 @@ type QueryOptionsFn = { /** * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can - * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * be shared across hooks and imperative APIs such as `fetchQuery`. `options.queryKey` is required and * is the query key to generate options for. * @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `useQuery`. * @returns The same options object, typed so that `queryKey` carries the inferred data type. @@ -150,7 +150,7 @@ type QueryOptionsFn = { * @example * A parameterized factory, so the same options object can be reused per `id`: * ```tsx - * import { queryOptions, useQuery } from '@tanstack/react-query-no-core' + * import { queryOptions, useQuery } from '@tanstack/react-query-pluggable' * * export const postOptions = (id: string) => * queryOptions({ @@ -180,7 +180,7 @@ type QueryOptionsFn = { /** * You can generally pass everything to `queryOptions` that you can also pass to `useQuery`. These options can - * be shared across hooks and imperative APIs such as `queryClient.query`. `options.queryKey` is required and + * be shared across hooks and imperative APIs such as `fetchQuery`. `options.queryKey` is required and * is the query key to generate options for. * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `useQuery`. * @returns The same options object, typed so that `queryKey` carries the inferred data type. @@ -190,7 +190,7 @@ type QueryOptionsFn = { * @example * A parameterized factory, so the same options object can be reused per `id`: * ```tsx - * import { queryOptions, useQuery } from '@tanstack/react-query-no-core' + * import { queryOptions, useQuery } from '@tanstack/react-query-pluggable' * * export const postOptions = (id: string) => * queryOptions({ @@ -210,7 +210,7 @@ type QueryOptionsFn = { * @example * A factory that disables the query, type safe, until `postId` is set: * ```tsx - * import { queryOptions, skipToken, useQuery } from '@tanstack/react-query-no-core' + * import { queryOptions, skipToken, useQuery } from '@tanstack/react-query-pluggable' * * export const postOptions = (postId: number | undefined) => * queryOptions({ diff --git a/packages/react-query-no-core-pluggable/src/runtime/cacheOperations.ts b/packages/react-query-pluggable/src/runtime/cacheOperations.ts similarity index 92% rename from packages/react-query-no-core-pluggable/src/runtime/cacheOperations.ts rename to packages/react-query-pluggable/src/runtime/cacheOperations.ts index 5f315440d0d..d5eeb9b972a 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/cacheOperations.ts +++ b/packages/react-query-pluggable/src/runtime/cacheOperations.ts @@ -1,5 +1,7 @@ +import { noop } from '@tanstack/query-core/primitives' import { notifyManager } from './notifyManager' -import { noop } from './utils' +import { getQueryCache, setQueryData } from './queryClient' +import type { Updater } from '@tanstack/query-core/primitives' import type { QueryClient } from './queryClient' import type { CancelOptions, @@ -11,7 +13,7 @@ import type { ResetOptions, SetDataOptions, } from './types' -import type { QueryFilters, Updater } from './utils' +import type { QueryFilters } from './utils' /** * Imperative (non-reactive) way to retrieve the cached data of multiple queries at once. @@ -26,7 +28,7 @@ import type { QueryFilters, Updater } from './utils' * @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 QueryClient#getQueryData} + * @see {@link getQueryData} * @example * ```ts * const data = getQueriesData(queryClient, { queryKey: ['posts'] }) @@ -39,8 +41,7 @@ export function getQueriesData< client: QueryClient, filters: TQueryFilters, ): Array<[QueryKey, TQueryFnData | undefined]> { - return client - .getQueryCache() + return getQueryCache(client) .findAll(filters) .map(({ queryKey, state }) => { const data = state.data as TQueryFnData | undefined @@ -52,19 +53,18 @@ export function getQueriesData< * 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 QueryClient#setQueryData} for each matching query. + * {@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 QueryClient#setQueryData}. + * `undefined` case as {@link setQueryData}. * @example * ```ts * setQueriesData(queryClient, { queryKey: ['posts'] }, (oldPosts) => - * oldPosts ? oldPosts.filter((post) => post.id !== deletedId) : oldPosts, - * ) + * oldPosts ? oldPosts.filter((post) => post.id !== deletedId) : oldPosts) * ``` */ export function setQueriesData< @@ -80,12 +80,11 @@ export function setQueriesData< options?: SetDataOptions, ): Array<[QueryKey, TQueryFnData | undefined]> { return notifyManager.batch(() => - client - .getQueryCache() + getQueryCache(client) .findAll(filters) .map(({ queryKey }) => [ queryKey, - client.setQueryData(queryKey, updater, options), + setQueryData(client, queryKey, updater, options), ]), ) } @@ -107,7 +106,7 @@ export function removeQueries( client: QueryClient, filters?: QueryFilters, ): void { - const queryCache = client.getQueryCache() + const queryCache = getQueryCache(client) notifyManager.batch(() => { queryCache.findAll(filters).forEach((query) => { queryCache.remove(query) @@ -135,7 +134,7 @@ export function resetQueries( filters?: QueryFilters, options?: ResetOptions, ): Promise { - const queryCache = client.getQueryCache() + const queryCache = getQueryCache(client) return notifyManager.batch(() => { const matched = queryCache.findAll(filters) @@ -180,8 +179,7 @@ export function cancelQueries( const defaultedCancelOptions = { revert: true, ...cancelOptions } const promises = notifyManager.batch(() => - client - .getQueryCache() + getQueryCache(client) .findAll(filters) .map((query) => query.cancel(defaultedCancelOptions)), ) @@ -211,11 +209,10 @@ export function cancelQueries( export function invalidateQueries( client: QueryClient, filters?: InvalidateQueryFilters, - options: InvalidateOptions = {}, + options?: InvalidateOptions, ): Promise { return notifyManager.batch(() => { - client - .getQueryCache() + getQueryCache(client) .findAll(filters) .forEach((query) => { query.invalidate() @@ -262,15 +259,14 @@ export function invalidateQueries( export function refetchQueries( client: QueryClient, filters?: RefetchQueryFilters, - options: RefetchOptions = {}, + options?: RefetchOptions, ): Promise { const fetchOptions = { ...options, - cancelRefetch: options.cancelRefetch ?? true, + cancelRefetch: options?.cancelRefetch ?? true, } const promises = notifyManager.batch(() => - client - .getQueryCache() + getQueryCache(client) .findAll(filters) .filter((query) => !query.isDisabled() && !query.isStatic()) .map((query) => { diff --git a/packages/react-query-no-core-pluggable/src/runtime/infiniteQuery.ts b/packages/react-query-pluggable/src/runtime/fetchInfiniteQuery.ts similarity index 87% rename from packages/react-query-no-core-pluggable/src/runtime/infiniteQuery.ts rename to packages/react-query-pluggable/src/runtime/fetchInfiniteQuery.ts index 60fcdf25d0b..4d9b666a424 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/infiniteQuery.ts +++ b/packages/react-query-pluggable/src/runtime/fetchInfiniteQuery.ts @@ -1,6 +1,6 @@ import { infiniteFetchOptions } from './infiniteQueryBehavior' -import type { WithoutSkipToken } from '@tanstack/query-types/bindings' -import type { QueryClient } from './queryClient' +import { fetchQuery } from './queryClient' +import type { QueryClient, WithoutSkipToken } from './queryClient' import type { DefaultError, InfiniteData, @@ -16,7 +16,7 @@ import type { * 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 QueryClient#getQueryData} + * 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. @@ -25,7 +25,7 @@ import type { * @example * ```ts * try { - * const data = await infiniteQuery(queryClient, { + * const data = await fetchInfiniteQuery(queryClient, { * queryKey, * queryFn, * initialPageParam: 0, @@ -37,7 +37,7 @@ import type { * } * ``` */ -export function infiniteQuery< +export function fetchInfiniteQuery< TQueryFnData, TError = DefaultError, TData = InfiniteData, @@ -59,7 +59,7 @@ export function infiniteQuery< ? InfiniteData : TData > -export function infiniteQuery< +export function fetchInfiniteQuery< TQueryFnData, TError = DefaultError, TData = InfiniteData, @@ -80,7 +80,7 @@ export function infiniteQuery< ? InfiniteData : TData) > -export function infiniteQuery< +export function fetchInfiniteQuery< TQueryFnData, TError = DefaultError, TData = InfiniteData, @@ -101,5 +101,5 @@ export function infiniteQuery< ? InfiniteData : TData) > { - return client.query(infiniteFetchOptions(options) as any) + return fetchQuery(client, infiniteFetchOptions(options) as any) } diff --git a/packages/react-query-no-core-pluggable/src/runtime/hydration.ts b/packages/react-query-pluggable/src/runtime/hydration.ts similarity index 82% rename from packages/react-query-no-core-pluggable/src/runtime/hydration.ts rename to packages/react-query-pluggable/src/runtime/hydration.ts index d3905a7bb1b..27af3fd9f62 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/hydration.ts +++ b/packages/react-query-pluggable/src/runtime/hydration.ts @@ -1,18 +1,53 @@ +import { noop } from '@tanstack/query-core/primitives' import { prepareInfiniteFetch } from './infiniteQueryBehavior' import { Mutation } from './mutation' -import { mutationCacheKey } from './queryClient' +import { + getDefaultOptions, + getQueryCache, + mutationCacheKey, +} from './queryClient' import { serialScope } from './serialScope' -import { noop } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - DehydratedMutation, - DehydratedQuery, - DehydratedState, - TransformerFn, -} from '@tanstack/query-types/bindings' +import type { DefaultError, DehydratedState } from '@tanstack/query-core' +import type * as Core from '@tanstack/query-core' import type { Query } from './query' import type { QueryClient } from './queryClient' -import type { QueryRuntime } from './runtimeBinding' +import type { MutationOptions, QueryOptions } from './types' + +type DehydratedMutation = DehydratedState['mutations'][number] + +type DehydratedQuery = DehydratedState['queries'][number] + +type TransformerFn = NonNullable + +/** + * 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 extends Omit< + Core.DehydrateOptions, + 'shouldDehydrateMutation' | 'shouldDehydrateQuery' +> { + /** 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 +} + +/** + * 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 @@ -27,10 +62,9 @@ function tryResolveSync(promise: PromiseLike) { const thenResult = promise.then((result) => { data = result return result - }, noop) as Promise | undefined + }, noop) as Partial> | undefined - // .catch can be unavailable on certain kinds of thenable's - // oxlint-disable-next-line typescript/no-unnecessary-condition + // A synchronous thenable may return an object without a catch method. thenResult?.catch?.(noop) if (data !== undefined) { @@ -40,12 +74,6 @@ function tryResolveSync(promise: PromiseLike) { return undefined } -/** {@inheritDoc Shared.DehydrateOptions} */ -export type DehydrateOptions = Shared.DehydrateOptions - -/** {@inheritDoc Shared.HydrateOptions} */ -export type HydrateOptions = Shared.HydrateOptions - // FUNCTIONS /** @@ -170,7 +198,7 @@ export function defaultShouldDehydrateQuery(query: Query) { * ```ts * const queryClient = new QueryClient() * - * await queryClient.query({ + * await fetchQuery(queryClient, { * queryKey: ['posts'], * queryFn: getPosts, * }) @@ -184,7 +212,7 @@ export function dehydrate( ): DehydratedState { const filterMutation = options.shouldDehydrateMutation ?? - client.getDefaultOptions().dehydrate?.shouldDehydrateMutation ?? + getDefaultOptions(client).dehydrate?.shouldDehydrateMutation ?? defaultShouldDehydrateMutation const mutations = @@ -196,18 +224,17 @@ export function dehydrate( const filterQuery = options.shouldDehydrateQuery ?? - client.getDefaultOptions().dehydrate?.shouldDehydrateQuery ?? + getDefaultOptions(client).dehydrate?.shouldDehydrateQuery ?? defaultShouldDehydrateQuery const shouldRedactErrors = options.shouldRedactErrors ?? - client.getDefaultOptions().dehydrate?.shouldRedactErrors + getDefaultOptions(client).dehydrate?.shouldRedactErrors const serializeData = - options.serializeData ?? client.getDefaultOptions().dehydrate?.serializeData + options.serializeData ?? getDefaultOptions(client).dehydrate?.serializeData - const queries = client - .getQueryCache() + const queries = getQueryCache(client) .getAll() .flatMap((query) => filterQuery(query) @@ -248,7 +275,7 @@ export function hydrate( Mutation.build( client, { - ...client.getDefaultOptions().hydrate?.mutations, + ...getDefaultOptions(client).hydrate?.mutations, ...options?.defaultOptions?.mutations, ...mutationOptions, ...(scope && { scope: serialScope(scope.id) }), @@ -273,10 +300,10 @@ export function hydrateQueries( queries: Array, options?: HydrateOptions, ): void { - const queryCache = client.getQueryCache() + const queryCache = getQueryCache(client) const deserializeData = options?.defaultOptions?.deserializeData ?? - client.getDefaultOptions().hydrate?.deserializeData + getDefaultOptions(client).hydrate?.deserializeData queries.forEach( ({ @@ -335,7 +362,7 @@ export function hydrateQueries( query = queryCache.build( client, { - ...client.getDefaultOptions().hydrate?.queries, + ...getDefaultOptions(client).hydrate?.queries, ...options?.defaultOptions?.queries, queryKey, queryHash, @@ -390,4 +417,4 @@ export function hydrateQueries( ) } -export type { DehydratedState } from '@tanstack/query-types/bindings' +export type { DehydratedState } from '@tanstack/query-core' diff --git a/packages/react-query-no-core-pluggable/src/runtime/identity.ts b/packages/react-query-pluggable/src/runtime/identity.ts similarity index 100% rename from packages/react-query-no-core-pluggable/src/runtime/identity.ts rename to packages/react-query-pluggable/src/runtime/identity.ts diff --git a/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryBehavior.ts b/packages/react-query-pluggable/src/runtime/infiniteQueryBehavior.ts similarity index 97% rename from packages/react-query-no-core-pluggable/src/runtime/infiniteQueryBehavior.ts rename to packages/react-query-pluggable/src/runtime/infiniteQueryBehavior.ts index 87e4df7626a..8a5d9a127ca 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryBehavior.ts +++ b/packages/react-query-pluggable/src/runtime/infiniteQueryBehavior.ts @@ -1,12 +1,12 @@ import { addConsumeAwareSignal, addToArray, - ensureQueryFn, fetchSignal, -} from './utils' +} from '@tanstack/query-core/primitives' +import { ensureQueryFn } from './utils' +import type { FetchSignalContext } from '@tanstack/query-core/primitives' import type { FetchContext, Query } from './query' import type { InfiniteData, InfiniteQueryPageParamsOptions } from './types' -import type { FetchSignalContext } from './utils' /** * Installs the page fetcher for an infinite query. A retry continues from the diff --git a/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryObserver.ts b/packages/react-query-pluggable/src/runtime/infiniteQueryObserver.ts similarity index 92% rename from packages/react-query-no-core-pluggable/src/runtime/infiniteQueryObserver.ts rename to packages/react-query-pluggable/src/runtime/infiniteQueryObserver.ts index 7b51284dfe9..04555d44a81 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/infiniteQueryObserver.ts +++ b/packages/react-query-pluggable/src/runtime/infiniteQueryObserver.ts @@ -4,19 +4,13 @@ import { infiniteFetchOptions, } from './infiniteQueryBehavior' import { QueryObserver } from './queryObserver' -import type * as Shared from '@tanstack/query-types/bindings' -import type { - InfiniteQueryObserverListener, - ReplaceReturnType, -} from '@tanstack/query-types/bindings' +import type { Subscribable } from '@tanstack/query-core/primitives' import type { Query } from './query' import type { QueryClient } from './queryClient' import type { QueryObserverResultContext, QueryObserverResultReader, } from './queryObserver' -import type { QueryRuntime } from './runtimeBinding' -import type { Subscribable } from './subscribable' import type { DefaultError, DefaultedInfiniteQueryObserverOptions, @@ -24,25 +18,42 @@ import type { 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, -> = Shared.InfiniteObserverOptionsInput< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam -> +> = + | InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > + | DefaultedInfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + > /** * An `InfiniteQueryObserver` extends `QueryObserver` to observe and switch diff --git a/packages/react-query-no-core-pluggable/src/runtime/mutation.ts b/packages/react-query-pluggable/src/runtime/mutation.ts similarity index 95% rename from packages/react-query-no-core-pluggable/src/runtime/mutation.ts rename to packages/react-query-pluggable/src/runtime/mutation.ts index 5257b436f22..92fe8a700eb 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/mutation.ts +++ b/packages/react-query-pluggable/src/runtime/mutation.ts @@ -1,17 +1,15 @@ +import { Removable, createRetryer } from '@tanstack/query-core/primitives' import { getMutationCache } from './mutationCache' import { notifyManager } from './notifyManager' -import { Removable } from './removable' -import { createRetryer } from './retryer' -import type * as Shared from '@tanstack/query-types/bindings' +import { defaultMutationOptions } from './queryClient' +import type { MutationState } from '@tanstack/query-core' import type { MutationAction as Action, - MutationState, -} from '@tanstack/query-types/bindings' + Retryer, +} from '@tanstack/query-core/primitives' import type { MutationCache } from './mutationCache' import type { MutationObserver } from './mutationObserver' import type { QueryClient } from './queryClient' -import type { Retryer } from './retryer' -import type { QueryRuntime } from './runtimeBinding' import type { DefaultError, MutationFunctionContext, @@ -19,14 +17,13 @@ import type { MutationOptions, } from './types' -type MutationConfig = - Shared.MutationConfig< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult - > +interface MutationConfig { + client: QueryClient + mutationId: number + mutationCache: MutationCache + options: MutationOptions + state?: MutationState +} // CLASS @@ -82,7 +79,7 @@ export class Mutation< client, mutationCache: cache, mutationId, - options: client.defaultMutationOptions(options), + options: defaultMutationOptions(client, options), state, }), ) @@ -500,7 +497,5 @@ export function getDefaultState< } } -export type { - MutationState, - MutationAction as Action, -} from '@tanstack/query-types/bindings' +export type { MutationState } from '@tanstack/query-core' +export type { MutationAction as Action } from '@tanstack/query-core/primitives' diff --git a/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts b/packages/react-query-pluggable/src/runtime/mutationCache.ts similarity index 66% rename from packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts rename to packages/react-query-pluggable/src/runtime/mutationCache.ts index d85c33af47e..110acf28dc1 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/mutationCache.ts +++ b/packages/react-query-pluggable/src/runtime/mutationCache.ts @@ -1,22 +1,115 @@ +import { Subscribable, noop } from '@tanstack/query-core/primitives' import { notifyManager } from './notifyManager' import { mutationCacheKey } from './queryClient' -import { Subscribable } from './subscribable' -import { matchMutation, noop } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' +import { matchMutation } from './utils' +import type { + CacheKeyConfig, + MutationKey, + NotifyEvent, +} from '@tanstack/query-core' +import type { MutationAction } from '@tanstack/query-core/primitives' import type { Mutation } from './mutation' +import type { MutationObserver } from './mutationObserver' import type { QueryClient } from './queryClient' -import type { QueryRuntime } from './runtimeBinding' -import type { DefaultError } from './types' +import type { DefaultError, MutationFunctionContext } from './types' import type { MutationFilters } from './utils' -/** {@inheritDoc Shared.MutationCacheConfig} */ -export type MutationCacheConfig = Shared.MutationCacheConfig +/** + * 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 +} -/** {@inheritDoc Shared.MutationCacheNotifyEvent} */ +/** + * 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 = - Shared.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 +} -type MutationCacheListener = Shared.MutationCacheListener +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 @@ -25,7 +118,7 @@ type MutationCacheListener = Shared.MutationCacheListener * @returns The same mutation cache on every call for this client. * @example * ```ts - * import { getMutationCache } from '@tanstack/react-query-no-core-pluggable' + * import { getMutationCache } from '@tanstack/react-query-pluggable' * * const pending = getMutationCache(queryClient).findAll({ status: 'pending' }) * ``` diff --git a/packages/react-query-no-core-pluggable/src/runtime/mutationObserver.ts b/packages/react-query-pluggable/src/runtime/mutationObserver.ts similarity index 95% rename from packages/react-query-no-core-pluggable/src/runtime/mutationObserver.ts rename to packages/react-query-pluggable/src/runtime/mutationObserver.ts index f140cc0839d..5e4b880940d 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/mutationObserver.ts +++ b/packages/react-query-pluggable/src/runtime/mutationObserver.ts @@ -1,12 +1,14 @@ +import { + Subscribable, + hashKeyByOptions, + shallowEqualObjects, +} from '@tanstack/query-core/primitives' import { Mutation, getDefaultState } from './mutation' import { getMutationCache } from './mutationCache' import { notifyManager } from './notifyManager' -import { Subscribable } from './subscribable' -import { hashKeyByOptions, shallowEqualObjects } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' +import { defaultMutationOptions } from './queryClient' import type { Action } from './mutation' import type { QueryClient } from './queryClient' -import type { QueryRuntime } from './runtimeBinding' import type { DefaultError, MutateOptions, @@ -15,14 +17,9 @@ import type { MutationObserverResult, } from './types' -type MutationObserverListener = - Shared.MutationObserverListener< - QueryRuntime, - TData, - TError, - TVariables, - TOnMutateResult - > +type MutationObserverListener = ( + result: MutationObserverResult, +) => void // CLASS @@ -94,7 +91,7 @@ export class MutationObserver< * 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 - * QueryClient#defaultMutationOptions} before being applied. + * defaultMutationOptions} before being applied. * @example * ```ts * observer.setOptions({ @@ -114,7 +111,7 @@ export class MutationObserver< const prevOptions = this.options as | MutationObserverOptions | undefined - this.options = this.#client.defaultMutationOptions(options) + this.options = defaultMutationOptions(this.#client, options) const mutationCache = getMutationCache(this.#client) if (!shallowEqualObjects(this.options, prevOptions)) { mutationCache.notify({ diff --git a/packages/react-query-no-core/src/runtime/notifyManager.ts b/packages/react-query-pluggable/src/runtime/notifyManager.ts similarity index 92% rename from packages/react-query-no-core/src/runtime/notifyManager.ts rename to packages/react-query-pluggable/src/runtime/notifyManager.ts index 5886781bde9..f7e49b01d06 100644 --- a/packages/react-query-no-core/src/runtime/notifyManager.ts +++ b/packages/react-query-pluggable/src/runtime/notifyManager.ts @@ -1,9 +1,10 @@ -import type { - BatchCallsCallback, - NotifyCallback, - NotifyFunction, - ScheduleFunction, -} from '@tanstack/query-types/bindings' +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. @@ -100,7 +101,7 @@ export function createNotifyManager() { * @param fn - Receives a callback that runs the next batch, and schedules it. * @example * ```ts - * import { notifyManager } from '@tanstack/react-query-no-core' + * import { notifyManager } from '@tanstack/react-query-pluggable' * * // Use the v5 timer-based scheduler * notifyManager.setScheduler((cb) => setTimeout(cb, 0)) diff --git a/packages/react-query-no-core-pluggable/src/runtime/placeholderData.ts b/packages/react-query-pluggable/src/runtime/placeholderData.ts similarity index 93% rename from packages/react-query-no-core-pluggable/src/runtime/placeholderData.ts rename to packages/react-query-pluggable/src/runtime/placeholderData.ts index 71cba8df062..75a3530f771 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/placeholderData.ts +++ b/packages/react-query-pluggable/src/runtime/placeholderData.ts @@ -1,8 +1,13 @@ +import { + replaceData, + shallowEqualObjects, +} from '@tanstack/query-core/primitives' import { projectResult } from './projectResult' -import { replaceData, shallowEqualObjects } from './utils' -import type { ProjectionFailure } from '@tanstack/query-types/bindings' import type { Query } from './query' -import type { QueryObserverResultContext } from './queryObserver' +import type { + ProjectionFailure, + QueryObserverResultContext, +} from './queryObserver' import type { QueryKey, QueryObserverOptionsBase } from './types' /* #__NO_SIDE_EFFECTS__ */ diff --git a/packages/react-query-no-core-pluggable/src/runtime/projectResult.ts b/packages/react-query-pluggable/src/runtime/projectResult.ts similarity index 100% rename from packages/react-query-no-core-pluggable/src/runtime/projectResult.ts rename to packages/react-query-pluggable/src/runtime/projectResult.ts diff --git a/packages/react-query-no-core-pluggable/src/runtime/projectionTypes.ts b/packages/react-query-pluggable/src/runtime/projectionTypes.ts similarity index 100% rename from packages/react-query-no-core-pluggable/src/runtime/projectionTypes.ts rename to packages/react-query-pluggable/src/runtime/projectionTypes.ts diff --git a/packages/react-query-no-core-pluggable/src/runtime/queriesObserver.ts b/packages/react-query-pluggable/src/runtime/queriesObserver.ts similarity index 93% rename from packages/react-query-no-core-pluggable/src/runtime/queriesObserver.ts rename to packages/react-query-pluggable/src/runtime/queriesObserver.ts index 2b91a71a5d8..853e1ea15e2 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/queriesObserver.ts +++ b/packages/react-query-pluggable/src/runtime/queriesObserver.ts @@ -1,23 +1,42 @@ -import { notifyManager } from './notifyManager' -import { QueryObserver } from './queryObserver' -import { Subscribable } from './subscribable' import { + Subscribable, replaceEqualDeep, shallowEqualObjects, shouldThrowError, -} from './utils' -import type * as Shared from '@tanstack/query-types/bindings' +} from '@tanstack/query-core/primitives' +import { notifyManager } from './notifyManager' +import { defaultQueryOptions } from './queryClient' +import { QueryObserver } from './queryObserver' import type { - CombineContext, - CombineFn, - QueriesObserverListener, QueriesObserverOptions, QueriesObserverResultReader, -} from '@tanstack/query-types/bindings' + QueryObserverResultReader, +} from '@tanstack/query-core' import type { QueryClient } from './queryClient' import type { ObserverOptionsInput } from './queryObserver' -import type { QueryRuntime } from './runtimeBinding' -import type { QueryObserverResult } from './types' +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`. @@ -392,7 +411,7 @@ export class QueriesObserver< const observers: Array = [] queries.forEach((options) => { - const defaultedOptions = this.#client.defaultQueryOptions(options) + const defaultedOptions = defaultQueryOptions(this.#client, options) const match = prevObserversMap.get(defaultedOptions.queryHash)?.shift() const observer = match ?? new QueryObserver(this.#client, defaultedOptions) @@ -451,9 +470,7 @@ export class QueriesObserver< } } -type QueryObserverMatch = Shared.QueryObserverMatch - export type { QueriesObserverResultReader, QueriesObserverOptions, -} from '@tanstack/query-types/bindings' +} from '@tanstack/query-core' diff --git a/packages/react-query-no-core-pluggable/src/runtime/query.ts b/packages/react-query-pluggable/src/runtime/query.ts similarity index 87% rename from packages/react-query-no-core-pluggable/src/runtime/query.ts rename to packages/react-query-pluggable/src/runtime/query.ts index 023a10530c9..ee440535082 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/query.ts +++ b/packages/react-query-pluggable/src/runtime/query.ts @@ -1,31 +1,32 @@ -import { notifyManager } from './notifyManager' -import { Removable } from './removable' -import { CancelledError, canFetch, createRetryer } from './retryer' import { - ensureQueryFn, + CancelledError, + Removable, + createRetryer, fetchSignal, + fetchState, + getDefaultQueryState, noop, replaceData, - resolveQueryValue, skipToken, + successState, timeUntilStale, -} from './utils' -import type * as Shared from '@tanstack/query-types/bindings' +} from '@tanstack/query-core/primitives' +import { notifyManager } from './notifyManager' +import { getQueryCache } from './queryClient' +import { ensureQueryFn, resolveQueryValue } from './utils' +import type { QueryState } from '@tanstack/query-core' import type { FetchOptions, QueryAction, - QueryState, -} from '@tanstack/query-types/bindings' + Retryer, +} from '@tanstack/query-core/primitives' import type { prepareInfiniteFetch } from './infiniteQueryBehavior' import type { QueryCache } from './queryCache' import type { QueryClient } from './queryClient' import type { QueryObserver } from './queryObserver' -import type { Retryer } from './retryer' -import type { QueryRuntime } from './runtimeBinding' import type { CancelOptions, DefaultError, - InitialDataFunction, QueryKey, QueryMeta, QueryOptions, @@ -33,28 +34,77 @@ import type { StaleTime, } from './types' -type QueryConfig< +interface QueryConfig< TQueryFnData, TError, TData, TQueryKey extends QueryKey = QueryKey, -> = Shared.QueryConfig +> { + client: QueryClient + queryKey: TQueryKey + queryHash: string + options?: QueryOptions + defaultOptions?: QueryOptions + state?: QueryState +} -/** {@inheritDoc Shared.FetchContext} */ -export type FetchContext< +/** + * The context passed to a {@link QueryBehavior}'s `onFetch`, which can replace `fetchFn` to change + * how the query fetches (e.g. to fetch pages for an infinite query). + */ +export interface FetchContext< TQueryFnData, TError, TData, TQueryKey extends QueryKey = QueryKey, -> = Shared.FetchContext +> { + /** + * The function that runs the fetch. By default it calls `queryFn`; `onFetch` can replace it. + */ + fetchFn: () => unknown | Promise + /** + * The options of this fetch. + */ + fetchOptions?: FetchOptions + /** + * The `AbortSignal` that aborts when the fetch is cancelled. + */ + signal: AbortSignal + /** + * The options of the query. + */ + options: QueryOptions + /** + * The `QueryClient` the query belongs to. + */ + client: QueryClient + /** + * The key of the query. + */ + queryKey: TQueryKey + /** + * The state of the query when the fetch starts. + */ + state: QueryState +} -/** {@inheritDoc Shared.QueryBehavior} */ -export type QueryBehavior< +/** + * Customizes how a query fetches, e.g. the behavior that fetches the pages of an infinite query. + */ +export interface QueryBehavior< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> = Shared.QueryBehavior +> { + /** + * Called before each fetch of the query, e.g. to replace `fetchFn` in the context. + */ + onFetch: ( + context: FetchContext, + query: Query, + ) => void +} // CLASS @@ -68,7 +118,7 @@ export type QueryBehavior< * possible via `queryCache.find()`/`findAll()` for inspecting cache state. * @example * ```ts - * const queryCache = queryClient.getQueryCache() + * const queryCache = getQueryCache(queryClient) * const query = queryCache.find({ queryKey: ['posts'] }) * * if (query) { @@ -106,10 +156,10 @@ export class Query< this.setOptions(config.options) this.observers = [] this.#client = config.client - this.#cache = this.#client.getQueryCache() + this.#cache = getQueryCache(this.#client) this.queryKey = config.queryKey this.queryHash = config.queryHash - this.#initialState = getDefaultState(this.options) + this.#initialState = getDefaultQueryState(this.options) this.state = config.state ?? this.#initialState this.scheduleGc() } @@ -159,7 +209,7 @@ export class Query< // oxlint-disable-next-line typescript/no-unnecessary-condition -- the constructor calls 'setOptions' before it assigns 'state' if (this.state && this.state.data === undefined) { - const defaultState = getDefaultState(this.options) + const defaultState = getDefaultQueryState(this.options) if (defaultState.data !== undefined) { this.setState( successState(defaultState.data, defaultState.dataUpdatedAt), @@ -180,7 +230,7 @@ export class Query< * @internal * @param newData - The data to write. Structural sharing with the current data is applied. * @param options - Set `updatedAt` to override the timestamp, and `manual` to mark the write as - * manual (e.g. from `queryClient.setQueryData`). + * manual (e.g. from `setQueryData`). * @returns The data that was written. */ setData( @@ -776,98 +826,12 @@ export class Query< } } -/** - * Returns the state changes applied when a query starts fetching. - * @param data - The query's current data. If it is `undefined`, the query is also reset to - * `'pending'` with no error. - * @param options - The query options, whose `networkMode` decides whether the query is `'fetching'` - * or `'paused'`. - * @returns The partial query state for a starting fetch. - */ -export function fetchState< - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey, ->( - data: TData | undefined, - options: QueryOptions, -) { - return { - fetchFailureCount: 0, - fetchFailureReason: null, - fetchStatus: canFetch(options.networkMode) ? 'fetching' : 'paused', - ...(data === undefined && - ({ - error: null, - status: 'pending', - } as const)), - } as const -} - -/** - * Returns the state changes applied when a query receives data. - * @param data - The new data. - * @param dataUpdatedAt - The timestamp the data is recorded with. Defaults to the current time. - * @returns The partial query state for a successful update. - */ -function successState(data: TData | undefined, dataUpdatedAt?: number) { - return { - data, - dataUpdatedAt: dataUpdatedAt ?? Date.now(), - error: null, - isInvalidated: false, - status: 'success' as const, - } -} - -/** - * Returns the initial state of a query, based on its `initialData` and `initialDataUpdatedAt` - * options. - * @param options - The query options. - * @returns The initial query state: `'success'` if `initialData` is set, otherwise `'pending'`. - */ -function getDefaultState< - TQueryFnData, - TError, - TData, - TQueryKey extends QueryKey, ->( - options: QueryOptions, -): QueryState { - const data = - typeof options.initialData === 'function' - ? (options.initialData as InitialDataFunction)() - : options.initialData - - const hasData = data !== undefined - - const initialDataUpdatedAt = hasData - ? typeof options.initialDataUpdatedAt === 'function' - ? options.initialDataUpdatedAt() - : options.initialDataUpdatedAt - : 0 - - return { - data, - dataUpdateCount: 0, - dataUpdatedAt: hasData ? (initialDataUpdatedAt ?? Date.now()) : 0, - error: null, - errorUpdateCount: 0, - errorUpdatedAt: 0, - fetchFailureCount: 0, - fetchFailureReason: null, - fetchMeta: null, - isInvalidated: false, - status: hasData ? 'success' : 'pending', - fetchStatus: 'idle', - } -} - +export type { QueryState } from '@tanstack/query-core' export type { - QueryState, FetchDirection, FetchMeta, FetchOptions, QueryAction as Action, -} from '@tanstack/query-types/bindings' +} from '@tanstack/query-core/primitives' + +export { fetchState } from '@tanstack/query-core/primitives' diff --git a/packages/react-query-no-core/src/runtime/queryCache.ts b/packages/react-query-pluggable/src/runtime/queryCache.ts similarity index 65% rename from packages/react-query-no-core/src/runtime/queryCache.ts rename to packages/react-query-pluggable/src/runtime/queryCache.ts index 09179c347f3..7af03876b43 100644 --- a/packages/react-query-no-core/src/runtime/queryCache.ts +++ b/packages/react-query-pluggable/src/runtime/queryCache.ts @@ -1,11 +1,13 @@ +import { Subscribable, hashKeyByOptions } from '@tanstack/query-core/primitives' import { notifyManager } from './notifyManager' import { Query } from './query' -import { Subscribable } from './subscribable' -import { hashKeyByOptions, matchQuery } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' +import { defaultQueryOptions, getQueryDefaults } from './queryClient' +import { matchQuery } from './utils' +import type { CacheKeyConfig, NotifyEvent } from '@tanstack/query-core' +import type { QueryAction } from '@tanstack/query-core/primitives' import type { QueryState } from './query' import type { QueryClient } from './queryClient' -import type { QueryRuntime } from './runtimeBinding' +import type { QueryObserver } from './queryObserver' import type { DefaultError, QueryKey, @@ -14,16 +16,114 @@ import type { } from './types' import type { QueryFilters } from './utils' -/** {@inheritDoc Shared.QueryCacheConfig} */ -export type QueryCacheConfig = Shared.QueryCacheConfig +/** + * Global callbacks that fire for every query handled by a `QueryCache`, regardless of which + * component or observer triggered it. Unlike `QueryClient`'s `defaultOptions`, which a query can + * override, these callbacks are always called. Unlike `MutationCacheConfig`'s callbacks, these + * are fire-and-forget: their return value is not awaited before the query settles. + */ +export interface QueryCacheConfig { + /** + * Configures query key comparison and hashing globally. + * `equalityFn` compares individual values during partial matching and defaults to strict equality. + * `hashFn` hashes query keys and defaults to `hashKey`. + */ + queryKey?: CacheKeyConfig + /** Called when any query in the cache encounters an error. */ + onError?: ( + error: DefaultError, + query: Query, + ) => void + /** Called when any query in the cache is successful. */ + onSuccess?: (data: unknown, query: Query) => void + /** Called when any query in the cache is settled, either successfully or with an error. */ + onSettled?: ( + data: unknown | undefined, + error: DefaultError | null, + query: Query, + ) => void +} + +/** + * The event passed to a `QueryCache` subscriber. Fired whenever a query is added or removed from + * the cache, its state is updated (e.g. via `query.setState` or `removeQueries`), or + * one of its observers is added, removed, or has its results or options updated. + */ +export type QueryCacheNotifyEvent = + | NotifyEventQueryAdded + | NotifyEventQueryRemoved + | NotifyEventQueryUpdated + | NotifyEventQueryObserverAdded + | NotifyEventQueryObserverRemoved + | NotifyEventQueryObserverResultsUpdated + | NotifyEventQueryObserverOptionsUpdated + +type QueryCacheListener = (event: QueryCacheNotifyEvent) => void + +/** + * The store a `QueryCache` keeps its queries in, keyed by query hash. + */ +export interface QueryStore { + /** + * Returns whether a query with the given hash is stored. + */ + has: (queryHash: string) => boolean + /** + * Stores a query under its hash. + */ + set: (queryHash: string, query: Query) => void + /** + * Returns the query with the given hash, if any. + */ + get: (queryHash: string) => Query | undefined + /** + * Removes the query with the given hash. + */ + delete: (queryHash: string) => void + /** + * Returns an iterator over all stored queries. + */ + values: () => IterableIterator +} -/** {@inheritDoc Shared.QueryCacheNotifyEvent} */ -export type QueryCacheNotifyEvent = Shared.QueryCacheNotifyEvent +interface NotifyEventQueryAdded extends NotifyEvent { + type: 'added' + query: Query +} -type QueryCacheListener = Shared.QueryCacheListener +interface NotifyEventQueryRemoved extends NotifyEvent { + type: 'removed' + query: Query +} -/** {@inheritDoc Shared.QueryStore} */ -export type QueryStore = Shared.QueryStore +interface NotifyEventQueryUpdated extends NotifyEvent { + type: 'updated' + query: Query + action: QueryAction +} + +interface NotifyEventQueryObserverAdded extends NotifyEvent { + type: 'observerAdded' + query: Query + observer: QueryObserver +} + +interface NotifyEventQueryObserverRemoved extends NotifyEvent { + type: 'observerRemoved' + query: Query + observer: QueryObserver +} + +interface NotifyEventQueryObserverResultsUpdated extends NotifyEvent { + type: 'observerResultsUpdated' + query: Query +} + +interface NotifyEventQueryObserverOptionsUpdated extends NotifyEvent { + type: 'observerOptionsUpdated' + query: Query + observer: QueryObserver +} // CLASS @@ -58,13 +158,13 @@ export class QueryCache extends Subscribable { * the reactive `QueryObserver` machinery. * @param client - The client the query belongs to, used to default its options. * @param options - The query options, including the `queryKey`. A new query is created with the - * options defaulted by {@link QueryClient#defaultQueryOptions}. + * options defaulted by {@link defaultQueryOptions}. * @param state - The initial state of a newly created query, e.g. when hydrating. Ignored if the * query already exists. * @returns The existing or newly created query. * @example * ```ts - * const queryCache = queryClient.getQueryCache() + * const queryCache = getQueryCache(queryClient) * * const query = queryCache.build(queryClient, { * queryKey: ['posts'], @@ -95,9 +195,9 @@ export class QueryCache extends Subscribable { client, queryKey, queryHash, - options: client.defaultQueryOptions(options), + options: defaultQueryOptions(client, options), state, - defaultOptions: client.getQueryDefaults(queryKey), + defaultOptions: getQueryDefaults(client, queryKey), }) this.add(query) } @@ -130,7 +230,7 @@ export class QueryCache extends Subscribable { * @param query - The query to remove. * @example * ```ts - * const queryCache = queryClient.getQueryCache() + * const queryCache = getQueryCache(queryClient) * const query = queryCache.find({ queryKey: ['posts'] }) * * if (query) { @@ -152,7 +252,7 @@ export class QueryCache extends Subscribable { * Removes all queries from the cache. * @example * ```ts - * const queryCache = queryClient.getQueryCache() + * const queryCache = getQueryCache(queryClient) * * queryCache.clear() * ``` @@ -174,7 +274,7 @@ export class QueryCache extends Subscribable { * @returns The query stored under the hash, or `undefined`. * @example * ```ts - * const queryCache = queryClient.getQueryCache() + * const queryCache = getQueryCache(queryClient) * const queryHash = hashKey(['posts']) * * const query = queryCache.get(queryHash) @@ -198,7 +298,7 @@ export class QueryCache extends Subscribable { * @returns Every query in the cache. * @example * ```ts - * const queryCache = queryClient.getQueryCache() + * const queryCache = getQueryCache(queryClient) * * const queries = queryCache.getAll() * ``` @@ -222,7 +322,7 @@ export class QueryCache extends Subscribable { * @see {@link QueryCache#findAll} * @example * ```ts - * const queryCache = queryClient.getQueryCache() + * const queryCache = getQueryCache(queryClient) * * const query = queryCache.find({ queryKey: ['posts'] }) * ``` @@ -248,7 +348,7 @@ export class QueryCache extends Subscribable { * @see {@link QueryCache#find} * @example * ```ts - * const queryCache = queryClient.getQueryCache() + * const queryCache = getQueryCache(queryClient) * * const queries = queryCache.findAll({ queryKey: ['posts'] }) * ``` diff --git a/packages/react-query-pluggable/src/runtime/queryClient.ts b/packages/react-query-pluggable/src/runtime/queryClient.ts new file mode 100644 index 00000000000..b55f4fa76ec --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/queryClient.ts @@ -0,0 +1,783 @@ +import { + defaultQueryFn, + focusManager, + functionalUpdate, + hashKeyByOptions, + onlineManager, + partialMatchKey, + skipToken, +} from '@tanstack/query-core/primitives' +import { QueryCache } from './queryCache' +import { resolveQueryValue } from './utils' +import type { Updater } from '@tanstack/query-core/primitives' +import type { MutationCache } from './mutationCache' +import type { QueryState } from './query' +import type { + CacheKeyConfig, + DefaultError, + DefaultOptions, + DefaultedQueryObserverOptions, + InferDataFromTag, + InferErrorFromTag, + MutationKey, + MutationObserverOptions, + MutationOptions, + OmitKeyof, + QueryClientConfig, + QueryExecuteOptions, + QueryKey, + QueryObserverOptionsBase, + QueryOptions, + SetDataOptions, +} from './types' +import type { MutationFilters, QueryFilters } from './utils' + +/** Options whose query function always executes. */ +export type WithoutSkipToken = Omit< + T, + 'queryFn' +> & { + queryFn?: Exclude +} + +type QueryDefaults = OmitKeyof, 'queryKey'> +type MutationDefaults = MutationOptions + +class KeyDefaults< + TKey extends ReadonlyArray, + TOptions extends object, +> { + #entries = new Map() + + set(key: TKey, options: TOptions, config?: CacheKeyConfig): void { + this.#entries.set(hashKeyByOptions(key, config), { key, options }) + } + + get(key: TKey, config?: CacheKeyConfig): Partial { + const result: Partial = {} + for (const entry of this.#entries.values()) { + if (partialMatchKey(key, entry.key, config?.equalityFn)) { + Object.assign(result, entry.options) + } + } + return result + } +} + +/** @internal */ +export const mutationCacheKey = Symbol.for( + '@tanstack/react-query-pluggable/mutationCache', +) + +const clientState = Symbol.for('@tanstack/react-query-pluggable/clientState') + +/** Holds the caches, defaults and subscriptions shared by this client's consumers. */ +export class QueryClient { + /** @internal */ + [mutationCacheKey]?: MutationCache + /** @internal */ + readonly [clientState]: { + queryCache: QueryCache + defaultOptions: DefaultOptions + queryDefaults?: KeyDefaults + mutationDefaults?: KeyDefaults + mountCount: number + unsubscribeFocus?: () => void + unsubscribeOnline?: () => void + } + + constructor(config: QueryClientConfig = {}) { + this[mutationCacheKey] = config.mutationCache + this[clientState] = { + queryCache: config.queryCache ?? new QueryCache(), + defaultOptions: config.defaultOptions ?? {}, + mountCount: 0, + } + } +} + +/** + * Called by a framework adapter's `QueryClientProvider`-equivalent when it mounts, to start + * listening for focus/online events and resume paused mutations. Ref-counted via an internal + * mount count, so nested or multiple providers sharing the same `QueryClient` don't tear down + * the shared listeners until the last one unmounts. + * @param client - The client whose subscriptions are managed. + */ +export function mountQueryClient(client: QueryClient): void { + client[clientState].mountCount++ + if (client[clientState].mountCount !== 1) return + + client[clientState].unsubscribeFocus = focusManager.subscribe( + async (focused) => { + if (focused) { + await resumePausedMutations(client) + client[clientState].queryCache.onFocus() + } + }, + ) + client[clientState].unsubscribeOnline = onlineManager.subscribe( + async (online) => { + if (online) { + await resumePausedMutations(client) + client[clientState].queryCache.onOnline() + } + }, + ) +} + +/** + * The inverse of {@link mountQueryClient} — called by a framework adapter's + * `QueryClientProvider`-equivalent when it unmounts. Only tears down the focus/online + * listeners once the mount count returns to `0`. + * @param client - The client whose subscriptions are managed. + */ +export function unmountQueryClient(client: QueryClient): void { + client[clientState].mountCount-- + if (client[clientState].mountCount !== 0) return + + client[clientState].unsubscribeFocus?.() + client[clientState].unsubscribeFocus = undefined + + client[clientState].unsubscribeOnline?.() + client[clientState].unsubscribeOnline = undefined +} + +/** + * Returns the number of queries in the cache that are currently fetching, optionally + * matching a set of filters. This includes background-fetching, loading new pages, and + * loading more infinite query results. + * @param client - The client that owns this operation. + * @param filters - Narrows down which fetching queries are counted. Without filters, every + * fetching query is counted. + * @returns The number of matching queries whose `fetchStatus` is `'fetching'`. + * @example + * ```ts + * if (isFetching(queryClient)) { + * console.log('At least one query is fetching!') + * } + * ``` + */ +export function isFetching( + client: QueryClient, + filters?: Omit, +): number { + return client[clientState].queryCache.findAll({ + ...filters, + fetchStatus: 'fetching', + }).length +} + +/** + * Returns the number of mutations in the cache that are currently pending, optionally + * matching a set of filters. + * @param client - The client that owns this operation. + * @param filters - Narrows down which pending mutations are counted. Without filters, every + * pending mutation is counted. + * @returns The number of matching mutations whose `status` is `'pending'`. + * @example + * ```ts + * if (isMutating(queryClient)) { + * console.log('At least one mutation is pending!') + * } + * ``` + */ +export function isMutating< + TMutationFilters extends MutationFilters = MutationFilters< + any, + any + >, +>( + client: QueryClient, + filters?: NoInfer>, +): number { + return ( + client[mutationCacheKey]?.findAll({ ...filters, status: 'pending' }) + .length ?? 0 + ) +} + +/** + * Imperative (non-reactive) way to retrieve data for a QueryKey. + * Should only be used in callbacks or functions where reading the latest data is necessary, e.g. for optimistic updates. + * + * Hint: Do not use this function inside a component, because it won't receive updates. + * Use `useQuery` to create a `QueryObserver` that subscribes to changes. + * @param client - The client that owns this operation. + * @param queryKey - The query key of the query to read. + * @returns The cached data for the query, or `undefined` if no query with this key has been observed yet. + * @see {@link getQueriesData} + */ +export function getQueryData< + TQueryFnData = unknown, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, +>( + client: QueryClient, + queryKey: TTaggedQueryKey, +): TInferredQueryFnData | undefined { + const options = defaultQueryOptions(client, { queryKey }) + + return client[clientState].queryCache.get( + options.queryHash, + )?.state.data +} + +/** + * Synchronous way to immediately update a query's cached data. If the updater (or the value + * passed) resolves to `undefined`, the cache is left untouched and no query is created; + * otherwise, if the query does not exist yet, it will be created. To update multiple queries + * at once by partially matching query keys, import `setQueriesData`. + * + * Updates must be performed immutably: do not mutate `oldData`, or data previously retrieved + * via {@link getQueryData}, in place. + * @param client - The client that owns this operation. + * @param queryKey - The query key to set data for. + * @param updater - Either the new data, or a function that receives the 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 The data that was written, or `undefined` if the updater returned `undefined` — in that case + * the write is skipped and the cache is left unchanged. + * @example + * ```ts + * setQueryData(queryClient, ['posts'], newPosts) + * + * // Or, using an updater function that receives the current data: + * setQueryData(queryClient, ['posts'], (oldPosts) => [...oldPosts, newPost]) + * ``` + */ +export function setQueryData< + TQueryFnData = unknown, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, +>( + client: QueryClient, + queryKey: TTaggedQueryKey, + updater: Updater< + InferDataFromTag, TTaggedQueryKey> | undefined, + NoInfer | undefined + >, + options?: SetDataOptions, +): NoInfer | undefined { + const defaultedOptions = defaultQueryOptions< + any, + any, + unknown, + any, + QueryKey + >(client, { queryKey }) + + const query = client[clientState].queryCache.get< + InferDataFromTag, TTaggedQueryKey> + >(defaultedOptions.queryHash) + const prevData = query?.state.data + const data = functionalUpdate(updater, prevData) + + if (data === undefined) { + return undefined + } + + return client[clientState].queryCache + .build(client, defaultedOptions) + .setData(data, { ...options, manual: true }) +} + +/** + * Imperative (non-reactive) way to retrieve an existing query's state. If the query does not + * exist, `undefined` is returned. + * @param client - The client that owns this operation. + * @param queryKey - The query key of the query to read. + * @returns The query's state, or `undefined` if no query with this key exists. + * @example + * ```ts + * const state = getQueryState(queryClient, ['posts']) + * console.log(state?.dataUpdatedAt) + * ``` + */ +export function getQueryState< + TQueryFnData = unknown, + TError = DefaultError, + TTaggedQueryKey extends QueryKey = QueryKey, + TInferredQueryFnData = InferDataFromTag, + TInferredError = InferErrorFromTag, +>( + client: QueryClient, + queryKey: TTaggedQueryKey, +): QueryState | undefined { + const options = defaultQueryOptions(client, { queryKey }) + return client[clientState].queryCache.get< + TInferredQueryFnData, + TInferredError + >(options.queryHash)?.state +} + +/** + * Asynchronous method to fetch and cache a query, resolving with the data or throwing with + * the error. + * + * If the query already exists in the cache and its data is not stale (per the given + * `staleTime`), the cached data is returned without fetching. Otherwise, the query is fetched + * and the promise resolves once the fetch settles. If a `select` function is provided, it is + * applied to the data in both cases (cached or freshly fetched) before it is returned. + * + * Unlike a reactive observer, retries are disabled by default here (`retry: false`) unless + * explicitly configured, since there is no component to catch a thrown error and retry through + * re-render. + * + * The accepted options are `QueryObserverOptions` minus the fields that only make sense for a + * reactive observer — `enabled`, `refetchInterval`, `refetchIntervalInBackground`, + * `refetchOnWindowFocus`, `refetchOnReconnect`, `refetchOnMount`, `retryOnMount`, + * `notifyOnChangeProps`, `throwOnError`, `suspense`, and `placeholderData` are not part of this + * method's options. + * Shared query options can contain `skipToken` as their `queryFn`. If the supplied options contain + * the token, the call skips fetching and resolves with existing data regardless of freshness. + * It applies `select` when data exists and resolves to `undefined` on a cache miss. + * Use {@link getQueryData} to read the cache directly. + * @param client - The client that owns this operation. + * @param options - The query options, including the `queryKey` and the `queryFn` used if the + * query needs to fetch. + * @returns A promise that resolves to the data, 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 fetchQuery(queryClient, { queryKey, queryFn, staleTime: 10000 }) + * } catch (error) { + * console.log(error) + * } + * ``` + */ +export function fetchQuery< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +>( + client: QueryClient, + options: WithoutSkipToken< + QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > + >, +): Promise + +export function fetchQuery< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +>( + client: QueryClient, + options: QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, +): Promise + +export async function fetchQuery< + TQueryFnData, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +>( + client: QueryClient, + options: QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, +): Promise { + const defaultedOptions = defaultQueryOptions(client, options) + let queryData: TQueryData + + if (options.queryFn === skipToken) { + const cachedData = client[clientState].queryCache.get< + TQueryFnData, + TError, + TQueryData, + TQueryKey + >(defaultedOptions.queryHash)?.state.data + if (cachedData === undefined) return undefined + queryData = cachedData + } else { + // https://github.com/tannerlinsley/react-query/issues/652 + if (defaultedOptions.retry === undefined) { + defaultedOptions.retry = false + } + + const query = client[clientState].queryCache.build(client, defaultedOptions) + + const isStale = query.isStaleByTime( + resolveQueryValue(defaultedOptions.staleTime, query), + ) + + queryData = isStale + ? await query.fetch(defaultedOptions) + : (query.state.data as TQueryData) + } + + const select = defaultedOptions.select + + if (select) { + return select[1](queryData) + } + + return queryData as unknown as TData +} + +/** + * Resumes mutations that were paused because there was no network connection. Does nothing + * (resolving immediately) if the client is currently offline. + * @param client - The client that owns this operation. + * @returns A promise that resolves once the resumed mutations have settled. + * @example + * ```ts + * import { QueryClient, resumePausedMutations } from '@tanstack/react-query-pluggable' + * + * const queryClient = new QueryClient() + * await resumePausedMutations(queryClient) + * ``` + */ +export function resumePausedMutations(client: QueryClient): Promise { + if (onlineManager.isOnline()) { + return ( + client[mutationCacheKey]?.resumePausedMutations() ?? Promise.resolve([]) + ) + } + return Promise.resolve() +} + +/** + * Returns the query cache this client is connected to. + * @param client - The client that owns this operation. + * @returns The {@link QueryCache} instance. + * @example + * ```ts + * import { QueryClient, getQueryCache } from '@tanstack/react-query-pluggable' + * + * const queryClient = new QueryClient() + * const queryCache = getQueryCache(queryClient) + * const queries = queryCache.findAll({ queryKey: ['posts'] }) + * ``` + */ +export function getQueryCache(client: QueryClient): QueryCache { + return client[clientState].queryCache +} + +/** + * Returns the default options that were set when creating the client, or via + * {@link setDefaultOptions}. + * @param client - The client that owns this operation. + * @returns The client's current default options. + * @example + * ```ts + * import { QueryClient, getDefaultOptions } from '@tanstack/react-query-pluggable' + * + * const queryClient = new QueryClient() + * const defaultOptions = getDefaultOptions(queryClient) + * ``` + */ +export function getDefaultOptions(client: QueryClient): DefaultOptions { + return client[clientState].defaultOptions +} + +/** + * Dynamically sets the default options for this client, overwriting any previously defined + * default options. + * @param client - The client that owns this operation. + * @param options - The new default options for queries and mutations. + * @see {@link getDefaultOptions} + * @example + * ```ts + * import { QueryClient, setDefaultOptions } from '@tanstack/react-query-pluggable' + * + * const queryClient = new QueryClient() + * setDefaultOptions(queryClient, { + * queries: { + * staleTime: Infinity, + * }, + * }) + * ``` + */ +export function setDefaultOptions( + client: QueryClient, + options: DefaultOptions, +): void { + client[clientState].defaultOptions = options +} + +/** + * Sets default options for queries whose query key partially matches the given `queryKey`. + * + * If several registered query defaults match a given query key, they are merged together in + * registration order by {@link getQueryDefaults}, so register defaults from the + * most generic key to the least generic one — more specific defaults should be registered + * after more generic ones so they take precedence. + * @param client - The client that owns this operation. + * @param queryKey - The query key that query keys are partially matched against. + * @param options - The default options applied to matching queries. + * @example + * ```ts + * setQueryDefaults(queryClient, ['posts'], { queryFn: fetchPosts }) + * + * await fetchQuery(queryClient, { queryKey: ['posts'] }) + * ``` + */ +export function setQueryDefaults< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, +>( + client: QueryClient, + queryKey: QueryKey, + options: Partial< + OmitKeyof< + QueryObserverOptionsBase, + 'queryKey' + > + >, +): void { + ;(client[clientState].queryDefaults ??= new KeyDefaults()).set( + queryKey, + options, + client[clientState].queryCache.config.queryKey, + ) +} + +/** + * Returns the default options registered for queries whose query key partially matches the + * given `queryKey`, via {@link setQueryDefaults}. If multiple registered defaults + * match, they are merged together in registration order. + * @param client - The client that owns this operation. + * @param queryKey - The query key to look up registered defaults for. + * @returns The merged default options of every registration that matches, or an empty object if + * none match. + * @example + * ```ts + * const defaultOptions = getQueryDefaults(queryClient, ['posts']) + * ``` + */ +export function getQueryDefaults( + client: QueryClient, + queryKey: QueryKey, +): OmitKeyof, 'queryKey'> { + return ( + client[clientState].queryDefaults?.get( + queryKey, + client[clientState].queryCache.config.queryKey, + ) ?? {} + ) +} + +/** + * Sets default options for mutations whose mutation key partially matches the given + * `mutationKey`. As with {@link setQueryDefaults}, the order of registration + * matters when several registered defaults match the same mutation key. + * @param client - The client that owns this operation. + * @param mutationKey - The mutation key that mutation keys are partially matched against. + * @param options - The default options applied to matching mutations. + * @see {@link getMutationDefaults} + * @example + * ```ts + * setMutationDefaults(queryClient, ['addPost'], { mutationFn: addPost }) + * ``` + */ +export function setMutationDefaults< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +>( + client: QueryClient, + mutationKey: MutationKey, + options: OmitKeyof< + MutationObserverOptions, + 'mutationKey' + >, +): void { + ;(client[clientState].mutationDefaults ??= new KeyDefaults()).set( + mutationKey, + options, + client[mutationCacheKey]?.config.mutationKey, + ) +} + +/** + * Returns the default options registered for mutations whose mutation key partially matches + * the given `mutationKey`, via {@link setMutationDefaults}. If multiple registered + * defaults match, they are merged together in registration order. + * @param client - The client that owns this operation. + * @param mutationKey - The mutation key to look up registered defaults for. + * @returns The merged default options of every registration that matches, or an empty object if + * none match. + * @example + * ```ts + * const defaultOptions = getMutationDefaults(queryClient, ['addPost']) + * ``` + */ +export function getMutationDefaults( + client: QueryClient, + mutationKey: MutationKey, +): OmitKeyof, 'mutationKey'> { + return ( + client[clientState].mutationDefaults?.get( + mutationKey, + client[mutationCacheKey]?.config.mutationKey, + ) ?? {} + ) +} + +/** + * Called by framework adapters (e.g. inside `useQuery`) to resolve the options passed by the + * caller into their final, defaulted form: merging the client's own `defaultOptions.queries`, + * then `setQueryDefaults` for the given `queryKey`, then the caller's options on + * top. A no-op if the options are already defaulted (`_defaulted: true`). + * @param client - The client that owns this operation. + * @param options - The query options passed by the caller. + * @returns The defaulted options, with `queryHash` and dependent defaults (e.g. + * `refetchOnReconnect`) filled in. + */ +export function defaultQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +>( + client: QueryClient, + options: QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, +): DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam +> { + if (options._defaulted) { + return options as DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > + } + + const queryDefaults = getQueryDefaults(client, options.queryKey) + const defaultedOptions = { + ...client[clientState].defaultOptions.queries, + ...queryDefaults, + ...options, + _defaulted: true, + } + + if (defaultedOptions.queryFn === defaultQueryFn) { + defaultedOptions.queryFn = + 'queryFn' in queryDefaults + ? queryDefaults.queryFn + : client[clientState].defaultOptions.queries?.queryFn + } + + if (!defaultedOptions.queryHash) { + defaultedOptions.queryHash = hashKeyByOptions( + defaultedOptions.queryKey, + client[clientState].queryCache.config.queryKey, + ) + } + + // dependent default values + if (defaultedOptions.refetchOnReconnect === undefined) { + defaultedOptions.refetchOnReconnect = + defaultedOptions.networkMode !== 'always' + } + if (defaultedOptions.throwOnError === undefined) { + defaultedOptions.throwOnError = !!defaultedOptions.suspense + } + + if (!defaultedOptions.networkMode && defaultedOptions.persister) { + defaultedOptions.networkMode = 'offlineFirst' + } + + if (defaultedOptions.queryFn === skipToken) { + defaultedOptions.enabled = false + } + + return defaultedOptions as DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + > +} + +/** + * The mutation counterpart of {@link defaultQueryOptions}. Called by framework + * adapters (e.g. inside `useMutation`) to merge the client's `defaultOptions.mutations`, then + * `setMutationDefaults` for the given `mutationKey`, then the caller's options on + * top. A no-op if the options are already defaulted (`_defaulted: true`). + * @param client - The client that owns this operation. + * @param options - The mutation options passed by the caller. + * @returns The defaulted options. + */ +export function defaultMutationOptions< + T extends MutationOptions, +>(client: QueryClient, options?: T): T { + if (options?._defaulted) { + return options + } + return { + ...client[clientState].defaultOptions.mutations, + ...(options?.mutationKey && + getMutationDefaults(client, options.mutationKey)), + ...options, + _defaulted: true, + } as T +} + +/** + * Clears both the query cache and the mutation cache this client is connected to. + * This clears their garbage collection timers and cancels in-flight query fetches. + * Running mutations continue to execute. + * @param client - The client that owns this operation. + * @example + * ```ts + * import { QueryClient, clearQueryClient } from '@tanstack/react-query-pluggable' + * + * const queryClient = new QueryClient() + * clearQueryClient(queryClient) + * ``` + */ +export function clearQueryClient(client: QueryClient): void { + client[clientState].queryCache.clear() + client[mutationCacheKey]?.clear() +} diff --git a/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts b/packages/react-query-pluggable/src/runtime/queryObserver.ts similarity index 88% rename from packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts rename to packages/react-query-pluggable/src/runtime/queryObserver.ts index 2cfc3ed04a5..a87495bd53d 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/queryObserver.ts +++ b/packages/react-query-pluggable/src/runtime/queryObserver.ts @@ -1,68 +1,132 @@ -import { isServer as isServerEnvironment } from './environmentManager' -import { notifyManager } from './notifyManager' -import { fetchState } from './query' -import { Subscribable } from './subscribable' -import { timeoutManager } from './timeoutManager' import { + Subscribable, + fetchState, + isServer as isServerEnvironment, isValidTimeout, noop, - resolveQueryValue, shallowEqualObjects, timeUntilStale, -} from './utils' -import type * as Shared from '@tanstack/query-types/bindings' + timeoutManager, +} from '@tanstack/query-core/primitives' +import { notifyManager } from './notifyManager' +import { defaultQueryOptions, getQueryCache } from './queryClient' +import { resolveQueryValue } from './utils' +import type { QueryObserverResultReader } from '@tanstack/query-core' import type { - ObserverFetchOptions, - QueryObserverListener, - QueryObserverResultReader, -} from '@tanstack/query-types/bindings' + FetchOptions, + ManagedTimerId, +} from '@tanstack/query-core/primitives' import type { projectResult } from './projectResult' import type { Query, QueryState } from './query' import type { QueryClient } from './queryClient' import type { PollingTimer } from './refetchInterval' -import type { QueryRuntime } from './runtimeBinding' -import type { ManagedTimerId } from './timeoutManager' import type { DefaultError, DefaultedQueryObserverOptions, + PlaceholderValue, QueryKey, QueryObserverBaseResult, + QueryObserverOptions, QueryObserverOptionsBase, QueryObserverResult, + QueryOptions, RefetchOptions, } from './types' -/** {@inheritDoc Shared.QueryObserverResultContext} */ -export type QueryObserverResultContext< +/** The last selector or placeholder error and when it occurred. */ +export type ProjectionFailure = { + /** The error thrown while computing the result. */ + error: TError + /** Timestamp of the failed computation. */ + errorUpdatedAt: number +} + +interface ObserverFetchOptions extends FetchOptions { + throwOnError?: boolean +} + +type QueryObserverListener = ( + result: QueryObserverResult, +) => void + +/** + * Selection and placeholder computation state shared by reads of the same result. + * @internal + */ +export interface QueryObserverResultContext< TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey, -> = Shared.QueryObserverResultContext< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey -> & { project?: typeof projectResult } +> { + /** The optional result projection that produced this reader’s cached state. */ + project?: typeof projectResult + + /** The memo key and failure of the most recent selection. */ + selection?: { + key: { + input: TQueryData + select: (data: TQueryData) => TData + structuralSharing: QueryOptions< + TQueryFnData, + TError, + TQueryData, + TQueryKey + >['structuralSharing'] + } + failure?: ProjectionFailure + } + /** The last successful selection, used if selection fails. */ + selected?: { + data: TData + query?: Query + } + /** The unselected placeholder or factory error. */ + placeholder?: { + key: { + placeholderData: + | PlaceholderValue + | undefined + structuralSharing: QueryOptions< + TQueryFnData, + TError, + TQueryData, + TQueryKey + >['structuralSharing'] + previousQuery: + | Query + | undefined + previousState: QueryState | undefined + previousOptions: + | QueryOptions + | undefined + } + sourceQuery?: Query + input: TQueryData | undefined + failure?: ProjectionFailure + } +} -/** {@inheritDoc Shared.ObserverOptionsInput} */ +/** + * Options supplied to an observer by a caller or already resolved by the client. + * @internal + */ export type ObserverOptionsInput< TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> = Shared.ObserverOptionsInput< - QueryRuntime, - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey -> +> = + | QueryObserverOptions + | DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + > /** * A `QueryObserver` watches a single query in the `QueryCache` and computes a @@ -202,7 +266,7 @@ export class QueryObserver< * subscribers, recompute the current result, and reschedule the stale and * refetch-interval timers as needed. * @param options - The new observer options. They are defaulted with {@link - * QueryClient#defaultQueryOptions} before being applied. + * defaultQueryOptions} before being applied. * @throws {Error} If `enabled` is neither a boolean nor a function. * @example * ```ts @@ -223,7 +287,7 @@ export class QueryObserver< const prevOptions = this.options const prevQuery = this.#currentQuery - this.options = this.#client.defaultQueryOptions(options) + this.options = defaultQueryOptions(this.#client, options) if ( this.options.enabled !== undefined && @@ -244,7 +308,7 @@ export class QueryObserver< prevOptions._defaulted && !shallowEqualObjects(this.options, prevOptions) ) { - this.#client.getQueryCache().notify({ + getQueryCache(this.#client).notify({ type: 'observerOptionsUpdated', query: this.#currentQuery, observer: this, @@ -308,9 +372,10 @@ export class QueryObserver< let result = this.#currentResult const getSnapshot = () => { - const query = this.#client - .getQueryCache() - .build(this.#client, readerOptions) + const query = getQueryCache(this.#client).build( + this.#client, + readerOptions, + ) readerOptions.select?.[0].reuse( readerOptions, query, @@ -442,14 +507,15 @@ export class QueryObserver< TQueryKey >, ): Promise> { - const defaultedOptions = this.#client.defaultQueryOptions(options) + const defaultedOptions = defaultQueryOptions(this.#client, options) - const query = this.#client - .getQueryCache() - .build(this.#client, defaultedOptions) + const query = getQueryCache(this.#client).build( + this.#client, + defaultedOptions, + ) const cached = Promise.withResolvers>() - const unsubscribe = this.#client.getQueryCache().subscribe((event) => { + const unsubscribe = getQueryCache(this.#client).subscribe((event) => { if ( event.type === 'updated' && event.query.queryHash === query.queryHash && @@ -736,7 +802,7 @@ export class QueryObserver< } // Then the cache listeners - this.#client.getQueryCache().notify({ + getQueryCache(this.#client).notify({ query: this.#currentQuery, type: 'observerResultsUpdated', }) @@ -744,7 +810,7 @@ export class QueryObserver< } #updateQuery(): void { - const query = this.#client.getQueryCache().build(this.#client, this.options) + const query = getQueryCache(this.#client).build(this.#client, this.options) if (query === this.#currentQuery) { return @@ -881,4 +947,4 @@ function isStale( ) } -export type { QueryObserverResultReader } from '@tanstack/query-types/bindings' +export type { QueryObserverResultReader } from '@tanstack/query-core' diff --git a/packages/react-query-no-core-pluggable/src/runtime/refetchInterval.ts b/packages/react-query-pluggable/src/runtime/refetchInterval.ts similarity index 91% rename from packages/react-query-no-core-pluggable/src/runtime/refetchInterval.ts rename to packages/react-query-pluggable/src/runtime/refetchInterval.ts index 20a1733de0b..332d9978b9d 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/refetchInterval.ts +++ b/packages/react-query-pluggable/src/runtime/refetchInterval.ts @@ -1,8 +1,11 @@ -import { isServer } from './environmentManager' -import { focusManager } from './focusManager' -import { timeoutManager } from './timeoutManager' -import { isValidTimeout, resolveQueryValue } from './utils' -import type { QueryKey } from '@tanstack/query-types/bindings' +import { + focusManager, + isServer, + isValidTimeout, + timeoutManager, +} from '@tanstack/query-core/primitives' +import { resolveQueryValue } from './utils' +import type { QueryKey } from '@tanstack/query-core' import type { Query } from './query' interface PollingTimer { diff --git a/packages/react-query-no-core-pluggable/src/runtime/select.ts b/packages/react-query-pluggable/src/runtime/select.ts similarity index 97% rename from packages/react-query-no-core-pluggable/src/runtime/select.ts rename to packages/react-query-pluggable/src/runtime/select.ts index 7b69dbecc7e..c52e6bb2228 100644 --- a/packages/react-query-no-core-pluggable/src/runtime/select.ts +++ b/packages/react-query-pluggable/src/runtime/select.ts @@ -1,5 +1,8 @@ +import { + replaceData, + shallowEqualObjects, +} from '@tanstack/query-core/primitives' import { projectResult } from './projectResult' -import { replaceData, shallowEqualObjects } from './utils' import type { Select } from './projectionTypes' import type { Query } from './query' import type { QueryObserverResultContext } from './queryObserver' diff --git a/packages/react-query-no-core-pluggable/src/runtime/serialScope.ts b/packages/react-query-pluggable/src/runtime/serialScope.ts similarity index 100% rename from packages/react-query-no-core-pluggable/src/runtime/serialScope.ts rename to packages/react-query-pluggable/src/runtime/serialScope.ts diff --git a/packages/react-query-no-core/src/runtime/streamedQuery.ts b/packages/react-query-pluggable/src/runtime/streamedQuery.ts similarity index 58% rename from packages/react-query-no-core/src/runtime/streamedQuery.ts rename to packages/react-query-pluggable/src/runtime/streamedQuery.ts index 6efb1dbfcdd..428da5442bb 100644 --- a/packages/react-query-no-core/src/runtime/streamedQuery.ts +++ b/packages/react-query-pluggable/src/runtime/streamedQuery.ts @@ -1,14 +1,57 @@ -import { addConsumeAwareSignal, fetchSignal } from './utils' -import type * as Shared from '@tanstack/query-types/bindings' -import type { QueryRuntime } from './runtimeBinding' -import type { OmitKeyof, QueryFunction, QueryKey } from './types' -import type { FetchSignalContext } from './utils' +import { + addConsumeAwareSignal, + fetchSignal, +} from '@tanstack/query-core/primitives' +import { getQueryCache, getQueryData, setQueryData } from './queryClient' +import type { FetchSignalContext } from '@tanstack/query-core/primitives' +import type { + OmitKeyof, + QueryFunction, + QueryFunctionContext, + QueryKey, +} from './types' -type StreamedQueryParams< +type StreamedQueryParams = + | SimpleStreamedQueryParams + | ReducibleStreamedQueryParams + +type SimpleStreamedQueryParams< + TQueryFnData, + TQueryKey extends QueryKey, +> = BaseStreamedQueryParams & { + reducer?: never + initialValue?: never +} + +type ReducibleStreamedQueryParams< TQueryFnData, TData, TQueryKey extends QueryKey, -> = Shared.StreamedQueryParams +> = BaseStreamedQueryParams & { + /** + * Combines the accumulated data with the next chunk. Provide `initialValue` with a custom reducer. + */ + reducer: (acc: TData, chunk: TQueryFnData) => TData + /** + * The starting value for the reducer when there is no cached data or when + * `refetchMode` is `'replace'` during a refetch. + */ + initialValue: TData +} + +type BaseStreamedQueryParams = { + /** Returns an `AsyncIterable` or a promise that resolves to one. */ + streamFn: ( + context: QueryFunctionContext, + ) => AsyncIterable | Promise> + /** + * Defines how refetches are handled. + * - `'reset'` (default): resets the query to its initial state before reading the stream. + * - `'append'`: appends new data to the existing data. + * - `'replace'`: writes all data to the cache once the stream ends. + */ + refetchMode?: 'append' | 'reset' | 'replace' +} /** * Creates a query function that streams data from an `AsyncIterable`. @@ -24,7 +67,7 @@ type StreamedQueryParams< * @returns A query function to pass as `queryFn`. * @example * ```ts - * await queryClient.query({ + * await fetchQuery(queryClient, { * queryKey: ['data'], * queryFn: streamedQuery({ * streamFn: fetchDataInChunks, @@ -53,9 +96,10 @@ export function streamedQuery< return initialValue } - const query = context.client - .getQueryCache() - .find({ queryKey: context.queryKey, exact: true }) + const query = getQueryCache(context.client).find({ + queryKey: context.queryKey, + exact: true, + }) const isRefetch = !!query && query.isFetched() if (isRefetch && refetchMode === 'reset') { query.setState({ @@ -95,7 +139,7 @@ export function streamedQuery< // don't append to the cache directly when replace-refetching result = reducer(result, chunk) } else { - context.client.setQueryData(context.queryKey, (prev) => + setQueryData(context.client, context.queryKey, (prev) => reducer(prev === undefined ? initialValue : prev, chunk), ) } @@ -103,10 +147,10 @@ export function streamedQuery< // finalize result: replace-refetching needs to write to the cache if (isReplaceRefetch && !isStreamInactive()) { - context.client.setQueryData(context.queryKey, result) + setQueryData(context.client, context.queryKey, result) } - const data = context.client.getQueryData(context.queryKey) + const data = getQueryData(context.client, context.queryKey) return data === undefined ? initialValue : data } } diff --git a/packages/react-query-pluggable/src/runtime/types.ts b/packages/react-query-pluggable/src/runtime/types.ts new file mode 100644 index 00000000000..f1bc0a0e9b2 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/types.ts @@ -0,0 +1,788 @@ +import type { + DefaultError, + InfiniteData, + InfiniteQueryPageParamsOptions, + OmitKeyof, + QueryKey, + QueryMeta, + StaleTime, + WithRequired, +} from '@tanstack/query-core' +import type * as Core from '@tanstack/query-core' +import type { + DefaultQueryFn, + QueryTypeFilter, + SkipToken, +} from '@tanstack/query-core/primitives' +import type * as CorePrimitives from '@tanstack/query-core/primitives' +import type { DehydrateOptions, HydrateOptions } from './hydration' +import type { MutationCache } from './mutationCache' +import type { placeholderData } from './placeholderData' +import type { Select } from './projectionTypes' +import type { Query } from './query' +import type { QueryCache } from './queryCache' +import type { QueryClient } from './queryClient' +import type { RefetchInterval } from './refetchInterval' +import type { SerialScope } from './serialScope' +import type { QueryFilters } from './utils' + +/** @inline */ +export type QueryFunction< + T = unknown, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = (context: QueryFunctionContext) => T | Promise + +/** @inline */ +export type StaleTimeFunction< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = + | StaleTime + | ((query: Query) => StaleTime) + +/** @inline */ +export type QueryBooleanOption< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = + | boolean + | ((query: Query) => boolean) + +/** @inline */ +export type QueryPersister< + T = unknown, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = [TPageParam] extends [never] + ? ( + queryFn: QueryFunction, + context: QueryFunctionContext, + query: Query, + ) => T | Promise + : ( + queryFn: QueryFunction, + context: QueryFunctionContext, + query: Query, + ) => T | Promise + +/** + * The object passed to `queryFn`: the `QueryClient`, the `queryKey`, an `AbortSignal` that aborts + * when the query is cancelled, the query's `meta`, and for infinite queries the `pageParam` of the + * page being fetched. + */ +export type QueryFunctionContext< + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = [TPageParam] extends [never] + ? { + client: QueryClient + queryKey: TQueryKey + signal: AbortSignal + meta: QueryMeta | undefined + pageParam?: unknown + } + : { + client: QueryClient + queryKey: TQueryKey + signal: AbortSignal + meta: QueryMeta | undefined + pageParam: TPageParam + } + +/** @inline */ +export type PlaceholderDataFunction< + TQueryFnData = unknown, + TError = DefaultError, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = ( + previousData: TQueryData | undefined, + previousQuery: Query | undefined, +) => TQueryData | undefined + +/** Query cache options. The query function and persister receive this adapter’s client. */ +export interface QueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> extends Omit< + Core.QueryOptions, + 'queryFn' | 'persister' +> { + /** + * The function that the query will use to request data. + * Pass `defaultQueryFn` to use the function configured in the client's query defaults. + * Pass `skipToken` to disable a query without a function where supported. + * Receives a {@link QueryFunctionContext}. + * Must return a promise that will either resolve data or throw an error. The data cannot be `undefined`. + */ + queryFn?: + | QueryFunction + | SkipToken + | DefaultQueryFn + /** + * This option can be used to persist the result of a query to an external storage, bypassing the need to actually + * call the `queryFn`. Useful for persisting a query's data across e.g. server/client boundaries. + */ + persister?: QueryPersister, TPageParam> +} + +/** @inline */ +export type ThrowOnError< + TQueryFnData, + TError, + TQueryData, + TQueryKey extends QueryKey, +> = + | boolean + | (( + error: TError, + query: Query, + ) => boolean) + +/** Shared observer options, including opt-in selection, placeholder data, and polling. */ +export interface QueryObserverOptionsBase< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> + extends + WithRequired< + QueryOptions, + 'queryKey' + >, + Pick< + CorePrimitives.QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + | 'refetchIntervalInBackground' + | 'notifyOnChangeProps' + | 'suspense' + | '_optimisticResults' + > { + /** + * Set this to `false` or a function that returns `false` to disable automatic refetching when the query mounts or changes query keys. + * To refetch the query, use the `refetch` method returned from the `useQuery` instance. + * Accepts a boolean or function that returns a boolean. + * @defaultValue true + */ + enabled?: QueryBooleanOption + /** + * The time in milliseconds after data is considered stale. + * If set to `Infinity`, the data will never be considered stale. + * If set to `'static'`, the data will never be considered stale. + * If set to a function, the function will be executed with the query to compute a `staleTime`. + * @defaultValue 0 + */ + staleTime?: StaleTimeFunction + /** Set refetchInterval(milliseconds) or return it from a callback to poll the query. */ + refetchInterval?: + | false + | RefetchInterval> + | (( + query: Query, + ) => + | false + | undefined + | RefetchInterval>) + /** + * If set to `true`, the query will refetch on window focus if the data is stale. + * If set to `false`, the query will not refetch on window focus. + * If set to `'always'`, the query will always refetch on window focus (except when `staleTime: 'static'` is used). + * If set to a function, the function will be executed with the latest data and query to compute the value. + * @defaultValue true + */ + refetchOnWindowFocus?: + | boolean + | 'always' + | (( + query: Query, + ) => boolean | 'always') + /** + * If set to `true`, the query will refetch on reconnect if the data is stale. + * If set to `false`, the query will not refetch on reconnect. + * If set to `'always'`, the query will always refetch on reconnect (except when `staleTime: 'static'` is used). + * If set to a function, the function will be executed with the latest data and query to compute the value. + * + * Defaults to `true` unless `networkMode` is `'always'`. + */ + refetchOnReconnect?: + | boolean + | 'always' + | (( + query: Query, + ) => boolean | 'always') + /** + * If set to `true`, the query will refetch on mount if the data is stale. + * If set to `false`, will disable additional instances of a query to trigger background refetch. + * If set to `'always'`, the query will always refetch on mount (except when `staleTime: 'static'` is used). + * If set to a function, the function will be executed with the latest data and query to compute the value + * @defaultValue true + */ + refetchOnMount?: + | boolean + | 'always' + | (( + query: Query, + ) => boolean | 'always') + /** + * If set to `false`, the query will not be retried on mount if it contains an error. + * If set to a function, the function will be executed with the query to compute the value. + * @defaultValue true + */ + retryOnMount?: QueryBooleanOption + /** + * Whether errors should be thrown instead of setting the `error` property. + * If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. + * If set to `false` and `suspense` is `false`, errors are returned as state. + * If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`). + * @defaultValue false + */ + throwOnError?: ThrowOnError + /** Pass [select, transform] to derive the data returned by this observer. */ + select?: Select + /** Wrap a value or factory with placeholderData to display it while the query loads. */ + placeholderData?: readonly [ + feature: typeof placeholderData, + value: PlaceholderValue, + ] +} + +/** + * The options of a `QueryObserver`, and of the hooks built on it like `useQuery`: the + * {@link QueryOptions} of the query, plus options that control the observer, such as `enabled`, + * `staleTime`, `refetchInterval`, `select`, and `placeholderData`. + * Pass a `queryFn` or use `defaultQueryFn` to select the client defaults. + */ +export interface QueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> extends WithRequired< + QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + 'queryFn' +> {} + +/** + * The {@link QueryObserverOptions} after `defaultQueryOptions` has applied the + * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. + */ +export type DefaultedQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> = WithRequired< + QueryObserverOptionsBase< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + 'throwOnError' | 'refetchOnReconnect' | 'queryHash' +> + +/** + * The options of an `InfiniteQueryObserver`: {@link QueryObserverOptions} whose query data is + * {@link InfiniteData}, plus the page param options. + */ +export interface InfiniteQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> + extends + QueryObserverOptions< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey, + TPageParam + >, + InfiniteQueryPageParamsOptions {} + +/** + * The {@link InfiniteQueryObserverOptions} after `defaultQueryOptions` has applied the + * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. + */ +export type DefaultedInfiniteQueryObserverOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey, + TPageParam +> & + InfiniteQueryPageParamsOptions + +/** + * The options of `fetchQuery`: the {@link QueryOptions} of the query, plus a `staleTime` + * that decides whether cached data is returned instead of fetching, and a `select` that only + * transforms the value the call resolves with. + */ +export interface QueryExecuteOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = never, +> + extends + WithRequired< + QueryOptions, + 'queryKey' + >, + Pick< + Core.QueryExecuteOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey, + TPageParam + >, + 'initialPageParam' + > { + /** Pass [select, transform] to derive the resolved value while retaining the fetched data in the cache. */ + select?: Select + /** + * The time in milliseconds after data is considered stale. + * If the data is fresh it will be returned from the cache. + */ + staleTime?: StaleTimeFunction +} + +/** + * The options of `fetchInfiniteQuery`. Extends {@link QueryExecuteOptions} + * with `initialPageParam`, `getNextPageParam`, and the optional `pages` count. + */ +export type InfiniteQueryExecuteOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = InfiniteData, + TQueryKey extends QueryKey = QueryKey, + TPageParam = unknown, +> = Omit< + QueryExecuteOptions< + TQueryFnData, + TError, + TData, + InfiniteData, + TQueryKey, + TPageParam + >, + 'initialPageParam' +> & + InfiniteQueryFetchPageOptions + +/** + * The filters of `invalidateQueries`: the {@link QueryFilters} that select the queries + * to invalidate, plus `refetchType` to choose which of them are refetched. + */ +export interface InvalidateQueryFilters< + TQueryKey extends QueryKey = QueryKey, +> extends QueryFilters { + /** + * Controls which of the matched (now-invalidated) queries are refetched in the background. + * + * - `'active'`: only queries with at least one active observer are refetched. + * - `'inactive'`: only queries with no active observer are refetched. + * - `'all'`: every matched query is refetched, active or not. + * - `'none'`: no query is refetched; matched queries are only marked as invalidated. + * @defaultValue 'active' + */ + refetchType?: QueryTypeFilter | 'none' +} + +/** + * The filters of `refetchQueries`, which select the queries to refetch. + */ +export interface RefetchQueryFilters< + TQueryKey extends QueryKey = QueryKey, +> extends QueryFilters {} + +/** + * The object passed to `mutationFn` and the mutation callbacks: the `QueryClient`, the mutation's + * `meta`, and its `mutationKey`. + */ +export type MutationFunctionContext = Core.Override< + Core.MutationFunctionContext, + { client: QueryClient } +> + +/** @inline */ +export type MutationFunction = ( + variables: TVariables, + context: MutationFunctionContext, +) => Promise + +/** + * The options of a mutation: its `mutationFn`, `mutationKey`, callbacks, retries, `scope`, and so + * on. + */ +export interface MutationOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> extends Omit< + Core.MutationOptions, + 'mutationFn' | 'onMutate' | 'onSuccess' | 'onError' | 'onSettled' | 'scope' +> { + /** + * The function that performs the asynchronous task this mutation runs. + * Required, unless a default mutation function has been set for the matching `mutationKey` via + * `setMutationDefaults`. + * Receives the `variables` passed to `mutate`, and a {@link MutationFunctionContext} holding the + * `QueryClient`, the `mutationKey` and `meta`. + * Must return a promise that resolves the mutation's data. + */ + mutationFn?: MutationFunction + /** + * This function fires before the mutation function runs, and receives the same variables. + * Useful for optimistic updates applied in the hope that the mutation succeeds. + * The value it returns is passed to `onSuccess`, `onError` and `onSettled` as `onMutateResult`, + * which is where an optimistic update is usually rolled back. + * If a promise is returned, it is awaited before the mutation function runs. + */ + onMutate?: ( + variables: TVariables, + context: MutationFunctionContext, + ) => Promise | TOnMutateResult + /** + * This function fires when the mutation succeeds, and is passed the mutation's result. + * If a promise is returned, it is awaited before `onSettled` runs. + */ + onSuccess?: ( + data: TData, + variables: TVariables, + onMutateResult: TOnMutateResult, + context: MutationFunctionContext, + ) => Promise | unknown + /** + * This function fires when the mutation encounters an error, and is passed the error. + * If a promise is returned, it is awaited before `onSettled` runs. + */ + onError?: ( + error: TError, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => Promise | unknown + /** + * This function fires when the mutation either succeeds or errors, and is passed either the data + * or the error. + * If a promise is returned, it is awaited before the mutation settles. + */ + onSettled?: ( + data: TData | undefined, + error: TError | null, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => Promise | unknown + /** Pass serialScope(id) to run mutations with this ID in order. */ + scope?: SerialScope +} + +/** + * The options of a `MutationObserver`, and of the hooks built on it like `useMutation`: the + * {@link MutationOptions}, plus `throwOnError`. + */ +export interface MutationObserverOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> + extends + MutationOptions, + Pick< + Core.MutationObserverOptions, + 'throwOnError' + > {} + +/** + * The callbacks that can be passed to `mutate` for a single call. They run after the callbacks of + * the mutation options. + */ +export interface MutateOptions< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> { + /** + * Called when the mutation of this call succeeds, after the `onSuccess` of the mutation options. + */ + onSuccess?: ( + data: TData, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => void + /** + * Called when the mutation of this call fails, after the `onError` of the mutation options. + */ + onError?: ( + error: TError, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => void + /** + * Called when the mutation of this call succeeds or fails, after the `onSettled` of the mutation + * options. + */ + onSettled?: ( + data: TData | undefined, + error: TError | null, + variables: TVariables, + onMutateResult: TOnMutateResult | undefined, + context: MutationFunctionContext, + ) => void +} + +/** + * The parameters of {@link MutateFunction}: `variables`, optional when `TVariables` accepts + * `undefined`, and the {@link MutateOptions} for that call. + */ +export type MutateFunctionRest< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = undefined extends TVariables + ? [ + variables?: TVariables, + options?: MutateOptions, + ] + : [ + variables: TVariables, + options?: MutateOptions, + ] + +/** + * The `mutate` function of a `MutationObserver`: runs the mutation with the given variables and + * resolves with its data. + */ +export type MutateFunction< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = ( + ...rest: MutateFunctionRest +) => Promise + +type WithMutationFunction = Core.Override< + TResult, + { mutate: TMutate } +> + +/** + * The properties shared by every state of a mutation result, like `data`, `error`, `variables`, + * `status`, the `is*` flags, `mutate`, and `reset`. + */ +export type MutationObserverBaseResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = WithMutationFunction< + Core.MutationObserverBaseResult, + MutateFunction +> + +/** + * The result of a `MutationObserver`, and of the hooks built on it like `useMutation`. Narrow it by + * `status` or the `is*` flags to get the type of each state. + */ +export type MutationObserverResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = WithMutationFunction< + Core.MutationObserverResult, + MutateFunction +> + +/** + * A mutation result in the `idle` state: the mutation hasn't run yet, or was reset. + */ +export type MutationObserverIdleResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Extract< + MutationObserverResult, + { status: 'idle' } +> + +/** + * A mutation result in the `pending` state while the mutation runs. + */ +export type MutationObserverLoadingResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Extract< + MutationObserverResult, + { status: 'pending' } +> + +/** + * A mutation result in the `error` state after the mutation failed. + */ +export type MutationObserverErrorResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Extract< + MutationObserverResult, + { status: 'error' } +> + +/** + * A mutation result in the `success` state after the mutation succeeded. + */ +export type MutationObserverSuccessResult< + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, +> = Extract< + MutationObserverResult, + { status: 'success' } +> + +/** The caches and default options to use when creating a pluggable client. */ +export interface QueryClientConfig { + /** The query cache this client is connected to. A new `QueryCache` is created if not provided. */ + queryCache?: QueryCache + /** + * The mutation cache this client is connected to. A new `MutationCache` is created if not + * provided. + */ + mutationCache?: MutationCache + /** Default options for all queries and mutations created through this client. */ + defaultOptions?: DefaultOptions +} + +/** + * The default options of a `QueryClient`, applied to every query (`queries`), mutation + * (`mutations`), `hydrate`, and `dehydrate` call unless overridden. + */ +export interface DefaultOptions { + /** Default options applied to every query, unless overridden per-query. */ + queries?: OmitKeyof< + QueryObserverOptionsBase, + 'suspense' | 'queryKey' + > + /** Default options applied to every mutation, unless overridden per-mutation. */ + mutations?: MutationObserverOptions + /** Default options used when hydrating queries and mutations; see {@link HydrateOptions}. */ + hydrate?: HydrateOptions['defaultOptions'] + /** Default options used when dehydrating the client's caches; see {@link DehydrateOptions}. */ + dehydrate?: DehydrateOptions +} + +/** A raw placeholder value or the callback that supplies it for a query. */ +export type PlaceholderValue = + | NonFunctionGuard + | PlaceholderDataFunction< + NonFunctionGuard, + TError, + NonFunctionGuard, + TQueryKey + > + +type InfiniteQueryFetchPageOptions = Pick< + InfiniteQueryPageParamsOptions, + 'initialPageParam' | 'getNextPageParam' +> & { + /** + * The number of pages to fetch. Defaults to the number of cached pages, + * or one page if the cache has no pages. + */ + pages?: number +} + +// oxlint-disable-next-line typescript/no-unsafe-function-type -- excludes all callable and constructable values +type NonFunctionGuard = T extends Function ? never : T + +export { + dataTagSymbol, + dataTagErrorSymbol, + unsetMarker, +} from '@tanstack/query-core/primitives' + +export type { + OmitKeyof, + DefaultError, + QueryKey, + InferDataFromTag, + InferErrorFromTag, + StaleTime, + CacheKeyConfig, + InfiniteData, + QueryMeta, + InfiniteQueryPageParamsOptions, + WithRequired, + RefetchOptions, + InvalidateOptions, + ResetOptions, + FetchNextPageOptions, + FetchPreviousPageOptions, + QueryObserverBaseResult, + QueryObserverResult, + InfiniteQueryObserverBaseResult, + InfiniteQueryObserverResult, + MutationKey, + MutationMeta, + CancelOptions, + SetDataOptions, +} from '@tanstack/query-core' diff --git a/packages/react-query-pluggable/src/runtime/utils.ts b/packages/react-query-pluggable/src/runtime/utils.ts new file mode 100644 index 00000000000..64bf89b3993 --- /dev/null +++ b/packages/react-query-pluggable/src/runtime/utils.ts @@ -0,0 +1,300 @@ +import { + defaultQueryFn, + hashKeyByOptions, + partialMatchKey, + skipToken, +} from '@tanstack/query-core/primitives' +import { identity } from './identity' +import type * as Core from '@tanstack/query-core' +import type { DefaultQueryFn, SkipToken } from '@tanstack/query-core/primitives' +import type { Mutation } from './mutation' +import type { FetchOptions, Query } from './query' +import type { + CacheKeyConfig, + DefaultError, + MutationKey, + QueryFunction, + QueryKey, +} from './types' + +/** + * Filters used to select queries, for example in `getQueriesData` or `invalidateQueries`. + * All provided filters must match; filters that are left unspecified are ignored. + */ +export interface QueryFilters< + TQueryKey extends QueryKey = QueryKey, +> extends Omit, 'predicate'> { + /** + * Include queries matching this predicate function + */ + predicate?: (query: Query) => boolean +} + +/** + * Filters used to select mutations, for example in `mutationCache.findAll` or `isMutating`. + * All provided filters must match; filters that are left unspecified are ignored. + */ +export interface MutationFilters< + TData = unknown, + TError = DefaultError, + TVariables = unknown, + TOnMutateResult = unknown, +> extends Omit< + Core.MutationFilters, + 'predicate' +> { + /** + * Include mutations matching this predicate function + */ + predicate?: ( + mutation: Mutation, + ) => boolean +} + +/** + * Resolves an option that can be given either as a value or as a function of the query, such as + * `staleTime`. + * @param value - The option value, or a function that receives `query` and returns the value. + * @param query - The query passed to `value` if it is a function. + * @returns The resolved value, or `undefined` if `value` is `undefined`. + */ +export function resolveQueryValue< + TValue, + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + value: + | undefined + | TValue + | ((query: Query) => TValue), + query: Query, +): TValue | undefined { + return typeof value === 'function' + ? ( + value as ( + query: Query, + ) => TValue + )(query) + : value +} + +/** + * Checks whether a query matches the given {@link QueryFilters}. + * Every filter that is specified must match; filters that are left unspecified are ignored. + * @param filters - The filters to check the query against. + * @param query - The query to check. + * @param keyConfig - The cache configuration for key comparison and hashing. + * @returns `true` if the query matches every specified filter. + * @example + * ```ts + * const queryCache = getQueryCache(queryClient) + * + * const matchingQueries = queryCache + * .getAll() + * .filter((query) => matchQuery({ queryKey: ['posts'] }, query)) + * ``` + */ +export function matchQuery( + filters: QueryFilters, + query: Query, + keyConfig?: CacheKeyConfig, +): boolean { + const { + type = 'all', + exact, + fetchStatus, + predicate, + queryKey, + stale, + } = filters + + if (queryKey) { + if (exact) { + if (query.queryHash !== hashKeyByOptions(queryKey, keyConfig)) { + return false + } + } else if ( + !partialMatchKey(query.queryKey, queryKey, keyConfig?.equalityFn) + ) { + return false + } + } + + if (type !== 'all') { + const isActive = query.isActive() + if (type === 'active' && !isActive) { + return false + } + if (type === 'inactive' && isActive) { + return false + } + } + + if (typeof stale === 'boolean' && query.isStale() !== stale) { + return false + } + + if (fetchStatus && fetchStatus !== query.state.fetchStatus) { + return false + } + + if (predicate && !predicate(query)) { + return false + } + + return true +} + +/** + * Checks whether a mutation matches the given {@link MutationFilters}. + * Every filter that is specified must match; filters that are left unspecified are ignored. + * If a `mutationKey` filter is provided but the mutation has no `mutationKey` of its own, it does not match. + * @param filters - The filters to check the mutation against. + * @param mutation - The mutation to check. + * @param keyConfig - The cache configuration for key comparison and hashing. + * @returns `true` if the mutation matches every specified filter. + * @example + * ```ts + * const mutationCache = getMutationCache(queryClient) + * + * const matchingMutations = mutationCache + * .getAll() + * .filter((mutation) => matchMutation({ mutationKey: ['addPost'] }, mutation)) + * ``` + */ +export function matchMutation( + filters: MutationFilters, + mutation: Mutation, + keyConfig?: CacheKeyConfig, +): boolean { + const { exact, status, predicate, mutationKey } = filters + if (mutationKey) { + if (!mutation.options.mutationKey) { + return false + } + if (exact) { + if ( + hashKeyByOptions(mutation.options.mutationKey, keyConfig) !== + hashKeyByOptions(mutationKey, keyConfig) + ) { + return false + } + } else if ( + !partialMatchKey( + mutation.options.mutationKey, + mutationKey, + keyConfig?.equalityFn, + ) + ) { + return false + } + } + + if (status && mutation.state.status !== status) { + return false + } + + if (predicate && !predicate(mutation)) { + return false + } + + return true +} + +/** + * Intended to be passed as a query's `placeholderData` option, for example + * `placeholderData: keepPreviousData`. Instead of resetting the query's data to `undefined` while a new + * query key is fetching, it keeps displaying the previously fetched data until the new data arrives. + * @param previousData - The data of the previous query key, passed by the observer. + * @returns The previous data, unchanged. + * @example + * ```ts + * new QueryObserver(queryClient, { + * queryKey: ['posts', page], + * queryFn: () => fetchPosts(page), + * placeholderData: keepPreviousData, + * }) + * ``` + */ +export const keepPreviousData: ( + previousData: T | undefined, +) => T | undefined = identity + +/** + * Returns the function to call for a fetch. If there is no `queryFn` but the fetch was started from + * an `initialPromise`, that promise is returned instead. If there is no usable `queryFn`, the returned + * function rejects with a `Missing queryFn` error. + * @param options - The query options with the `queryFn`, and the `queryHash` used in error messages. + * @param fetchOptions - The fetch options, which may carry an `initialPromise`. + * @returns The function to call for the fetch. + */ +export function ensureQueryFn< + TQueryFnData = unknown, + TQueryKey extends QueryKey = QueryKey, +>( + options: { + queryFn?: + | QueryFunction + | SkipToken + | DefaultQueryFn + queryHash?: string + }, + fetchOptions?: FetchOptions, +): QueryFunction { + if (process.env.NODE_ENV !== 'production') { + if (options.queryFn === skipToken) { + console.error( + `Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${options.queryHash}'`, + ) + } + } + + // if we attempt to retry a fetch that was triggered from an initialPromise + // when we don't have a queryFn yet, we can't retry, so we just return the already rejected initialPromise + // if an observer has already mounted, we will be able to retry with that queryFn + if (!options.queryFn && fetchOptions?.initialPromise) { + return () => fetchOptions.initialPromise! + } + + if ( + !options.queryFn || + options.queryFn === skipToken || + options.queryFn === defaultQueryFn + ) { + return () => + Promise.reject(new Error(`Missing queryFn: '${options.queryHash}'`)) + } + + return options.queryFn +} + +export { + addConsumeAwareSignal, + addToArray, + defaultQueryFn, + fetchSignal, + functionalUpdate, + hashKey, + hashKeyByOptions, + isPlainArray, + isPlainObject, + isValidTimeout, + noop, + partialMatchKey, + replaceData, + replaceEqualDeep, + shallowEqualObjects, + shouldThrowError, + skipToken, + sleep, + timeUntilStale, +} from '@tanstack/query-core/primitives' +export type { + DefaultQueryFn, + FetchSignalContext, + QueryTypeFilter, + SkipToken, + Updater, +} from '@tanstack/query-core/primitives' diff --git a/packages/react-query-no-core/src/suspense.ts b/packages/react-query-pluggable/src/suspense.ts similarity index 96% rename from packages/react-query-no-core/src/suspense.ts rename to packages/react-query-pluggable/src/suspense.ts index 09ff0957953..e2d79baf4c6 100644 --- a/packages/react-query-no-core/src/suspense.ts +++ b/packages/react-query-pluggable/src/suspense.ts @@ -1,10 +1,11 @@ import { use } from 'react' +import { getQueryCache } from './runtime/queryClient' import { QueryObserver } from './runtime/queryObserver' import type { DefaultError, QueryKey, QueryObserverResult, -} from '@tanstack/query-types/bindings' +} from '@tanstack/query-core' import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' import type { Query } from './runtime/query' import type { QueryClient } from './runtime/queryClient' @@ -145,7 +146,7 @@ const useReadSuspenseQuery = ( if (!defaultedOptions.suspense) return const snapshot = reader.getSnapshot() - const query = client.getQueryCache().build(client, defaultedOptions) + const query = getQueryCache(client).build(client, defaultedOptions) const suspend = shouldSuspend(snapshot, errorResetBoundary, query) if (suspend === undefined) return @@ -181,7 +182,7 @@ const useReadSuspenseQueries = ( return undefined } - const query = client.getQueryCache().build(client, opts) + const query = getQueryCache(client).build(client, opts) const suspend = shouldSuspend(result, errorResetBoundary, query) if (suspend === undefined) { diff --git a/packages/react-query-pluggable/src/suspenseQuery.ts b/packages/react-query-pluggable/src/suspenseQuery.ts new file mode 100644 index 00000000000..c9e33daff0f --- /dev/null +++ b/packages/react-query-pluggable/src/suspenseQuery.ts @@ -0,0 +1,87 @@ +import { skipToken } from '@tanstack/query-core/primitives' +import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' +import type { DefaultError, QueryKey, SkipToken } from '@tanstack/query-core' +import type { InfiniteQueryMode } from './infiniteQuery' +import type { UseSuspenseQueryOptions } from './types' +import type { SkippableSuspenseQueryOptions } from './useSuspenseQuery' + +/** The render policy attached to options prepared with `suspenseQuery`. */ +export interface SuspenseQueryMode { + /** Skipping the query disables its Suspense policy for this render. */ + readonly renderPolicy: TSkippable extends true + ? typeof suspenseQueryPolicy | undefined + : typeof suspenseQueryPolicy +} + +/** Options that make a single enabled query read through React Suspense. */ +export type SuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, +> = UseSuspenseQueryOptions & + SuspenseQueryMode + +/** + * Applies the Suspense render policy to a paginated query. + * @param options - An infinite query prepared with `infiniteQuery`. + * @returns The same paginated options with the policy for a running or skipped query. + */ +export function suspenseQuery< + TOptions extends InfiniteQueryMode & { queryFn?: unknown }, +>( + options: TOptions, +): TOptions & + SuspenseQueryMode + +/** + * Lets `useQuery` suspend while fetching a query without data. A failed query + * without data throws to the nearest error boundary. An observer can reuse + * data already cached by a regular query with the same key. + * @param options - Query options. The Suspense policy controls enabled and throwOnError. + * @returns Options for `useQuery`. A running query returns defined data. + */ +export function suspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: UseSuspenseQueryOptions, +): SuspenseQueryOptions + +/** + * Supports a query function that may be `skipToken`. + * @param options - Passing `skipToken` keeps the observer disabled. + * @returns Options for `useQuery`. A skipped query can return undefined data. + */ +export function suspenseQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: SkippableSuspenseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryKey + >, +): SkippableSuspenseQueryOptions & + SuspenseQueryMode + +export function suspenseQuery( + options: TOptions, +): TOptions & { + readonly renderPolicy: typeof suspenseQueryPolicy | undefined + enabled?: boolean + throwOnError?: typeof defaultThrowOnError +} { + const enabled = options.queryFn !== skipToken + return { + ...options, + enabled, + throwOnError: defaultThrowOnError, + renderPolicy: enabled ? suspenseQueryPolicy : undefined, + } +} diff --git a/packages/react-query-no-core-pluggable/src/types.ts b/packages/react-query-pluggable/src/types.ts similarity index 98% rename from packages/react-query-no-core-pluggable/src/types.ts rename to packages/react-query-pluggable/src/types.ts index cd45fee106b..c1a2e18a0ce 100644 --- a/packages/react-query-no-core-pluggable/src/types.ts +++ b/packages/react-query-pluggable/src/types.ts @@ -1,5 +1,3 @@ -/* istanbul ignore file */ - import type { DefaultError, DefinedInfiniteQueryObserverResult, @@ -13,8 +11,8 @@ import type { QueryKey, QueryObserverPlaceholderResult, QueryObserverResult, - SkipToken, -} from '@tanstack/query-types/bindings' +} from '@tanstack/query-core' +import type { SkipToken } from '@tanstack/query-core/primitives' import type { InfiniteQueryExecuteOptions, InfiniteQueryObserverOptions, @@ -68,7 +66,7 @@ export interface UseBaseQueryOptions< } /** - * The options accepted by `usePrefetchQuery` — everything you can pass to `queryClient.query`, with a + * The options accepted by `usePrefetchQuery` — everything you can pass to `fetchQuery`, with a * required `queryFn`. Pass `defaultQueryFn` to use the client defaults. * @template TQueryFnData - The type your `queryFn` resolves to. * @template TError - The type of errors your `queryFn` may throw. @@ -104,7 +102,7 @@ export type UsePrefetchQueryOptions< } /** - * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `infiniteQuery(client, options)`, + * The options accepted by `usePrefetchInfiniteQuery` — everything you can pass to `fetchInfiniteQuery(client, options)`, * with a required `queryFn`. Pass `defaultQueryFn` to use the client defaults. * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. * @template TError - The type of errors your `queryFn` may throw. diff --git a/packages/react-query-no-core-pluggable/src/useBaseQuery.ts b/packages/react-query-pluggable/src/useBaseQuery.ts similarity index 84% rename from packages/react-query-no-core-pluggable/src/useBaseQuery.ts rename to packages/react-query-pluggable/src/useBaseQuery.ts index 7216bf66c41..ed6254e6fb1 100644 --- a/packages/react-query-no-core-pluggable/src/useBaseQuery.ts +++ b/packages/react-query-pluggable/src/useBaseQuery.ts @@ -8,11 +8,9 @@ import { getHasError, useClearResetErrorBoundary, } from './errorBoundaryUtils' +import { defaultQueryOptions, getQueryCache } from './runtime/queryClient' import { useObserverSnapshot } from './useObserverSnapshot' -import type { - QueryKey, - QueryObserverResult, -} from '@tanstack/query-types/bindings' +import type { QueryKey, QueryObserverResult } from '@tanstack/query-core' import type { QueryClient } from './runtime/queryClient' import type { QueryObserver } from './runtime/queryObserver' import type { suspenseQueryPolicy } from './suspense' @@ -61,16 +59,17 @@ export function useBaseQuery< const isRestoring = useIsRestoring() const errorResetBoundary = useQueryErrorResetBoundary() const client = useQueryClient(queryClient) - const defaultedOptions = client.defaultQueryOptions({ + const defaultedOptions = defaultQueryOptions(client, { ...options, suspense: !!suspense, }) - const query = client - .getQueryCache() - .get( - defaultedOptions.queryHash, - ) + const query = getQueryCache(client).get< + TQueryFnData, + TError, + TQueryData, + TQueryKey + >(defaultedOptions.queryHash) if (process.env.NODE_ENV !== 'production') { if (!defaultedOptions.queryFn) { @@ -93,13 +92,21 @@ export function useBaseQuery< ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query) useClearResetErrorBoundary(errorResetBoundary) - const [observer] = React.useState( - () => - new Observer( - client, - defaultedOptions, - ), - ) + const createObserver = () => ({ + client, + Observer, + observer: new Observer( + client, + defaultedOptions, + ), + }) + const [saved, setSaved] = React.useState(createObserver) + let current = saved + if (current.Observer !== Observer || current.client !== client) { + current = createObserver() + setSaved(current) + } + const { observer } = current const reader = observer.createResultReader(defaultedOptions) diff --git a/packages/react-query-no-core/src/useInfiniteQuery.ts b/packages/react-query-pluggable/src/useInfiniteQuery.ts similarity index 92% rename from packages/react-query-no-core/src/useInfiniteQuery.ts rename to packages/react-query-pluggable/src/useInfiniteQuery.ts index 356af76465e..3b2882b95e4 100644 --- a/packages/react-query-no-core/src/useInfiniteQuery.ts +++ b/packages/react-query-pluggable/src/useInfiniteQuery.ts @@ -1,17 +1,13 @@ 'use client' -import { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' -import { useBaseQuery } from './useBaseQuery' -import type { - DefaultError, - InfiniteData, - QueryKey, -} from '@tanstack/query-types/bindings' + +import { infiniteQuery } from './infiniteQuery' +import { useQuery } from './useQuery' +import type { DefaultError, InfiniteData, QueryKey } from '@tanstack/query-core' import type { DefinedInitialDataInfiniteOptions, UndefinedInitialDataInfiniteOptions, } from './infiniteQueryOptions' import type { QueryClient } from './runtime/queryClient' -import type { QueryObserver } from './runtime/queryObserver' import type { DefinedUseInfiniteQueryResult, UseInfiniteQueryOptions, @@ -33,10 +29,10 @@ import type { * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `fetchInfiniteQuery(client, options)`. * @example * ```tsx - * import { useInfiniteQuery } from '@tanstack/react-query-no-core' + * import { useInfiniteQuery } from '@tanstack/react-query-pluggable' * * function Projects() { * // `data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the @@ -90,11 +86,11 @@ export function useInfiniteQuery< * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `fetchInfiniteQuery(client, options)`. * @example * Fetching the next page from a "Load More" button click: * ```tsx - * import { useInfiniteQuery } from '@tanstack/react-query-no-core' + * import { useInfiniteQuery } from '@tanstack/react-query-pluggable' * * function Projects() { * const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = @@ -133,7 +129,7 @@ export function useInfiniteQuery< * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a * sentinel element after the list: * ```tsx - * import { useInfiniteQuery } from '@tanstack/react-query-no-core' + * import { useInfiniteQuery } from '@tanstack/react-query-pluggable' * import { useEffect, useRef } from 'react' * * function Projects() { @@ -213,11 +209,11 @@ export function useInfiniteQuery< * @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default * refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user * actions, or add conditions like `hasNextPage && !isFetching`. - * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`. + * @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `fetchInfiniteQuery(client, options)`. * @example * Fetching the next page from a "Load More" button click: * ```tsx - * import { useInfiniteQuery } from '@tanstack/react-query-no-core' + * import { useInfiniteQuery } from '@tanstack/react-query-pluggable' * * function Projects() { * const { data, isPending, isError, error, fetchNextPage, hasNextPage, isFetching, isFetchingNextPage } = @@ -256,7 +252,7 @@ export function useInfiniteQuery< * Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a * sentinel element after the list: * ```tsx - * import { useInfiniteQuery } from '@tanstack/react-query-no-core' + * import { useInfiniteQuery } from '@tanstack/react-query-pluggable' * import { useEffect, useRef } from 'react' * * function Projects() { @@ -309,7 +305,7 @@ export function useInfiniteQuery< * A query that's disabled, type safe, until `postId` is set — pass `skipToken` as `queryFn` * instead of setting `enabled: false`: * ```tsx - * import { skipToken, useInfiniteQuery } from '@tanstack/react-query-no-core' + * import { skipToken, useInfiniteQuery } from '@tanstack/react-query-pluggable' * * function Comments({ postId }: { postId: string | undefined }) { * // Use `isLoading`, not `isPending`, so the loading state doesn't show while the query is disabled. @@ -356,9 +352,5 @@ export function useInfiniteQuery( options: UseInfiniteQueryOptions, queryClient?: QueryClient, ) { - return useBaseQuery( - options, - InfiniteQueryObserver as typeof QueryObserver, - queryClient, - ) + return useQuery(infiniteQuery(options), queryClient) } diff --git a/packages/react-query-no-core/src/useIsFetching.ts b/packages/react-query-pluggable/src/useIsFetching.ts similarity index 84% rename from packages/react-query-no-core/src/useIsFetching.ts rename to packages/react-query-pluggable/src/useIsFetching.ts index f80652f8b2e..bd98c21423f 100644 --- a/packages/react-query-no-core/src/useIsFetching.ts +++ b/packages/react-query-pluggable/src/useIsFetching.ts @@ -2,6 +2,7 @@ import * as React from 'react' import { useQueryClient } from './QueryClientProvider' import { notifyManager } from './runtime/notifyManager' +import { getQueryCache, isFetching } from './runtime/queryClient' import type { QueryClient } from './runtime/queryClient' import type { QueryFilters } from './runtime/utils' @@ -15,7 +16,7 @@ import type { QueryFilters } from './runtime/utils' * background. * @example * ```tsx - * import { useIsFetching } from '@tanstack/react-query-no-core' + * import { useIsFetching } from '@tanstack/react-query-pluggable' * * function PostsFetchingIndicator() { * // How many queries matching the posts prefix are fetching? @@ -27,7 +28,7 @@ import type { QueryFilters } from './runtime/utils' * @example * A global loading indicator for any query fetching in the background, not just the ones on screen: * ```tsx - * import { useIsFetching } from '@tanstack/react-query-no-core' + * import { useIsFetching } from '@tanstack/react-query-pluggable' * * function GlobalLoadingIndicator() { * const isFetching = useIsFetching() @@ -43,7 +44,7 @@ export function useIsFetching( queryClient?: QueryClient, ): number { const client = useQueryClient(queryClient) - const queryCache = client.getQueryCache() + const queryCache = getQueryCache(client) return React.useSyncExternalStore( React.useCallback( @@ -51,7 +52,7 @@ export function useIsFetching( queryCache.subscribe(notifyManager.batchCalls(onStoreChange)), [queryCache], ), - () => client.isFetching(filters), - () => client.isFetching(filters), + () => isFetching(client, filters), + () => isFetching(client, filters), ) } diff --git a/packages/react-query-no-core/src/useMutation.ts b/packages/react-query-pluggable/src/useMutation.ts similarity index 82% rename from packages/react-query-no-core/src/useMutation.ts rename to packages/react-query-pluggable/src/useMutation.ts index e14c686c472..7e15fcc17f9 100644 --- a/packages/react-query-no-core/src/useMutation.ts +++ b/packages/react-query-pluggable/src/useMutation.ts @@ -1,10 +1,11 @@ 'use client' + +import { noop, shouldThrowError } from '@tanstack/query-core/primitives' import * as React from 'react' import { useQueryClient } from './QueryClientProvider' import { MutationObserver } from './runtime/mutationObserver' import { notifyManager } from './runtime/notifyManager' -import { noop, shouldThrowError } from './runtime/utils' -import type { DefaultError } from '@tanstack/query-types/bindings' +import type { DefaultError } from '@tanstack/query-core' import type { QueryClient } from './runtime/queryClient' import type { UseMutateFunction, @@ -31,14 +32,14 @@ import type { * the mutation up elsewhere via its `mutationKey` (e.g. with `useMutationState`). * @example * ```tsx - * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core' + * import { useMutation, useQueryClient, invalidateQueries } from '@tanstack/react-query-pluggable' * * function AddTodo() { * const queryClient = useQueryClient() * * const addMutation = useMutation({ * mutationFn: addTodo, - * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + * onSuccess: () => invalidateQueries(queryClient, { queryKey: ['todos'] }), * }) * * return ( @@ -57,14 +58,14 @@ import type { * @example * Rendering the mutation's own state, rather than just firing it off: * ```tsx - * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core' + * import { useMutation, useQueryClient, invalidateQueries } from '@tanstack/react-query-pluggable' * * function AddTodo() { * const queryClient = useQueryClient() * * const addMutation = useMutation({ * mutationFn: addTodo, - * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + * onSuccess: () => invalidateQueries(queryClient, { queryKey: ['todos'] }), * }) * * return ( @@ -86,7 +87,7 @@ import type { * @example * Optimistic update via `onMutate`, rolling back on `onError`: * ```tsx - * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core' + * import { useMutation, useQueryClient, cancelQueries, getQueryData, setQueryData, invalidateQueries } from '@tanstack/react-query-pluggable' * * function AddTodo() { * const queryClient = useQueryClient() @@ -94,10 +95,10 @@ import type { * const addMutation = useMutation({ * mutationFn: addTodo, * onMutate: async (newTodo) => { - * await queryClient.cancelQueries({ queryKey: ['todos'] }) - * const previousTodos = queryClient.getQueryData>(['todos']) + * await cancelQueries(queryClient, { queryKey: ['todos'] }) + * const previousTodos = getQueryData(queryClient, ['todos']) * - * queryClient.setQueryData>(['todos'], (old) => [ + * setQueryData(queryClient, ['todos'], (old) => [ * ...(old ?? []), * newTodo, * ]) @@ -106,10 +107,10 @@ import type { * return { previousTodos } * }, * onError: (_err, _newTodo, onMutateResult) => { - * queryClient.setQueryData(['todos'], onMutateResult?.previousTodos) + * setQueryData(queryClient, ['todos'], onMutateResult?.previousTodos) * }, * onSettled: () => { - * queryClient.invalidateQueries({ queryKey: ['todos'] }) + * invalidateQueries(queryClient, { queryKey: ['todos'] }) * }, * }) * @@ -122,14 +123,14 @@ import type { * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a * promise per call instead, so you can wait for all of them when they succeed: * ```tsx - * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core' + * import { useMutation, useQueryClient, invalidateQueries } from '@tanstack/react-query-pluggable' * * function AddTodos() { * const queryClient = useQueryClient() * * const addMutation = useMutation({ * mutationFn: addTodo, - * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + * onSuccess: () => invalidateQueries(queryClient, { queryKey: ['todos'] }), * }) * * async function handleAddAll(todos: Array) { @@ -152,14 +153,14 @@ import type { * did — rather than losing that information the moment the first one rejects — swap `Promise.all` for * `Promise.allSettled`: * ```tsx - * import { useMutation, useQueryClient } from '@tanstack/react-query-no-core' + * import { useMutation, useQueryClient, invalidateQueries } from '@tanstack/react-query-pluggable' * * function AddTodos() { * const queryClient = useQueryClient() * * const addMutation = useMutation({ * mutationFn: addTodo, - * onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), + * onSuccess: () => invalidateQueries(queryClient, { queryKey: ['todos'] }), * }) * * async function handleAddAll(todos: Array) { diff --git a/packages/react-query-no-core-pluggable/src/useMutationState.ts b/packages/react-query-pluggable/src/useMutationState.ts similarity index 94% rename from packages/react-query-no-core-pluggable/src/useMutationState.ts rename to packages/react-query-pluggable/src/useMutationState.ts index fa732480865..f5f06adfe8b 100644 --- a/packages/react-query-no-core-pluggable/src/useMutationState.ts +++ b/packages/react-query-pluggable/src/useMutationState.ts @@ -1,10 +1,11 @@ 'use client' + +import { replaceEqualDeep } from '@tanstack/query-core/primitives' import * as React from 'react' import { useQueryClient } from './QueryClientProvider' import { getMutationCache } from './runtime/mutationCache' import { notifyManager } from './runtime/notifyManager' -import { replaceEqualDeep } from './runtime/utils' -import type { MutationState } from '@tanstack/query-types/bindings' +import type { MutationState } from '@tanstack/query-core' import type { Mutation } from './runtime/mutation' import type { MutationCache } from './runtime/mutationCache' import type { QueryClient } from './runtime/queryClient' @@ -19,7 +20,7 @@ import type { MutationFilters } from './runtime/utils' * @returns Will be the `number` of the mutations that your application currently has `pending`. * @example * ```tsx - * import { useIsMutating } from '@tanstack/react-query-no-core-pluggable' + * import { useIsMutating } from '@tanstack/react-query-pluggable' * * function PostsMutatingIndicator() { * // How many mutations matching the posts prefix are in progress? @@ -122,7 +123,7 @@ function createSnapshotFactory< * @example * Get all variables of all running mutations: * ```tsx - * import { useMutationState } from '@tanstack/react-query-no-core-pluggable' + * import { useMutationState } from '@tanstack/react-query-pluggable' * * function PendingPosts() { * const pendingVariables = useMutationState({ @@ -136,7 +137,7 @@ function createSnapshotFactory< * @example * Get all data for specific mutations via the `mutationKey`: * ```tsx - * import { useMutation, useMutationState } from '@tanstack/react-query-no-core-pluggable' + * import { useMutation, useMutationState } from '@tanstack/react-query-pluggable' * * const mutationKey = ['posts'] * @@ -165,7 +166,7 @@ function createSnapshotFactory< * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the * last item that `useMutationState` returns to get the latest successful invocation: * ```tsx - * import { useMutationState } from '@tanstack/react-query-no-core-pluggable' + * import { useMutationState } from '@tanstack/react-query-pluggable' * * function LatestPost() { * const savedPosts = useMutationState({ diff --git a/packages/react-query-no-core-pluggable/src/useObserverSnapshot.ts b/packages/react-query-pluggable/src/useObserverSnapshot.ts similarity index 95% rename from packages/react-query-no-core-pluggable/src/useObserverSnapshot.ts rename to packages/react-query-pluggable/src/useObserverSnapshot.ts index b02245410f1..216594a18cc 100644 --- a/packages/react-query-no-core-pluggable/src/useObserverSnapshot.ts +++ b/packages/react-query-pluggable/src/useObserverSnapshot.ts @@ -1,7 +1,7 @@ 'use client' +import { noop } from '@tanstack/query-core/primitives' import * as React from 'react' import { notifyManager } from './runtime/notifyManager' -import { noop } from './runtime/utils' import type { QueryObserverResultReader } from './runtime/queryObserver' interface ObserverStore { diff --git a/packages/react-query-no-core-pluggable/src/usePrefetchInfiniteQuery.tsx b/packages/react-query-pluggable/src/usePrefetchInfiniteQuery.tsx similarity index 82% rename from packages/react-query-no-core-pluggable/src/usePrefetchInfiniteQuery.tsx rename to packages/react-query-pluggable/src/usePrefetchInfiniteQuery.tsx index 0637ec05b99..05d833a7346 100644 --- a/packages/react-query-no-core-pluggable/src/usePrefetchInfiniteQuery.tsx +++ b/packages/react-query-pluggable/src/usePrefetchInfiniteQuery.tsx @@ -1,18 +1,15 @@ +import { noop } from '@tanstack/query-core/primitives' import { useQueryClient } from './QueryClientProvider' -import { infiniteQuery } from './runtime/infiniteQuery' -import { noop } from './runtime/utils' -import type { - DefaultError, - InfiniteData, - QueryKey, -} from '@tanstack/query-types/bindings' +import { fetchInfiniteQuery } from './runtime/fetchInfiniteQuery' +import { getQueryState } from './runtime/queryClient' +import type { DefaultError, InfiniteData, QueryKey } from '@tanstack/query-core' import type { QueryClient } from './runtime/queryClient' import type { UsePrefetchInfiniteQueryOptions } from './types' /** * `usePrefetchInfiniteQuery` does not return anything, it should be used just to fire a prefetch during render, * before a suspense boundary that wraps a component that uses `useSuspenseInfiniteQuery`. You can pass - * everything to `usePrefetchInfiniteQuery` that you can pass to `infiniteQuery(client, options)`, though + * everything to `usePrefetchInfiniteQuery` that you can pass to `fetchInfiniteQuery(client, options)`, though * `queryKey`, `initialPageParam`, and `getNextPageParam` are always required, and `queryFn` is required. Pass `defaultQueryFn` to use the client defaults. * * `getNextPageParam` receives both the last page of the infinite list of data and the full array of all pages, @@ -22,13 +19,13 @@ import type { UsePrefetchInfiniteQueryOptions } from './types' * The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left * over from a previous attempt — so calling this on every render is cheap and won't refetch data that's * already there or already in flight. - * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `infiniteQuery(client, options)`. + * @param options - The {@link UsePrefetchInfiniteQueryOptions} to use — everything you can pass to `fetchInfiniteQuery(client, options)`. * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will * be used. * @example * ```tsx * import { Suspense } from 'react' - * import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/react-query-no-core-pluggable' + * import { infiniteQueryOptions, usePrefetchInfiniteQuery } from '@tanstack/react-query-pluggable' * * const projectsOptions = infiniteQueryOptions({ * queryKey: ['projects'], @@ -67,7 +64,7 @@ export function usePrefetchInfiniteQuery< ): void { const client = useQueryClient(queryClient) - if (!client.getQueryState(options.queryKey)) { - void infiniteQuery(client, options).catch(noop) + if (!getQueryState(client, options.queryKey)) { + void fetchInfiniteQuery(client, options).catch(noop) } } diff --git a/packages/react-query-no-core/src/usePrefetchQuery.tsx b/packages/react-query-pluggable/src/usePrefetchQuery.tsx similarity index 77% rename from packages/react-query-no-core/src/usePrefetchQuery.tsx rename to packages/react-query-pluggable/src/usePrefetchQuery.tsx index 7d98c66fc34..43eca68bb73 100644 --- a/packages/react-query-no-core/src/usePrefetchQuery.tsx +++ b/packages/react-query-pluggable/src/usePrefetchQuery.tsx @@ -1,25 +1,26 @@ +import { noop } from '@tanstack/query-core/primitives' import { useQueryClient } from './QueryClientProvider' -import { noop } from './runtime/utils' -import type { DefaultError, QueryKey } from '@tanstack/query-types/bindings' +import { fetchQuery, getQueryState } from './runtime/queryClient' +import type { DefaultError, QueryKey } from '@tanstack/query-core' import type { QueryClient } from './runtime/queryClient' import type { UsePrefetchQueryOptions } from './types' /** * `usePrefetchQuery` does not return anything, it should be used just to fire a prefetch during render, before * a suspense boundary that wraps a component that uses `useSuspenseQuery`. You can pass everything to - * `usePrefetchQuery` that you can pass to `queryClient.query`, though `queryKey` is always required, and + * `usePrefetchQuery` that you can pass to `fetchQuery`, though `queryKey` is always required, and * `queryFn` is required. Pass `defaultQueryFn` to use the client defaults. * * The prefetch is skipped if the query already has any cached state — including a `pending`/`error` state left * over from a previous attempt — so calling this on every render is cheap and won't refetch data that's * already there or already in flight. - * @param options - The {@link UsePrefetchQueryOptions} to use — everything you can pass to `queryClient.query`. + * @param options - The {@link UsePrefetchQueryOptions} to use — everything you can pass to `fetchQuery`. * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will * be used. * @example * ```tsx * import { Suspense } from 'react' - * import { usePrefetchQuery } from '@tanstack/react-query-no-core' + * import { usePrefetchQuery } from '@tanstack/react-query-pluggable' * * function App() { * // Fire the prefetch during render, before the suspense boundary below. @@ -54,7 +55,7 @@ export function usePrefetchQuery< ): void { const client = useQueryClient(queryClient) - if (!client.getQueryState(options.queryKey)) { - void client.query(options).catch(noop) + if (!getQueryState(client, options.queryKey)) { + void fetchQuery(client, options).catch(noop) } } diff --git a/packages/react-query-no-core-pluggable/src/useQueries.ts b/packages/react-query-pluggable/src/useQueries.ts similarity index 97% rename from packages/react-query-no-core-pluggable/src/useQueries.ts rename to packages/react-query-pluggable/src/useQueries.ts index 8c74bf2909e..0d437e0dd14 100644 --- a/packages/react-query-no-core-pluggable/src/useQueries.ts +++ b/packages/react-query-pluggable/src/useQueries.ts @@ -9,6 +9,7 @@ import { useClearResetErrorBoundary, } from './errorBoundaryUtils' import { QueriesObserver } from './runtime/queriesObserver' +import { defaultQueryOptions, getQueryCache } from './runtime/queryClient' import { useObserverSnapshot } from './useObserverSnapshot' import type { DefaultError, @@ -16,7 +17,7 @@ import type { QueriesObserverOptions, QueriesPlaceholderDataFunction, QueryKey, -} from '@tanstack/query-types/bindings' +} from '@tanstack/query-core' import type { placeholderData } from './runtime/placeholderData' import type { Select } from './runtime/projectionTypes' import type { QueryClient } from './runtime/queryClient' @@ -281,7 +282,7 @@ type UseQueriesInput, TCombinedResult> = { * previously rendered queries, because the number of queries can differ between renders. * @example * ```tsx - * import { useQueries } from '@tanstack/react-query-no-core-pluggable' + * import { useQueries } from '@tanstack/react-query-pluggable' * * function Posts({ ids }: { ids: Array }) { * const postQueries = useQueries({ @@ -306,7 +307,7 @@ type UseQueriesInput, TCombinedResult> = { * @example * Combining results into a single value: * ```tsx - * import { useQueries } from '@tanstack/react-query-no-core-pluggable' + * import { useQueries } from '@tanstack/react-query-pluggable' * * function Posts({ ids }: { ids: Array }) { * const { data, isPending, isError } = useQueries({ @@ -340,7 +341,7 @@ type UseQueriesInput, TCombinedResult> = { * `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is * resolved before it reaches `useQueries`: * ```tsx - * import { queryOptions, select, useQueries } from '@tanstack/react-query-no-core-pluggable' + * import { queryOptions, select, useQueries } from '@tanstack/react-query-pluggable' * * const postOptions = (id: number) => * queryOptions({ @@ -408,7 +409,7 @@ export function useBaseQueries< const defaultedQueries = React.useMemo( () => queries.map((opts) => { - const defaultedOptions = client.defaultQueryOptions({ + const defaultedOptions = defaultQueryOptions(client, { ...opts, suspense: !!suspense, } as QueryObserverOptions) @@ -427,7 +428,7 @@ export function useBaseQueries< defaultedQueries.forEach((queryOptions) => { suspense?.prepare(queryOptions) - const query = client.getQueryCache().get(queryOptions.queryHash) + const query = getQueryCache(client).get(queryOptions.queryHash) ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query) }) @@ -463,7 +464,7 @@ export function useBaseQueries< result, errorResetBoundary, throwOnError: query.throwOnError, - query: client.getQueryCache().get(query.queryHash), + query: getQueryCache(client).get(query.queryHash), suspense: query.suspense, }) ) diff --git a/packages/react-query-no-core-pluggable/src/useQuery.ts b/packages/react-query-pluggable/src/useQuery.ts similarity index 71% rename from packages/react-query-no-core-pluggable/src/useQuery.ts rename to packages/react-query-pluggable/src/useQuery.ts index 59896724e2e..fd5d5fd0292 100644 --- a/packages/react-query-no-core-pluggable/src/useQuery.ts +++ b/packages/react-query-pluggable/src/useQuery.ts @@ -1,18 +1,97 @@ 'use client' + import { QueryObserver } from './runtime/queryObserver' import { useBaseQuery } from './useBaseQuery' -import type { DefaultError, QueryKey } from '@tanstack/query-types/bindings' +import type { + AnyDataTag, + DefaultError, + InfiniteData, + QueryKey, +} from '@tanstack/query-core' +import type { InfiniteQueryMode } from './infiniteQuery' import type { DefinedInitialDataOptions, UndefinedInitialDataOptions, } from './queryOptions' import type { QueryClient } from './runtime/queryClient' +import type { suspenseQueryPolicy } from './suspense' +import type { SuspenseQueryOptions } from './suspenseQuery' import type { + AnyUseInfiniteQueryOptions, + AnyUseQueryOptions, + DefinedUseInfiniteQueryResult, DefinedUseQueryResult, + UseInfiniteQueryOptions, + UseInfiniteQueryResult, UseQueryOptions, UseQueryResult, + UseSuspenseInfiniteQueryResult, + UseSuspenseQueryResult, } from './types' +type PreparedQuery = + | (AnyUseQueryOptions & { queryKey: AnyDataTag; getNextPageParam?: never }) + | (AnyUseInfiniteQueryOptions & InfiniteQueryMode) + +type HasInitialData = T extends { + initialData: TQueryData | (() => TQueryData) +} + ? true + : false + +type PreparedQueryResult = T extends InfiniteQueryMode & + UseInfiniteQueryOptions< + infer TPage, + infer TError, + infer TData, + any, + infer TPageParam + > + ? T extends { renderPolicy: typeof suspenseQueryPolicy } + ? UseSuspenseInfiniteQueryResult + : HasInitialData> extends true + ? DefinedUseInfiniteQueryResult + : UseInfiniteQueryResult + : T extends UseQueryOptions< + infer TQueryFnData, + infer TError, + infer TData, + any + > + ? T extends { renderPolicy: typeof suspenseQueryPolicy } + ? UseSuspenseQueryResult + : HasInitialData> extends true + ? DefinedUseQueryResult + : UseQueryResult + : never + +/** + * Reads prepared regular or paginated options, including a choice between them. + * @param options - Query options prepared for the selected observer and render policy. + * @param queryClient - The client to use. Defaults to the nearest provider. + * @returns The result for the selected query, including pagination controls for infinite queries. + */ +export function useQuery( + options: T, + queryClient?: QueryClient, +): PreparedQueryResult + +/** + * Reads a query using the render policy supplied by `suspenseQuery`. + * @param options - Options returned by `suspenseQuery` for a running query. + * @param queryClient - Defaults to the nearest provider's client. + * @returns The result with defined data when the component can render. + */ +export function useQuery< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +>( + options: SuspenseQueryOptions, + queryClient?: QueryClient, +): UseSuspenseQueryResult + /** * This overload is selected when `initialData` is known to be defined, so the resulting `data` is typed as never * `undefined` (unless a `select` changes `TData` to include `undefined`). At runtime, `data` is still `undefined` @@ -24,10 +103,10 @@ import type { * resolves to `pending` in this overload's type, since `initialData` guarantees data upfront). `status` is * `error` if the query has an error from a fetch that failed after its retries or if `select` threw, and * `success` otherwise. `isSuccess`/`isError` are derived booleans for convenience. - * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`. + * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `fetchQuery`. * @example * ```tsx - * import { useQuery } from '@tanstack/react-query-no-core-pluggable' + * import { useQuery } from '@tanstack/react-query-pluggable' * * function Posts() { * // `data` is `Post[]`, never `undefined`, thanks to `initialData` — even if a refetch fails, @@ -69,10 +148,10 @@ export function useQuery< * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError` * are derived booleans for convenience. - * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`. + * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `fetchQuery`. * @example * ```tsx - * import { useQuery } from '@tanstack/react-query-no-core-pluggable' + * import { useQuery } from '@tanstack/react-query-pluggable' * * function Posts() { * const { status, data, error, isFetching } = useQuery({ @@ -98,7 +177,7 @@ export function useQuery< * @example * The same query, checking `isPending`/`isError` instead of `status` — pick whichever reads better to you: * ```tsx - * import { useQuery } from '@tanstack/react-query-no-core-pluggable' + * import { useQuery } from '@tanstack/react-query-pluggable' * * function Posts() { * const { isPending, isError, data, error } = useQuery({ @@ -138,10 +217,10 @@ export function useQuery< * after its retries or if `select` threw, `success` if the query has cached data (even if `select` returns * `undefined`) or data from `placeholderData`, and `pending` otherwise. `isPending`/`isSuccess`/`isError` * are derived booleans for convenience. - * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`. + * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `fetchQuery`. * @example * ```tsx - * import { useQuery } from '@tanstack/react-query-no-core-pluggable' + * import { useQuery } from '@tanstack/react-query-pluggable' * * function Posts() { * const { status, data, error, isFetching } = useQuery({ @@ -168,7 +247,7 @@ export function useQuery< * `select` derives whatever `data` a component needs from the cached value, without changing what's * actually stored in the cache — the cache still holds the full `Post[]`, but `data` here is a `number`: * ```tsx - * import { select, useQuery } from '@tanstack/react-query-no-core-pluggable' + * import { select, useQuery } from '@tanstack/react-query-pluggable' * * function PostCount() { * const { data, isPending, isError, error } = useQuery({ @@ -187,7 +266,7 @@ export function useQuery< * A dependent query, only enabled once `postId` is set — use `isLoading`, not `isPending`, so the * loading state doesn't show while the query is disabled: * ```tsx - * import { useQuery } from '@tanstack/react-query-no-core-pluggable' + * import { useQuery } from '@tanstack/react-query-pluggable' * * function Post({ postId }: { postId: number | undefined }) { * const { data, isLoading, isError, error } = useQuery({ @@ -209,7 +288,7 @@ export function useQuery< * `refetch` doesn't work while `queryFn` is `skipToken` — use `enabled: false` instead if you * need to trigger the query manually: * ```tsx - * import { skipToken, useQuery } from '@tanstack/react-query-no-core-pluggable' + * import { skipToken, useQuery } from '@tanstack/react-query-pluggable' * * function Post({ postId }: { postId: number | undefined }) { * const { data, isLoading, isError, error } = useQuery({ @@ -229,7 +308,7 @@ export function useQuery< * over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was * fetched rather than from now: * ```tsx - * import { useQuery, useQueryClient } from '@tanstack/react-query-no-core-pluggable' + * import { useQuery, useQueryClient, getQueryData, getQueryState } from '@tanstack/react-query-pluggable' * * function Post({ postId }: { postId: number }) { * const queryClient = useQueryClient() @@ -238,11 +317,10 @@ export function useQuery< * queryKey: ['post', postId], * queryFn: () => fetchPost(postId), * initialData: () => - * queryClient - * .getQueryData>(['posts']) + * getQueryData(queryClient, ['posts']) * ?.find((post) => post.id === postId), * initialDataUpdatedAt: () => - * queryClient.getQueryState(['posts'])?.dataUpdatedAt, + * getQueryState(queryClient, ['posts'])?.dataUpdatedAt, * }) * * if (isError) return Error: {error.message} @@ -253,7 +331,7 @@ export function useQuery< * @example * Paginated data, keeping the previous page's data visible while the next page loads: * ```tsx - * import { keepPreviousData, placeholderData, useQuery } from '@tanstack/react-query-no-core-pluggable' + * import { keepPreviousData, placeholderData, useQuery } from '@tanstack/react-query-pluggable' * import { useState } from 'react' * * function Posts() { @@ -293,6 +371,20 @@ export function useQuery< queryClient?: QueryClient, ): UseQueryResult -export function useQuery(options: UseQueryOptions, queryClient?: QueryClient) { - return useBaseQuery(options, QueryObserver, queryClient) +export function useQuery( + options: + | ((AnyUseQueryOptions | AnyUseInfiniteQueryOptions) & { + Observer?: InfiniteQueryMode['Observer'] + renderPolicy?: typeof suspenseQueryPolicy + }) + | null + | undefined, + queryClient?: QueryClient, +) { + return useBaseQuery( + options as AnyUseQueryOptions, + (options?.Observer ?? QueryObserver) as typeof QueryObserver, + queryClient, + options?.renderPolicy, + ) } diff --git a/packages/react-query-no-core/src/useSuspenseInfiniteQuery.ts b/packages/react-query-pluggable/src/useSuspenseInfiniteQuery.ts similarity index 82% rename from packages/react-query-no-core/src/useSuspenseInfiniteQuery.ts rename to packages/react-query-pluggable/src/useSuspenseInfiniteQuery.ts index 4b73c02c92a..7f147a14e05 100644 --- a/packages/react-query-no-core/src/useSuspenseInfiniteQuery.ts +++ b/packages/react-query-pluggable/src/useSuspenseInfiniteQuery.ts @@ -1,17 +1,17 @@ 'use client' -import { InfiniteQueryObserver } from './runtime/infiniteQueryObserver' -import { skipToken } from './runtime/utils' -import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' -import { useBaseQuery } from './useBaseQuery' + +import { infiniteQuery } from './infiniteQuery' +import { suspenseQuery } from './suspenseQuery' +import { useQuery } from './useQuery' import type { DefaultError, InfiniteData, OmitKeyof, QueryKey, -} from '@tanstack/query-types/bindings' +} from '@tanstack/query-core' import type { QueryClient } from './runtime/queryClient' -import type { QueryObserver } from './runtime/queryObserver' import type { + AnyUseInfiniteQueryOptions, UseInfiniteQueryOptions, UseInfiniteQueryResult, UseSuspenseInfiniteQueryOptions, @@ -57,7 +57,7 @@ type SkippableSuspenseInfiniteQueryOptions< * import { * QueryErrorResetBoundary, * useSuspenseInfiniteQuery, - * } from '@tanstack/react-query-no-core' + * } from '@tanstack/react-query-pluggable' * * function Projects() { * // `data` is guaranteed to be defined here — no `isPending` check needed. @@ -154,32 +154,9 @@ export function useSuspenseInfiniteQuery< queryClient?: QueryClient, ): UseInfiniteQueryResult -export function useSuspenseInfiniteQuery< - TQueryFnData, - TError = DefaultError, - TData = InfiniteData, - TQueryKey extends QueryKey = QueryKey, - TPageParam = unknown, ->( - options: SkippableSuspenseInfiniteQueryOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, +export function useSuspenseInfiniteQuery( + options: AnyUseInfiniteQueryOptions, queryClient?: QueryClient, -): UseInfiniteQueryResult { - const skipped = options.queryFn === skipToken - - return useBaseQuery( - { - ...options, - enabled: !skipped, - throwOnError: defaultThrowOnError, - }, - InfiniteQueryObserver as typeof QueryObserver, - queryClient, - skipped ? undefined : suspenseQueryPolicy, - ) as UseInfiniteQueryResult +) { + return useQuery(suspenseQuery(infiniteQuery(options)), queryClient) } diff --git a/packages/react-query-no-core-pluggable/src/useSuspenseQueries.ts b/packages/react-query-pluggable/src/useSuspenseQueries.ts similarity index 98% rename from packages/react-query-no-core-pluggable/src/useSuspenseQueries.ts rename to packages/react-query-pluggable/src/useSuspenseQueries.ts index c5a75816eed..6061b40950b 100644 --- a/packages/react-query-no-core-pluggable/src/useSuspenseQueries.ts +++ b/packages/react-query-pluggable/src/useSuspenseQueries.ts @@ -1,5 +1,6 @@ 'use client' -import { skipToken } from './runtime/utils' + +import { skipToken } from '@tanstack/query-core/primitives' import { defaultThrowOnError, suspenseQueriesPolicy } from './suspense' import { useBaseQueries } from './useQueries' import type { @@ -7,7 +8,7 @@ import type { OmitKeyof, QueriesPlaceholderDataFunction, QueryKey, -} from '@tanstack/query-types/bindings' +} from '@tanstack/query-core' import type { placeholderData } from './runtime/placeholderData' import type { Select } from './runtime/projectionTypes' import type { QueryClient } from './runtime/queryClient' @@ -234,7 +235,7 @@ export type SuspenseQueriesResults< * import { * QueryErrorResetBoundary, * useSuspenseQueries, - * } from '@tanstack/react-query-no-core-pluggable' + * } from '@tanstack/react-query-pluggable' * * function Posts({ ids }: { ids: Array }) { * // Every result is guaranteed to be defined — no per-query `isPending` check needed. @@ -285,7 +286,7 @@ export type SuspenseQueriesResults< * import { * QueryErrorResetBoundary, * useSuspenseQueries, - * } from '@tanstack/react-query-no-core-pluggable' + * } from '@tanstack/react-query-pluggable' * * function Dashboard() { * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({ @@ -336,7 +337,7 @@ export type SuspenseQueriesResults< * import { * QueryErrorResetBoundary, * useSuspenseQueries, - * } from '@tanstack/react-query-no-core-pluggable' + * } from '@tanstack/react-query-pluggable' * * function Refresh() { * const anyFetching = useSuspenseQueries({ @@ -416,7 +417,7 @@ export function useSuspenseQueries< * import { * QueryErrorResetBoundary, * useSuspenseQueries, - * } from '@tanstack/react-query-no-core-pluggable' + * } from '@tanstack/react-query-pluggable' * * function Posts({ ids }: { ids: Array }) { * // Every result is guaranteed to be defined — no per-query `isPending` check needed. @@ -467,7 +468,7 @@ export function useSuspenseQueries< * import { * QueryErrorResetBoundary, * useSuspenseQueries, - * } from '@tanstack/react-query-no-core-pluggable' + * } from '@tanstack/react-query-pluggable' * * function Dashboard() { * const [usersQuery, teamsQuery, projectsQuery] = useSuspenseQueries({ diff --git a/packages/react-query-no-core/src/useSuspenseQuery.ts b/packages/react-query-pluggable/src/useSuspenseQuery.ts similarity index 86% rename from packages/react-query-no-core/src/useSuspenseQuery.ts rename to packages/react-query-pluggable/src/useSuspenseQuery.ts index 45d54de3130..3550ca21aa3 100644 --- a/packages/react-query-no-core/src/useSuspenseQuery.ts +++ b/packages/react-query-pluggable/src/useSuspenseQuery.ts @@ -1,13 +1,8 @@ 'use client' -import { QueryObserver } from './runtime/queryObserver' -import { skipToken } from './runtime/utils' -import { defaultThrowOnError, suspenseQueryPolicy } from './suspense' -import { useBaseQuery } from './useBaseQuery' -import type { - DefaultError, - OmitKeyof, - QueryKey, -} from '@tanstack/query-types/bindings' + +import { suspenseQuery } from './suspenseQuery' +import { useQuery } from './useQuery' +import type { DefaultError, OmitKeyof, QueryKey } from '@tanstack/query-core' import type { QueryClient } from './runtime/queryClient' import type { UseQueryOptions, @@ -16,7 +11,8 @@ import type { UseSuspenseQueryResult, } from './types' -type SkippableSuspenseQueryOptions< +/** Options for a Suspense reader whose query function can be skipped. */ +export type SkippableSuspenseQueryOptions< TQueryFnData, TError, TData, @@ -45,7 +41,7 @@ type SkippableSuspenseQueryOptions< * ```tsx * import { Suspense } from 'react' * import { ErrorBoundary } from 'react-error-boundary' - * import { QueryErrorResetBoundary, useSuspenseQuery } from '@tanstack/react-query-no-core' + * import { QueryErrorResetBoundary, useSuspenseQuery } from '@tanstack/react-query-pluggable' * * function Posts() { * // `data` is guaranteed to be defined here — no `isPending` check needed. @@ -136,16 +132,5 @@ export function useSuspenseQuery< >, queryClient?: QueryClient, ): UseQueryResult { - const skipped = options.queryFn === skipToken - - return useBaseQuery( - { - ...options, - enabled: !skipped, - throwOnError: defaultThrowOnError, - }, - QueryObserver, - queryClient, - skipped ? undefined : suspenseQueryPolicy, - ) + return useQuery(suspenseQuery(options), queryClient) } diff --git a/packages/react-query-no-core-pluggable/tests/compat-polling.ts b/packages/react-query-pluggable/tests/compat-polling.ts similarity index 100% rename from packages/react-query-no-core-pluggable/tests/compat-polling.ts rename to packages/react-query-pluggable/tests/compat-polling.ts diff --git a/packages/react-query-no-core-pluggable/tests/compat-projection.ts b/packages/react-query-pluggable/tests/compat-projection.ts similarity index 100% rename from packages/react-query-no-core-pluggable/tests/compat-projection.ts rename to packages/react-query-pluggable/tests/compat-projection.ts diff --git a/packages/react-query-no-core-pluggable/tests/compat-scope.ts b/packages/react-query-pluggable/tests/compat-scope.ts similarity index 100% rename from packages/react-query-no-core-pluggable/tests/compat-scope.ts rename to packages/react-query-pluggable/tests/compat-scope.ts diff --git a/packages/react-query-no-core-pluggable/tsconfig.json b/packages/react-query-pluggable/tsconfig.json similarity index 100% rename from packages/react-query-no-core-pluggable/tsconfig.json rename to packages/react-query-pluggable/tsconfig.json diff --git a/packages/react-query-no-core-pluggable/tsconfig.legacy.json b/packages/react-query-pluggable/tsconfig.legacy.json similarity index 100% rename from packages/react-query-no-core-pluggable/tsconfig.legacy.json rename to packages/react-query-pluggable/tsconfig.legacy.json diff --git a/packages/query-types/tsconfig.prod.json b/packages/react-query-pluggable/tsconfig.prod.json similarity index 100% rename from packages/query-types/tsconfig.prod.json rename to packages/react-query-pluggable/tsconfig.prod.json diff --git a/packages/react-query-no-core-pluggable/tsdown.config.ts b/packages/react-query-pluggable/tsdown.config.ts similarity index 100% rename from packages/react-query-no-core-pluggable/tsdown.config.ts rename to packages/react-query-pluggable/tsdown.config.ts diff --git a/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx b/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx index ca56a81d79c..8310469c993 100644 --- a/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx +++ b/packages/react-query/src/__tests__/infiniteQueryOptions.test-d.tsx @@ -1,6 +1,5 @@ import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { selectOption } from '@tanstack/query-test-utils/projection' import { assertType, describe, expectTypeOf, it } from 'vitest' import { defaultQueryFn } from '..' @@ -117,7 +116,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 1, }) - const data = await cacheOperations(new QueryClient()).infiniteQuery(options) + const data = await new QueryClient().infiniteQuery(options) expectTypeOf(data).toEqualTypeOf>() }) @@ -131,7 +130,7 @@ describe('infiniteQueryOptions', () => { [selectOption]: (data) => data.pages, }) - const data = await cacheOperations(new QueryClient()).infiniteQuery(options) + const data = await new QueryClient().infiniteQuery(options) expectTypeOf(data).toEqualTypeOf>() }) @@ -145,7 +144,7 @@ describe('infiniteQueryOptions', () => { enabled: false, }) - const data = await cacheOperations(new QueryClient()).infiniteQuery(options) + const data = await new QueryClient().infiniteQuery(options) expectTypeOf(data).toEqualTypeOf>() }) @@ -158,7 +157,7 @@ describe('infiniteQueryOptions', () => { initialPageParam: 1, }) - const data = await cacheOperations(new QueryClient()).infiniteQuery(options) + const data = await new QueryClient().infiniteQuery(options) expectTypeOf(data).toEqualTypeOf< InfiniteData | undefined diff --git a/packages/react-query/src/__tests__/ssr.test.tsx b/packages/react-query/src/__tests__/ssr.test.tsx index 9329be7dd6b..8bd86910673 100644 --- a/packages/react-query/src/__tests__/ssr.test.tsx +++ b/packages/react-query/src/__tests__/ssr.test.tsx @@ -1,5 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import * as React from 'react' import { renderToString } from 'react-dom/server' import { @@ -176,7 +175,7 @@ describe('Server Side Rendering', () => { ) } - void cacheOperations(queryClient) + void queryClient .infiniteQuery({ queryKey: key, queryFn, diff --git a/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx b/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx index c32399f4a04..6f8aa0673e4 100644 --- a/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx +++ b/packages/react-query/src/__tests__/useInfiniteQuery.test-d.tsx @@ -1,6 +1,5 @@ import { QueryClient } from '@tanstack/query-core' import { createKey } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { selectOption } from '@tanstack/query-test-utils/projection' import { describe, expectTypeOf, it } from 'vitest' import { useInfiniteQuery } from '../useInfiniteQuery' @@ -21,7 +20,7 @@ describe('pageParam', () => { it('should define type of param passed to queryFunctionContext with initialPageParam for infiniteQuery', () => { const queryClient = new QueryClient() - cacheOperations(queryClient).infiniteQuery({ + queryClient.infiniteQuery({ queryKey: ['key'], queryFn: ({ pageParam }) => { expectTypeOf(pageParam).toEqualTypeOf() diff --git a/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx b/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx index 07a85bd20f7..266c51e8564 100644 --- a/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx +++ b/packages/react-query/src/__tests__/useInfiniteQuery.test.tsx @@ -1,5 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { placeholderOption, selectOption, @@ -1542,7 +1541,7 @@ describe('useInfiniteQuery', () => { // makes an actual network request // and calls invalidateQueries in an onSuccess items.splice(4, 1) - cacheOperations(queryClient).invalidateQueries({ + queryClient.invalidateQueries({ queryKey: key, }) }} diff --git a/packages/react-query/src/__tests__/useMutation.test.tsx b/packages/react-query/src/__tests__/useMutation.test.tsx index 9171fe68eb7..64dd1034206 100644 --- a/packages/react-query/src/__tests__/useMutation.test.tsx +++ b/packages/react-query/src/__tests__/useMutation.test.tsx @@ -1,8 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { - cacheOperations, - getMutationCache, -} from '@tanstack/query-test-utils/cacheOperations' import { act, fireEvent, render } from '@testing-library/react' import * as React from 'react' import { ErrorBoundary } from 'react-error-boundary' @@ -1088,7 +1084,7 @@ describe('useMutation', () => { expect(count).toBe(0) onlineMock.mockReturnValue(true) - getMutationCache(queryClient).resumePausedMutations() + queryClient.getMutationCache().resumePausedMutations() await vi.advanceTimersByTimeAsync(6) expect( @@ -1145,7 +1141,7 @@ describe('useMutation', () => { }) onlineMock.mockReturnValue(true) - getMutationCache(queryClient).resumePausedMutations() + queryClient.getMutationCache().resumePausedMutations() await vi.advanceTimersByTimeAsync(11) expect( @@ -1200,7 +1196,7 @@ describe('useMutation', () => { expect(states[1]).toBe('pending, true') onlineMock.mockReturnValue(true) - getMutationCache(queryClient).resumePausedMutations() + queryClient.getMutationCache().resumePausedMutations() await vi.advanceTimersByTimeAsync(11) expect( @@ -1248,10 +1244,10 @@ describe('useMutation', () => { expect(rendered.getByText('isPaused: true')).toBeInTheDocument() expect( - getMutationCache(queryClient).findAll({ mutationKey: key }), + queryClient.getMutationCache().findAll({ mutationKey: key }), ).toHaveLength(1) expect( - getMutationCache(queryClient).findAll({ mutationKey: key })[0]?.state, + queryClient.getMutationCache().findAll({ mutationKey: key })[0]?.state, ).toMatchObject({ status: 'pending', isPaused: true, @@ -1260,13 +1256,13 @@ describe('useMutation', () => { }) onlineMock.mockReturnValue(true) - getMutationCache(queryClient).resumePausedMutations() + queryClient.getMutationCache().resumePausedMutations() await vi.advanceTimersByTimeAsync(11) expect(rendered.getByText('data: data2')).toBeInTheDocument() expect( - getMutationCache(queryClient).findAll({ mutationKey: key })[0]?.state, + queryClient.getMutationCache().findAll({ mutationKey: key })[0]?.state, ).toMatchObject({ status: 'success', isPaused: false, @@ -1299,12 +1295,12 @@ describe('useMutation', () => { expect(states).toStrictEqual(['idle', 'pending']) fireEvent.click(getByText('unmount')) - expect(getMutationCache(queryClient).getAll()[0]?.state.status).toBe( + expect(queryClient.getMutationCache().getAll()[0]?.state.status).toBe( 'pending', ) await vi.advanceTimersByTimeAsync(11) - expect(getMutationCache(queryClient).getAll()[0]?.state.status).toBe( + expect(queryClient.getMutationCache().getAll()[0]?.state.status).toBe( 'success', ) expect(states).toStrictEqual(['idle', 'pending']) @@ -1644,9 +1640,9 @@ describe('useMutation', () => { fireEvent.click(rendered.getByRole('button', { name: /mutate/i })) fireEvent.click(rendered.getByRole('button', { name: /hide/i })) await vi.advanceTimersByTimeAsync(10) - expect(getMutationCache(queryClient).findAll({ mutationKey })).toHaveLength( - 0, - ) + expect( + queryClient.getMutationCache().findAll({ mutationKey }), + ).toHaveLength(0) expect(count).toBe(1) @@ -2318,7 +2314,7 @@ describe('useMutation', () => { mutationFn: () => sleep(10).then(() => Promise.reject(new Error('Some error'))), onMutate: async (newTodo: string) => { - await cacheOperations(queryClient).cancelQueries({ queryKey: key }) + await queryClient.cancelQueries({ queryKey: key }) const previousTodos = queryClient.getQueryData>(key) queryClient.setQueryData>(key, (old) => [ @@ -2355,7 +2351,7 @@ describe('useMutation', () => { const { mutate } = useMutation({ mutationFn: (newTodo: string) => sleep(10).then(() => newTodo), onMutate: async (newTodo: string) => { - await cacheOperations(queryClient).cancelQueries({ queryKey: key }) + await queryClient.cancelQueries({ queryKey: key }) const previousTodos = queryClient.getQueryData>(key) queryClient.setQueryData>(key, (old) => [ @@ -2614,7 +2610,7 @@ describe('useMutation', () => { const { mutate } = useMutation({ mutationFn: () => sleep(10).then(() => 'mutated'), onSuccess: (_data, _variables, _onMutateResult, context) => { - cacheOperations(context.client).invalidateQueries({ queryKey: key }) + context.client.invalidateQueries({ queryKey: key }) }, }) diff --git a/packages/react-query/src/__tests__/useMutationState.test.tsx b/packages/react-query/src/__tests__/useMutationState.test.tsx index 1003e793651..a22294f5e80 100644 --- a/packages/react-query/src/__tests__/useMutationState.test.tsx +++ b/packages/react-query/src/__tests__/useMutationState.test.tsx @@ -1,6 +1,5 @@ import { Mutation } from '@tanstack/query-core' import { createKey, sleep } from '@tanstack/query-test-utils' -import { getMutationCache } from '@tanstack/query-test-utils/cacheOperations' import { fireEvent, render } from '@testing-library/react' import * as React from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -252,7 +251,7 @@ describe('useMutationState', () => { const queryClient = new QueryClient() const key1 = createKey() const key2 = createKey() - const cache = getMutationCache(queryClient) + const cache = queryClient.getMutationCache() Mutation.build(queryClient, { mutationKey: key1 }) Mutation.build(queryClient, { mutationKey: key2 }) const onCacheChange = vi.fn<(event: MutationCacheNotifyEvent) => void>() @@ -309,7 +308,7 @@ describe('useMutationState', () => { (resultType) => { const queryClient = new QueryClient() const key = createKey() - const cache = getMutationCache(queryClient) + const cache = queryClient.getMutationCache() const existingMutation = Mutation.build(queryClient, { mutationKey: key, meta: { time: 0 }, @@ -513,8 +512,8 @@ describe('useMutationState', () => { expect( rendered.getByText(`keys: ${JSON.stringify([key2])}`), ).toBeInTheDocument() - expect(getMutationCache(client1).hasListeners()).toBe(false) - expect(getMutationCache(client2).hasListeners()).toBe(true) + expect(client1.getMutationCache().hasListeners()).toBe(false) + expect(client2.getMutationCache().hasListeners()).toBe(true) }) it('should remove successful mutations when the query client is cleared', async () => { @@ -545,7 +544,7 @@ describe('useMutationState', () => { fireEvent.click(rendered.getByRole('button', { name: 'clear' })) await vi.advanceTimersByTimeAsync(1) - expect(getMutationCache(queryClient).getAll()).toStrictEqual([]) + expect(queryClient.getMutationCache().getAll()).toStrictEqual([]) expect(rendered.getByText('data: []')).toBeInTheDocument() }) diff --git a/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx b/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx index 221cdd710d9..7ca8f841e6f 100644 --- a/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx +++ b/packages/react-query/src/__tests__/usePrefetchInfiniteQuery.test.tsx @@ -1,5 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { act, fireEvent } from '@testing-library/react' import * as React from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -114,9 +113,7 @@ describe('usePrefetchInfiniteQuery', () => { allPages.length < data.length ? allPages.length : undefined, } - void cacheOperations(queryClient) - .infiniteQuery({ ...queryOpts, pages: 3 }) - .catch(noop) + void queryClient.infiniteQuery({ ...queryOpts, pages: 3 }).catch(noop) await vi.advanceTimersByTimeAsync(30) queryOpts.queryFn.mockClear() diff --git a/packages/react-query/src/__tests__/useQueries.test.tsx b/packages/react-query/src/__tests__/useQueries.test.tsx index 3b9d5d56b54..dae2db61e75 100644 --- a/packages/react-query/src/__tests__/useQueries.test.tsx +++ b/packages/react-query/src/__tests__/useQueries.test.tsx @@ -1,5 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { selectOption } from '@tanstack/query-test-utils/projection' import { fireEvent, render } from '@testing-library/react' import * as React from 'react' @@ -903,7 +902,7 @@ describe('useQueries', () => { // both pending, one pending, both resolved expect(spy).toHaveBeenCalledTimes(3) - cacheOperations(client).refetchQueries() + client.refetchQueries() await vi.advanceTimersByTimeAsync(21) // no increase because result hasn't changed @@ -916,7 +915,7 @@ describe('useQueries', () => { value = 1 - cacheOperations(client).refetchQueries() + client.refetchQueries() await vi.advanceTimersByTimeAsync(21) expect( diff --git a/packages/react-query/src/__tests__/useQuery.test.tsx b/packages/react-query/src/__tests__/useQuery.test.tsx index ff46ddab48a..f1f7fd3d319 100644 --- a/packages/react-query/src/__tests__/useQuery.test.tsx +++ b/packages/react-query/src/__tests__/useQuery.test.tsx @@ -3,7 +3,6 @@ import { mockVisibilityState, sleep, } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { refetchInterval } from '@tanstack/query-test-utils/polling' import { placeholderOption, @@ -182,9 +181,7 @@ describe('useQuery', () => { ) try { await act(() => vi.advanceTimersByTimeAsync(0)) - await act(() => - cacheOperations(queryClient).cancelQueries({ queryKey: key }), - ) + await act(() => queryClient.cancelQueries({ queryKey: key })) await act(() => vi.advanceTimersByTimeAsync(1)) expect(view.result.current.fetchStatus).toBe('idle') focusManager.setFocused(false) @@ -672,7 +669,7 @@ describe('useQuery', () => { @@ -1021,11 +1014,7 @@ describe('useQuery', () => { return (
    - @@ -1140,11 +1129,7 @@ describe('useQuery', () => { return (
    isFetching: {result.isFetching}
    - data: {result.data} @@ -1180,9 +1165,7 @@ describe('useQuery', () => { return (
    @@ -1230,7 +1213,7 @@ describe('useQuery', () => { React.useEffect(() => { setActTimeout(() => { - cacheOperations(queryClient).refetchQueries({ queryKey: key }) + queryClient.refetchQueries({ queryKey: key }) }, 20) }, []) @@ -1269,7 +1252,7 @@ describe('useQuery', () => { React.useEffect(() => { setActTimeout(() => { - cacheOperations(queryClient).invalidateQueries({ queryKey: key }) + queryClient.invalidateQueries({ queryKey: key }) }, 10) }, []) @@ -3004,11 +2987,7 @@ describe('useQuery', () => { return (
    - {show && } @@ -4744,11 +4723,7 @@ describe('useQuery', () => { return (
    -
    data: {state.data ?? 'null'}
    @@ -4824,11 +4799,7 @@ describe('useQuery', () => { return (
    -
    data: {state.data ?? 'null'}
    @@ -5252,7 +5223,7 @@ describe('useQuery', () => {
    data: {state.data}
    @@ -5750,7 +5719,7 @@ describe('useQuery', () => { diff --git a/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx b/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx index 29a3a622853..47f48136f22 100644 --- a/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx +++ b/packages/react-query/src/__tests__/useSuspenseQuery.test.tsx @@ -1,5 +1,4 @@ import { createKey, sleep } from '@tanstack/query-test-utils' -import { cacheOperations } from '@tanstack/query-test-utils/cacheOperations' import { refetchInterval } from '@tanstack/query-test-utils/polling' import { placeholderOption, @@ -688,10 +687,7 @@ describe('useSuspenseQuery', () => { return (
    rendered {result.data} -
    diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 155552b6f5a..0769614faab 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7263,12 +7263,9 @@ importers: '@tanstack/react-query': specifier: workspace:* version: link:../../../packages/react-query - '@tanstack/react-query-no-core': + '@tanstack/react-query-pluggable': specifier: workspace:* - version: link:../../../packages/react-query-no-core - '@tanstack/react-query-no-core-pluggable': - specifier: workspace:* - version: link:../../../packages/react-query-no-core-pluggable + version: link:../../../packages/react-query-pluggable react: specifier: 'catalog:' version: 19.3.1 @@ -7387,18 +7384,12 @@ importers: '@tanstack/query-core': specifier: workspace:* version: link:../../../packages/query-core - '@tanstack/query-types': - specifier: workspace:* - version: link:../../../packages/query-types '@tanstack/react-query': specifier: workspace:* version: link:../../../packages/react-query - '@tanstack/react-query-no-core': + '@tanstack/react-query-pluggable': specifier: workspace:* - version: link:../../../packages/react-query-no-core - '@tanstack/react-query-no-core-pluggable': - specifier: workspace:* - version: link:../../../packages/react-query-no-core-pluggable + version: link:../../../packages/react-query-pluggable devDependencies: '@types/react': specifier: ^19.3.0 @@ -8046,10 +8037,6 @@ importers: version: 17.4.0(@babel/preset-env@7.29.7(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(supports-color@10.2.2) packages/query-core: - dependencies: - '@tanstack/query-types': - specifier: workspace:* - version: link:../query-types devDependencies: '@tanstack/query-test-utils': specifier: workspace:* @@ -8127,12 +8114,6 @@ importers: specifier: 'catalog:' version: 6.0.3 - packages/query-types: - devDependencies: - typescript: - specifier: 'catalog:' - version: 6.0.3 - packages/react-query: dependencies: '@tanstack/query-core': @@ -8237,40 +8218,30 @@ importers: specifier: 'catalog:' version: 6.0.3 - packages/react-query-no-core: + packages/react-query-persist-client: dependencies: - '@tanstack/query-types': + '@tanstack/query-persist-client-core': specifier: workspace:* - version: link:../query-types + version: link:../query-persist-client-core devDependencies: '@eslint-react/eslint-plugin': specifier: 'catalog:' version: 5.28.8(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3) - '@types/react': - specifier: ^19.3.0 - version: 19.3.0 - eslint-plugin-react-hooks: - specifier: 'catalog:' - version: 7.1.1(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2) - react: - specifier: 'catalog:' - version: 19.3.1 - typescript: - specifier: 'catalog:' - version: 6.0.3 - - packages/react-query-no-core-pluggable: - dependencies: - '@tanstack/query-types': + '@tanstack/query-test-utils': specifier: workspace:* - version: link:../query-types - devDependencies: - '@eslint-react/eslint-plugin': + version: link:../query-test-utils + '@tanstack/react-query': + specifier: workspace:* + version: link:../react-query + '@testing-library/react': specifier: 'catalog:' - version: 5.28.8(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3) + version: 16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@types/react': specifier: ^19.3.0 version: 19.3.0 + '@vitejs/plugin-react': + specifier: 'catalog:' + version: 6.2.1(babel-plugin-react-compiler@1.0.0)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) eslint-plugin-react-hooks: specifier: 'catalog:' version: 7.1.1(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2) @@ -8281,36 +8252,33 @@ importers: specifier: 'catalog:' version: 6.0.3 - packages/react-query-persist-client: + packages/react-query-pluggable: dependencies: - '@tanstack/query-persist-client-core': + '@tanstack/query-core': specifier: workspace:* - version: link:../query-persist-client-core + version: link:../query-core devDependencies: '@eslint-react/eslint-plugin': specifier: 'catalog:' version: 5.28.8(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@6.0.3) - '@tanstack/query-test-utils': - specifier: workspace:* - version: link:../query-test-utils - '@tanstack/react-query': - specifier: workspace:* - version: link:../react-query '@testing-library/react': specifier: 'catalog:' version: 16.3.2(@testing-library/dom@10.4.1)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1) '@types/react': specifier: ^19.3.0 version: 19.3.0 - '@vitejs/plugin-react': - specifier: 'catalog:' - version: 6.2.1(babel-plugin-react-compiler@1.0.0)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass-embedded@1.108.2)(sass@1.108.2)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.0)) + '@types/react-dom': + specifier: ^19.3.0 + version: 19.3.0(@types/react@19.3.0) eslint-plugin-react-hooks: specifier: 'catalog:' version: 7.1.1(eslint@9.39.5(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2) react: specifier: 'catalog:' version: 19.3.1 + react-dom: + specifier: 'catalog:' + version: 19.3.1(react@19.3.1) typescript: specifier: 'catalog:' version: 6.0.3 diff --git a/scripts/port-query-client-tests.mjs b/scripts/port-query-client-tests.mjs new file mode 100644 index 00000000000..f0c76c4d117 --- /dev/null +++ b/scripts/port-query-client-tests.mjs @@ -0,0 +1,180 @@ +// Port only calls on the original QueryClient. The upstream checker distinguishes +// its methods from identically named methods on observers, caches and promises. +import path from 'node:path' +import ts from 'typescript' + +const renamed = { + query: 'fetchQuery', + infiniteQuery: 'fetchInfiniteQuery', + mount: 'mountQueryClient', + unmount: 'unmountQueryClient', + clear: 'clearQueryClient', +} + +export function queryClientTestPort(upstream, files, packageName) { + const config = ts.readConfigFile( + path.join(upstream, 'tsconfig.json'), + ts.sys.readFile, + ) + const { options } = ts.parseJsonConfigFileContent( + config.config, + ts.sys, + upstream, + ) + const program = ts.createProgram(files, options) + const checker = program.getTypeChecker() + + function isClientMethod(receiver, name) { + return checker + .getTypeAtLocation(receiver) + .getProperty(name) + ?.declarations?.some( + (declaration) => + declaration.parent.name?.text === 'QueryClient' && + /\/query-core\/(?:src|build|dist-ts)\//.test( + declaration.getSourceFile().fileName, + ), + ) + } + + return function port(file) { + const source = program.getSourceFile(file) + const edits = [] + const api = '__clientOperations' + let usesOperations = false + let checksArguments = false + function edit(start, end, text) { + edits.push({ start, end, text }) + } + function operation(name) { + usesOperations = true + return api + '.' + (renamed[name] ?? name) + } + function typeReference(node) { + if ( + ts.isIndexedAccessTypeNode(node) && + ts.isLiteralTypeNode(node.indexType) && + ts.isStringLiteral(node.indexType.literal) && + isClientMethod(node.objectType, node.indexType.literal.text) + ) { + return { + operation: 'typeof ' + operation(node.indexType.literal.text), + client: api + '.QueryClient', + } + } + if ( + ts.isTypeQueryNode(node) && + ts.isQualifiedName(node.exprName) && + isClientMethod(node.exprName.left, node.exprName.right.text) + ) { + const generic = node.typeArguments?.length + ? '<' + + node.typeArguments.map((t) => t.getText(source)).join(', ') + + '>' + : '' + return { + operation: 'typeof ' + operation(node.exprName.right.text) + generic, + client: 'typeof ' + node.exprName.left.getText(source), + } + } + } + function visit(node) { + if ( + (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) && + node.moduleSpecifier && + ts.isStringLiteral(node.moduleSpecifier) && + node.moduleSpecifier.text === '@tanstack/query-core' + ) { + edit( + node.moduleSpecifier.getStart(), + node.moduleSpecifier.end, + JSON.stringify(packageName), + ) + return + } + if ( + ts.isCallExpression(node) && + ts.isPropertyAccessExpression(node.expression) + ) { + const member = node.expression + if (isClientMethod(member.expression, member.name.text)) { + edit(member.getStart(), member.end, operation(member.name.text)) + edit( + node.arguments.pos, + node.arguments.pos, + member.expression.getText(source) + + (node.arguments.length ? ', ' : ''), + ) + for (const arg of [...(node.typeArguments ?? []), ...node.arguments]) + visit(arg) + return + } + } + // Tests that inspect the old parameter tuple still check every original + // argument. The new first argument must be compatible with the receiver. + if ( + ts.isTypeReferenceNode(node) && + node.typeName.getText(source) === 'Parameters' && + node.typeArguments?.length === 1 + ) { + const ref = typeReference(node.typeArguments[0]) + if (ref) { + checksArguments = true + edit( + node.getStart(), + node.end, + '__OperationArgs<' + ref.operation + ', ' + ref.client + '>', + ) + return + } + } + if ( + ts.isPropertyAccessExpression(node) && + node.name.text === 'parameters' && + ts.isCallExpression(node.expression) + ) { + const assertion = node.expression, + member = assertion.arguments[0] + if ( + assertion.expression.getText(source) === 'expectTypeOf' && + member && + ts.isPropertyAccessExpression(member) && + isClientMethod(member.expression, member.name.text) + ) { + checksArguments = true + edit( + node.getStart(), + node.end, + 'expectTypeOf<__OperationArgs>()', + ) + return + } + } + ts.forEachChild(node, visit) + } + visit(source) + let result = source.text + for (const { start, end, text } of edits.sort( + (a, b) => b.start - a.start || b.end - a.end, + )) { + result = result.slice(0, start) + text + result.slice(end) + } + if (!usesOperations) return result + const argumentsType = checksArguments + ? 'type __OperationArgs unknown, Client> = Parameters extends [Client, ...infer Args] ? Args : never\n' + : '' + return ( + 'import * as ' + + api + + ' from ' + + JSON.stringify(packageName) + + '\n' + + argumentsType + + result + ) + } +} diff --git a/scripts/react-query-compat.config.ts b/scripts/react-query-compat.config.ts index e6442b05a6c..9f6f7ee8424 100644 --- a/scripts/react-query-compat.config.ts +++ b/scripts/react-query-compat.config.ts @@ -25,9 +25,7 @@ export default defineConfig({ ...base.test, name: `${basename(adapter)}/${suite}`, // Override the relative paths inherited from the upstream project. - setupFiles: isReact - ? [resolve(import.meta.dirname, '../packages/react-query/test-setup.ts')] - : [], + setupFiles: isReact ? [resolve('test-setup.ts')] : [], coverage: { ...base.test?.coverage, include: [ diff --git a/scripts/test-react-query-compat.mjs b/scripts/test-react-query-compat.mjs index f47df32654b..070160a3af4 100644 --- a/scripts/test-react-query-compat.mjs +++ b/scripts/test-react-query-compat.mjs @@ -1,4 +1,4 @@ -// Run the original runtime and type suites against each adapter. The temporary +// Run the original runtime and type suites against the pluggable adapter. The temporary // projects preserve the suites' relative imports without duplicating test cases. import { execFileSync } from 'node:child_process' import { @@ -11,13 +11,26 @@ import { } from 'node:fs' import { createRequire } from 'node:module' import { basename, join, relative, resolve, sep } from 'node:path' +import { queryClientTestPort } from './port-query-client-tests.mjs' import { portProjectionOptions } from './port-query-projection-tests.mjs' const adapter = process.cwd() const repository = resolve(import.meta.dirname, '..') const require = createRequire(import.meta.url) const entry = join(adapter, 'src/index.ts') -const pluggable = basename(adapter) === 'react-query-no-core-pluggable' +const packageName = '@tanstack/react-query-pluggable' +const shared = [ + 'environmentManager', + 'focusManager', + 'onlineManager', + 'removable', + 'retryer', + 'subscribable', + 'timeoutManager', +] + +// Only adapt imports in copies of the upstream tests and their setup. The +// implementation and its workspace dependencies resolve the real core package. function importPath(from, to) { return './' + relative(from, to).split(sep).join('/') } @@ -39,9 +52,32 @@ for (const suite of ['query-core', 'react-query']) { filter: (path) => suite !== 'query-core' || basename(path) !== 'frameworkAdapters', }) - if (pluggable) { - portProjectionOptions(join(source, '__tests__')) + const tests = join(source, '__tests__') + const originals = join(upstream, 'src/__tests__') + const testFiles = readdirSync(tests, { recursive: true }).filter((file) => + /\.tsx?$/.test(file), + ) + const configFiles = + suite === 'react-query' + ? [ + join(upstream, 'test-setup.ts'), + join( + repository, + 'packages/query-persist-client-core/src/createPersister.ts', + ), + ] + : [] + const port = queryClientTestPort( + upstream, + [...testFiles.map((file) => join(originals, file)), ...configFiles], + packageName, + ) + function copyTestModule(from, to) { + writeFileSync(to, port(from)) } + for (const file of testFiles) + copyTestModule(join(originals, file), join(tests, file)) + portProjectionOptions(tests) for (const file of readdirSync(implementation, { withFileTypes: true })) { if (!file.isFile() || !/\.tsx?$/.test(file.name)) continue @@ -49,7 +85,13 @@ for (const suite of ['query-core', 'react-query']) { writeFileSync(join(source, file.name), `export * from '${target}'\n`) } if (suite === 'query-core') { - // The React runtimes expose the page fetcher directly. + for (const name of shared) { + writeFileSync( + join(source, name + '.ts'), + "export * from '@tanstack/query-core/primitives'\n", + ) + } + // The pluggable runtime exposes the page fetcher directly. writeFileSync( join(source, '__tests__/infiniteFetch.ts'), `export { prepareInfiniteFetch } from '../infiniteQueryBehavior'\n`, @@ -61,7 +103,18 @@ for (const suite of ['query-core', 'react-query']) { ) } - const setup = join(repository, 'packages/react-query/test-setup.ts') + const setup = join(project, 'test-setup.ts') + const persister = join(source, 'createPersister.ts') + if (suite === 'react-query') { + copyTestModule(join(upstream, 'test-setup.ts'), setup) + copyTestModule( + join( + repository, + 'packages/query-persist-client-core/src/createPersister.ts', + ), + persister, + ) + } const tsconfig = { extends: join(adapter, 'tsconfig.json'), compilerOptions: { @@ -71,27 +124,17 @@ for (const suite of ['query-core', 'react-query']) { emitDeclarationOnly: false, noEmit: true, paths: { - '@tanstack/query-core': [entry], - // The React suite uses per-query persistence. The separate whole-client - // persister subscribes through the original client's mutation-cache method. - ...(pluggable && - suite === 'react-query' && { - '@tanstack/query-persist-client-core': [ - join( - repository, - 'packages/query-persist-client-core/src/createPersister.ts', - ), - ], - }), - ...(pluggable && - Object.fromEntries( - ['polling', 'cacheOperations', 'projection', 'scope'].map( - (name) => [ - `@tanstack/query-test-utils/${name}`, - [join(adapter, `tests/compat-${name}.ts`)], - ], - ), - )), + [packageName]: [entry], + // This suite exercises only the per-query persistence implementation. + ...(suite === 'react-query' && { + '@tanstack/query-persist-client-core': [persister], + }), + ...Object.fromEntries( + ['polling', 'projection', 'scope'].map((name) => [ + `@tanstack/query-test-utils/${name}`, + [join(adapter, `tests/compat-${name}.ts`)], + ]), + ), }, }, include: suite === 'react-query' ? ['src', setup] : ['src'],