@tanstack/angular-query 0.0.0 → 5.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +120 -36
  3. package/hydration-state-key.d.ts +4 -0
  4. package/hydration-state-key.mjs +14 -0
  5. package/hydration-state-key.mjs.map +1 -0
  6. package/index.d.ts +22 -0
  7. package/index.mjs +32 -0
  8. package/index.mjs.map +1 -0
  9. package/infinite-query-options.d.ts +216 -0
  10. package/infinite-query-options.mjs +7 -0
  11. package/infinite-query-options.mjs.map +1 -0
  12. package/inject-base-query.d.ts +5 -0
  13. package/inject-base-query.mjs +64 -0
  14. package/inject-base-query.mjs.map +1 -0
  15. package/inject-infinite-query.d.ts +67 -0
  16. package/inject-infinite-query.mjs +38 -0
  17. package/inject-infinite-query.mjs.map +1 -0
  18. package/inject-is-fetching.d.ts +11 -0
  19. package/inject-is-fetching.mjs +18 -0
  20. package/inject-is-fetching.mjs.map +1 -0
  21. package/inject-is-mutating.d.ts +11 -0
  22. package/inject-is-mutating.mjs +18 -0
  23. package/inject-is-mutating.mjs.map +1 -0
  24. package/inject-is-restoring.d.ts +13 -0
  25. package/inject-is-restoring.mjs +21 -0
  26. package/inject-is-restoring.mjs.map +1 -0
  27. package/inject-mutation-state.d.ts +16 -0
  28. package/inject-mutation-state.mjs +28 -0
  29. package/inject-mutation-state.mjs.map +1 -0
  30. package/inject-mutation.d.ts +32 -0
  31. package/inject-mutation.mjs +72 -0
  32. package/inject-mutation.mjs.map +1 -0
  33. package/inject-queries.d.ts +35 -0
  34. package/inject-queries.mjs +120 -0
  35. package/inject-queries.mjs.map +1 -0
  36. package/inject-queries.types.d.ts +109 -0
  37. package/inject-query.d.ts +127 -0
  38. package/inject-query.mjs +20 -0
  39. package/inject-query.mjs.map +1 -0
  40. package/internal.d.ts +8 -0
  41. package/internal.mjs +8 -0
  42. package/internal.mjs.map +1 -0
  43. package/mutation-options.d.ts +84 -0
  44. package/mutation-options.mjs +7 -0
  45. package/mutation-options.mjs.map +1 -0
  46. package/package.json +52 -4
  47. package/providers.d.ts +83 -0
  48. package/providers.mjs +89 -0
  49. package/providers.mjs.map +1 -0
  50. package/query-options.d.ts +208 -0
  51. package/query-options.mjs +7 -0
  52. package/query-options.mjs.map +1 -0
  53. package/query-resource.d.ts +36 -0
  54. package/query-resource.mjs +70 -0
  55. package/query-resource.mjs.map +1 -0
  56. package/schematics/collection.json +10 -0
  57. package/schematics/ng-add/index.js +96 -0
  58. package/schematics/ng-add/schema.js +2 -0
  59. package/schematics/ng-add/schema.json +17 -0
  60. package/schematics/package.json +3 -0
  61. package/types.d.ts +164 -0
  62. package/utils/inject-external-store.d.ts +33 -0
  63. package/utils/inject-external-store.mjs +41 -0
  64. package/utils/inject-external-store.mjs.map +1 -0
  65. package/utils/inject-pending-tasks-lifecycle.d.ts +6 -0
  66. package/utils/inject-pending-tasks-lifecycle.mjs +31 -0
  67. package/utils/inject-pending-tasks-lifecycle.mjs.map +1 -0
  68. package/utils/inject-query-zone.d.ts +2 -0
  69. package/utils/inject-query-zone.mjs +9 -0
  70. package/utils/inject-query-zone.mjs.map +1 -0
  71. package/utils/resource-types.d.ts +8 -0
  72. package/utils/result-fields.d.ts +80 -0
  73. package/utils/result-fields.mjs +65 -0
  74. package/utils/result-fields.mjs.map +1 -0
  75. package/utils/signal-proxy.d.ts +20 -0
  76. package/utils/signal-proxy.mjs +12 -0
  77. package/utils/signal-proxy.mjs.map +1 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021-present Tanner Linsley
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,45 +1,129 @@
1
- # @tanstack/angular-query
1
+ <picture>
2
+ <source
3
+ media="(prefers-color-scheme: dark)"
4
+ srcset="https://tanstack.com/api/readme/query.png?framework=angular&theme=dark"
5
+ />
6
+ <source
7
+ media="(prefers-color-scheme: light)"
8
+ srcset="https://tanstack.com/api/readme/query.png?framework=angular"
9
+ />
10
+ <img
11
+ src="https://tanstack.com/api/readme/query.png?framework=angular"
12
+ alt="TanStack Angular Query"
13
+ width="900"
14
+ />
15
+ </picture>
2
16
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
17
+ [![npm version](https://img.shields.io/npm/v/@tanstack/angular-query)](https://www.npmjs.com/package/@tanstack/angular-query)
18
+ [![npm license](https://img.shields.io/npm/l/@tanstack/angular-query)](https://github.com/TanStack/query/blob/main/LICENSE)
19
+ [![bundle size](https://img.shields.io/bundlephobia/minzip/@tanstack/angular-query)](https://bundlephobia.com/package/@tanstack/angular-query)
20
+ [![npm](https://img.shields.io/npm/dm/@tanstack/angular-query)](https://www.npmjs.com/package/@tanstack/angular-query)
4
21
 
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
22
+ # Angular Query
6
23
 
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
24
+ Functions for fetching, caching and updating asynchronous data in Angular
8
25
 
9
- ## Purpose
26
+ # Documentation
10
27
 
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `@tanstack/angular-query`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
28
+ Visit https://tanstack.com/query/latest/docs/framework/angular/overview
29
+
30
+ ## Quick Features
31
+
32
+ - Transport/protocol/backend agnostic data fetching (REST, GraphQL, promises, whatever!)
33
+ - Auto Caching + Refetching (stale-while-revalidate, Window Refocus, Polling/Realtime)
34
+ - Parallel + Dependent Queries
35
+ - Mutations + Reactive Query Refetching
36
+ - Multi-layer Cache + Automatic Garbage Collection
37
+ - Paginated + Cursor-based Queries
38
+ - Load-More + Infinite Scroll Queries w/ Scroll Recovery
39
+ - Request Cancellation
40
+ - Dedicated Devtools
41
+
42
+ # Quick Start
43
+
44
+ > The Angular adapter for TanStack Query requires Angular 20.1 or higher.
45
+
46
+ 1. Install `angular-query`
47
+
48
+ ```bash
49
+ $ npm i @tanstack/angular-query
50
+ ```
51
+
52
+ or
53
+
54
+ ```bash
55
+ $ pnpm add @tanstack/angular-query
56
+ ```
57
+
58
+ or
59
+
60
+ ```bash
61
+ $ yarn add @tanstack/angular-query
62
+ ```
63
+
64
+ or
65
+
66
+ ```bash
67
+ $ bun add @tanstack/angular-query
68
+ ```
69
+
70
+ 2. Initialize **TanStack Query** by adding **provideTanStackQuery** to your application
71
+
72
+ Pass a factory; Angular runs it once per injector and in an injection context.
73
+
74
+ ```ts
75
+ import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'
76
+
77
+ bootstrapApplication(AppComponent, {
78
+ providers: [provideTanStackQuery(() => new QueryClient())],
79
+ })
80
+ ```
81
+
82
+ 3. Inject query
83
+
84
+ ```ts
85
+ import { injectQuery } from '@tanstack/angular-query'
86
+ import { Component } from '@angular/core'
87
+
88
+ @Component({...})
89
+ export class TodosComponent {
90
+ info = injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodoList }))
91
+ }
92
+ ```
93
+
94
+ 4. If you need to update options on your query dynamically, make sure to pass them as signals. The query will refetch automatically if data for an updated query key is stale or not present.
95
+
96
+ [Open in StackBlitz](https://stackblitz.com/github/TanStack/query/tree/main/examples/angular/router)
97
+
98
+ ```ts
99
+ @Component({})
100
+ export class PostComponent {
101
+ #postsService = inject(PostsService)
102
+ postId = input.required({
103
+ transform: numberAttribute,
104
+ })
15
105
 
16
- ## What is OIDC Trusted Publishing?
106
+ postQuery = injectQuery(() => ({
107
+ queryKey: ['post', this.postId()],
108
+ queryFn: () => {
109
+ return lastValueFrom(this.#postsService.postById$(this.postId()))
110
+ },
111
+ }))
112
+ }
17
113
 
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
114
+ @Injectable({
115
+ providedIn: 'root',
116
+ })
117
+ export class PostsService {
118
+ #http = inject(HttpClient)
19
119
 
20
- ## Setup Instructions
120
+ postById$ = (postId: number) =>
121
+ this.#http.get<Post>(`https://jsonplaceholder.typicode.com/posts/${postId}`)
122
+ }
21
123
 
22
- To properly configure OIDC trusted publishing for this package:
23
-
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
28
-
29
- ## DO NOT USE THIS PACKAGE
30
-
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
36
-
37
- ## More Information
38
-
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
42
-
43
- ---
44
-
45
- **Maintained for OIDC setup purposes only**
124
+ export interface Post {
125
+ id: number
126
+ title: string
127
+ body: string
128
+ }
129
+ ```
@@ -0,0 +1,4 @@
1
+ import { InjectionToken, StateKey } from '@angular/core';
2
+ import { DehydratedState } from '@tanstack/query-core';
3
+ export declare const INTERNAL_TANSTACK_QUERY_HYDRATION_STATE_KEY: StateKey<DehydratedState>;
4
+ export declare const INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY: InjectionToken<StateKey<DehydratedState>>;
@@ -0,0 +1,14 @@
1
+ import { InjectionToken, makeStateKey } from "@angular/core";
2
+ const INTERNAL_TANSTACK_QUERY_HYDRATION_STATE_KEY = makeStateKey("tanstack-query-hydration-state");
3
+ const INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY = new InjectionToken(
4
+ "tanstack-query-hydration-transfer-key",
5
+ {
6
+ providedIn: "root",
7
+ factory: () => INTERNAL_TANSTACK_QUERY_HYDRATION_STATE_KEY
8
+ }
9
+ );
10
+ export {
11
+ INTERNAL_TANSTACK_QUERY_HYDRATION_STATE_KEY,
12
+ INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY
13
+ };
14
+ //# sourceMappingURL=hydration-state-key.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hydration-state-key.mjs","sources":["../src/hydration-state-key.ts"],"sourcesContent":["import { InjectionToken, makeStateKey } from '@angular/core'\nimport type { StateKey } from '@angular/core'\nimport type { DehydratedState } from '@tanstack/query-core'\n\nexport const INTERNAL_TANSTACK_QUERY_HYDRATION_STATE_KEY =\n makeStateKey<DehydratedState>('tanstack-query-hydration-state')\n\nexport const INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY =\n new InjectionToken<StateKey<DehydratedState>>(\n 'tanstack-query-hydration-transfer-key',\n {\n providedIn: 'root',\n factory: () => INTERNAL_TANSTACK_QUERY_HYDRATION_STATE_KEY,\n },\n )\n"],"names":[],"mappings":";AAIO,MAAM,8CACX,aAA8B,gCAAgC;AAEzD,MAAM,iDACX,IAAI;AAAA,EACF;AAAA,EACA;AAAA,IACE,YAAY;AAAA,IACZ,SAAS,MAAM;AAAA,EAAA;AAEnB;"}
package/index.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ export * from '@tanstack/query-core';
2
+ export * from './types.js';
3
+ export type { QueryResource } from './query-resource.js';
4
+ export { toResource } from './query-resource.js';
5
+ export type { DefinedInitialDataOptions, UndefinedInitialDataOptions, UnusedSkipTokenOptions, } from './query-options.js';
6
+ export { queryOptions } from './query-options.js';
7
+ export type { CreateMutationOptions } from './types.js';
8
+ export { mutationOptions } from './mutation-options.js';
9
+ export type { DefinedInitialDataInfiniteOptions, UndefinedInitialDataInfiniteOptions, UnusedSkipTokenInfiniteOptions, } from './infinite-query-options.js';
10
+ export { infiniteQueryOptions } from './infinite-query-options.js';
11
+ export { injectInfiniteQuery } from './inject-infinite-query.js';
12
+ export { injectIsFetching } from './inject-is-fetching.js';
13
+ export { injectIsMutating } from './inject-is-mutating.js';
14
+ export { injectIsRestoring } from './inject-is-restoring.js';
15
+ export { injectMutation } from './inject-mutation.js';
16
+ export type { MutationStateOptions } from './inject-mutation-state.js';
17
+ export { injectMutationState } from './inject-mutation-state.js';
18
+ export type { InjectQueriesOptions, QueriesOptions, QueriesResults, } from './inject-queries.types.js';
19
+ export { injectQueries } from './inject-queries.js';
20
+ export { injectQuery } from './inject-query.js';
21
+ export type { QueryFeature } from './providers.js';
22
+ export { provideTanStackQuery, withHydrationKey, withNoQueryHydration, } from './providers.js';
package/index.mjs ADDED
@@ -0,0 +1,32 @@
1
+ export * from "@tanstack/query-core";
2
+ import { toResource } from "./query-resource.mjs";
3
+ import { queryOptions } from "./query-options.mjs";
4
+ import { mutationOptions } from "./mutation-options.mjs";
5
+ import { infiniteQueryOptions } from "./infinite-query-options.mjs";
6
+ import { injectInfiniteQuery } from "./inject-infinite-query.mjs";
7
+ import { injectIsFetching } from "./inject-is-fetching.mjs";
8
+ import { injectIsMutating } from "./inject-is-mutating.mjs";
9
+ import { injectIsRestoring } from "./inject-is-restoring.mjs";
10
+ import { injectMutation } from "./inject-mutation.mjs";
11
+ import { injectMutationState } from "./inject-mutation-state.mjs";
12
+ import { injectQueries } from "./inject-queries.mjs";
13
+ import { injectQuery } from "./inject-query.mjs";
14
+ import { provideTanStackQuery, withHydrationKey, withNoQueryHydration } from "./providers.mjs";
15
+ export {
16
+ infiniteQueryOptions,
17
+ injectInfiniteQuery,
18
+ injectIsFetching,
19
+ injectIsMutating,
20
+ injectIsRestoring,
21
+ injectMutation,
22
+ injectMutationState,
23
+ injectQueries,
24
+ injectQuery,
25
+ mutationOptions,
26
+ provideTanStackQuery,
27
+ queryOptions,
28
+ toResource,
29
+ withHydrationKey,
30
+ withNoQueryHydration
31
+ };
32
+ //# sourceMappingURL=index.mjs.map
package/index.mjs.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;"}
@@ -0,0 +1,216 @@
1
+ import { DefaultError, InfiniteData, InitialDataFunction, NonUndefinedGuard, OmitKeyof, QueryKey, QueryKeyWithDataTag, SkipToken } from '@tanstack/query-core';
2
+ import { CreateInfiniteQueryOptions } from './types.js';
3
+ /**
4
+ * The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set — `data`
5
+ * may be `undefined` while the query is `pending`.
6
+ *
7
+ * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
8
+ * @template TError - The type of errors your `queryFn` may throw.
9
+ * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
10
+ * the shape of all fetched pages plus their page params.
11
+ * @template TQueryKey - The type of your `queryKey`.
12
+ * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
13
+ */
14
+ export type UndefinedInitialDataInfiniteOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> = CreateInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & {
15
+ /**
16
+ * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
17
+ * created or cached yet). If set to a function, the function will be called **once** during the shared/root
18
+ * query initialization, and be expected to synchronously return the initial data. Initial data is
19
+ * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
20
+ * cache.
21
+ */
22
+ initialData?: undefined | NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>> | InitialDataFunction<NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>>;
23
+ };
24
+ /**
25
+ * The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set and
26
+ * `queryFn` is not `skipToken` — same as {@link UndefinedInitialDataInfiniteOptions}, but `queryFn` may not be
27
+ * `skipToken`.
28
+ *
29
+ * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
30
+ * @template TError - The type of errors your `queryFn` may throw.
31
+ * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
32
+ * the shape of all fetched pages plus their page params.
33
+ * @template TQueryKey - The type of your `queryKey`.
34
+ * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
35
+ */
36
+ export type UnusedSkipTokenInfiniteOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> = OmitKeyof<CreateInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, 'queryFn'> & {
37
+ /**
38
+ * `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If
39
+ * you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a
40
+ * fetch that fails with "Missing queryFn" unless `enabled` is `false` or a default query function has been
41
+ * defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.
42
+ */
43
+ queryFn?: Exclude<CreateInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>['queryFn'], SkipToken | undefined>;
44
+ };
45
+ /**
46
+ * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is set — `data` is
47
+ * never `undefined` (unless a `select` changes `TData` to include `undefined`).
48
+ *
49
+ * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
50
+ * @template TError - The type of errors your `queryFn` may throw.
51
+ * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
52
+ * the shape of all fetched pages plus their page params.
53
+ * @template TQueryKey - The type of your `queryKey`.
54
+ * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
55
+ */
56
+ export type DefinedInitialDataInfiniteOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> = CreateInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & {
57
+ /**
58
+ * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
59
+ * created or cached yet). If set to a function, the function will be called **once** during the shared/root
60
+ * query initialization, and be expected to synchronously return the initial data. Initial data is
61
+ * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
62
+ * cache.
63
+ */
64
+ initialData: NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>> | (() => NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>);
65
+ };
66
+ /**
67
+ * You can generally pass everything to `infiniteQueryOptions` that you can also pass to
68
+ * `injectInfiniteQuery`. These options can be shared across functions and imperative APIs such as
69
+ * `queryClient.fetchInfiniteQuery`. `options.queryKey` is required and is the query key to generate options
70
+ * for.
71
+ *
72
+ * This overload is selected when `initialData` is set.
73
+ *
74
+ * @see {@link injectInfiniteQuery} to run an infinite query with these options.
75
+ * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to
76
+ * `injectInfiniteQuery`, with `initialData` set.
77
+ * @returns The same options object, typed so that `queryKey` carries the inferred data type.
78
+ * @remarks See {@link injectInfiniteQuery} for examples that fetch further pages, from a button click or
79
+ * automatically as the user scrolls.
80
+ *
81
+ * @example
82
+ * ```angular-ts
83
+ * import { infiniteQueryOptions, injectInfiniteQuery } from '@tanstack/angular-query'
84
+ *
85
+ * export const projectsOptions = infiniteQueryOptions({
86
+ * queryKey: ['projects'],
87
+ * queryFn: ({ pageParam }) => fetchProjects(pageParam),
88
+ * initialPageParam: 0,
89
+ * getNextPageParam: (lastPage) => lastPage.nextId,
90
+ * initialData: { pages: [], pageParams: [] },
91
+ * })
92
+ *
93
+ * @Component({
94
+ * selector: 'projects',
95
+ * template: `
96
+ * <!-- `projectsQuery.data()` is never `undefined`, thanks to `initialData` — even if a
97
+ * refetch fails, so the list stays visible alongside the error. -->
98
+ * <ul>
99
+ * @for (page of projectsQuery.data().pages; track $index) {
100
+ * @for (project of page.projects; track project.id) {
101
+ * <li>{{ project.name }}</li>
102
+ * }
103
+ * }
104
+ * </ul>
105
+ * `,
106
+ * })
107
+ * export class Projects {
108
+ * readonly projectsQuery = injectInfiniteQuery(() => projectsOptions)
109
+ * }
110
+ * ```
111
+ */
112
+ export declare function infiniteQueryOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): DefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>;
113
+ /**
114
+ * You can generally pass everything to `infiniteQueryOptions` that you can also pass to
115
+ * `injectInfiniteQuery`. These options can be shared across functions and imperative APIs such as
116
+ * `queryClient.fetchInfiniteQuery`. `options.queryKey` is required and is the query key to generate options
117
+ * for.
118
+ *
119
+ * @returns The same options object, typed so that `queryKey` carries the inferred data type.
120
+ * @remarks See {@link injectInfiniteQuery} for examples that fetch further pages, from a button click or
121
+ * automatically as the user scrolls.
122
+ *
123
+ * @example
124
+ * A parameterized factory, so the same options object can be reused per `postId`:
125
+ * ```angular-ts
126
+ * import { infiniteQueryOptions, injectInfiniteQuery } from '@tanstack/angular-query'
127
+ *
128
+ * export const commentsOptions = (postId: string) =>
129
+ * infiniteQueryOptions({
130
+ * queryKey: ['post', postId, 'comments'],
131
+ * queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
132
+ * initialPageParam: 0,
133
+ * getNextPageParam: (lastPage) => lastPage.nextId,
134
+ * })
135
+ *
136
+ * @Component({
137
+ * selector: 'comments',
138
+ * template: `
139
+ * @if (commentsQuery.isPending()) {
140
+ * Loading...
141
+ * } @else if (commentsQuery.isError()) {
142
+ * <span>Error: {{ commentsQuery.error()?.message }}</span>
143
+ * } @else {
144
+ * <ul>
145
+ * @for (page of commentsQuery.data().pages; track $index) {
146
+ * @for (comment of page.comments; track comment.id) {
147
+ * <li>{{ comment.text }}</li>
148
+ * }
149
+ * }
150
+ * </ul>
151
+ * }
152
+ * `,
153
+ * })
154
+ * export class Comments {
155
+ * readonly postId = signal('1')
156
+ * readonly commentsQuery = injectInfiniteQuery(() => commentsOptions(this.postId()))
157
+ * }
158
+ * ```
159
+ *
160
+ * @see {@link injectInfiniteQuery} to run an infinite query with these options.
161
+ * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to
162
+ * `injectInfiniteQuery`.
163
+ */
164
+ export declare function infiniteQueryOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: UnusedSkipTokenInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): UnusedSkipTokenInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>;
165
+ /**
166
+ * You can generally pass everything to `infiniteQueryOptions` that you can also pass to
167
+ * `injectInfiniteQuery`. These options can be shared across functions and imperative APIs such as
168
+ * `queryClient.fetchInfiniteQuery`. `options.queryKey` is required and is the query key to generate options
169
+ * for.
170
+ *
171
+ * @returns The same options object, typed so that `queryKey` carries the inferred data type.
172
+ * @remarks See {@link injectInfiniteQuery} for examples that fetch further pages (from a button click or
173
+ * automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set.
174
+ *
175
+ * @example
176
+ * A parameterized factory, so the same options object can be reused per `postId`:
177
+ * ```angular-ts
178
+ * import { infiniteQueryOptions, injectInfiniteQuery } from '@tanstack/angular-query'
179
+ *
180
+ * export const commentsOptions = (postId: string) =>
181
+ * infiniteQueryOptions({
182
+ * queryKey: ['post', postId, 'comments'],
183
+ * queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
184
+ * initialPageParam: 0,
185
+ * getNextPageParam: (lastPage) => lastPage.nextId,
186
+ * })
187
+ *
188
+ * @Component({
189
+ * selector: 'comments',
190
+ * template: `
191
+ * @if (commentsQuery.isPending()) {
192
+ * Loading...
193
+ * } @else if (commentsQuery.isError()) {
194
+ * <span>Error: {{ commentsQuery.error()?.message }}</span>
195
+ * } @else {
196
+ * <ul>
197
+ * @for (page of commentsQuery.data().pages; track $index) {
198
+ * @for (comment of page.comments; track comment.id) {
199
+ * <li>{{ comment.text }}</li>
200
+ * }
201
+ * }
202
+ * </ul>
203
+ * }
204
+ * `,
205
+ * })
206
+ * export class Comments {
207
+ * readonly postId = signal('1')
208
+ * readonly commentsQuery = injectInfiniteQuery(() => commentsOptions(this.postId()))
209
+ * }
210
+ * ```
211
+ *
212
+ * @see {@link injectInfiniteQuery} to run an infinite query with these options.
213
+ * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to
214
+ * `injectInfiniteQuery`.
215
+ */
216
+ export declare function infiniteQueryOptions<TQueryFnData, TError = DefaultError, TData = InfiniteData<TQueryFnData>, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown>(options: UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>): UndefinedInitialDataInfiniteOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam> & QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>;
@@ -0,0 +1,7 @@
1
+ function infiniteQueryOptions(options) {
2
+ return options;
3
+ }
4
+ export {
5
+ infiniteQueryOptions
6
+ };
7
+ //# sourceMappingURL=infinite-query-options.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"infinite-query-options.mjs","sources":["../src/infinite-query-options.ts"],"sourcesContent":["import type {\n DefaultError,\n InfiniteData,\n InitialDataFunction,\n NonUndefinedGuard,\n OmitKeyof,\n QueryKey,\n QueryKeyWithDataTag,\n SkipToken,\n} from '@tanstack/query-core'\nimport type { CreateInfiniteQueryOptions } from './types'\n\n/**\n * The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set — `data`\n * may be `undefined` while the query is `pending`.\n *\n * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,\n * the shape of all fetched pages plus their page params.\n * @template TQueryKey - The type of your `queryKey`.\n * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.\n */\nexport type UndefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> = CreateInfiniteQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n> & {\n /**\n * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been\n * created or cached yet). If set to a function, the function will be called **once** during the shared/root\n * query initialization, and be expected to synchronously return the initial data. Initial data is\n * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the\n * cache.\n */\n initialData?:\n | undefined\n | NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>\n | InitialDataFunction<\n NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>\n >\n}\n\n/**\n * The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set and\n * `queryFn` is not `skipToken` — same as {@link UndefinedInitialDataInfiniteOptions}, but `queryFn` may not be\n * `skipToken`.\n *\n * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,\n * the shape of all fetched pages plus their page params.\n * @template TQueryKey - The type of your `queryKey`.\n * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.\n */\nexport type UnusedSkipTokenInfiniteOptions<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> = OmitKeyof<\n CreateInfiniteQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n 'queryFn'\n> & {\n /**\n * `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If\n * you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a\n * fetch that fails with \"Missing queryFn\" unless `enabled` is `false` or a default query function has been\n * defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.\n */\n queryFn?: Exclude<\n CreateInfiniteQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >['queryFn'],\n SkipToken | undefined\n >\n}\n\n/**\n * The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is set — `data` is\n * never `undefined` (unless a `select` changes `TData` to include `undefined`).\n *\n * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,\n * the shape of all fetched pages plus their page params.\n * @template TQueryKey - The type of your `queryKey`.\n * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.\n */\nexport type DefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n> = CreateInfiniteQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n> & {\n /**\n * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been\n * created or cached yet). If set to a function, the function will be called **once** during the shared/root\n * query initialization, and be expected to synchronously return the initial data. Initial data is\n * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the\n * cache.\n */\n initialData:\n | NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>\n | (() => NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>)\n}\n\n/**\n * You can generally pass everything to `infiniteQueryOptions` that you can also pass to\n * `injectInfiniteQuery`. These options can be shared across functions and imperative APIs such as\n * `queryClient.fetchInfiniteQuery`. `options.queryKey` is required and is the query key to generate options\n * for.\n *\n * This overload is selected when `initialData` is set.\n *\n * @see {@link injectInfiniteQuery} to run an infinite query with these options.\n * @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to\n * `injectInfiniteQuery`, with `initialData` set.\n * @returns The same options object, typed so that `queryKey` carries the inferred data type.\n * @remarks See {@link injectInfiniteQuery} for examples that fetch further pages, from a button click or\n * automatically as the user scrolls.\n *\n * @example\n * ```angular-ts\n * import { infiniteQueryOptions, injectInfiniteQuery } from '@tanstack/angular-query'\n *\n * export const projectsOptions = infiniteQueryOptions({\n * queryKey: ['projects'],\n * queryFn: ({ pageParam }) => fetchProjects(pageParam),\n * initialPageParam: 0,\n * getNextPageParam: (lastPage) => lastPage.nextId,\n * initialData: { pages: [], pageParams: [] },\n * })\n *\n * @Component({\n * selector: 'projects',\n * template: `\n * <!-- `projectsQuery.data()` is never `undefined`, thanks to `initialData` — even if a\n * refetch fails, so the list stays visible alongside the error. -->\n * <ul>\n * @for (page of projectsQuery.data().pages; track $index) {\n * @for (project of page.projects; track project.id) {\n * <li>{{ project.name }}</li>\n * }\n * }\n * </ul>\n * `,\n * })\n * export class Projects {\n * readonly projectsQuery = injectInfiniteQuery(() => projectsOptions)\n * }\n * ```\n */\nexport function infiniteQueryOptions<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n options: DefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n): DefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n> &\n QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>\n\n/**\n * You can generally pass everything to `infiniteQueryOptions` that you can also pass to\n * `injectInfiniteQuery`. These options can be shared across functions and imperative APIs such as\n * `queryClient.fetchInfiniteQuery`. `options.queryKey` is required and is the query key to generate options\n * for.\n *\n * @returns The same options object, typed so that `queryKey` carries the inferred data type.\n * @remarks See {@link injectInfiniteQuery} for examples that fetch further pages, from a button click or\n * automatically as the user scrolls.\n *\n * @example\n * A parameterized factory, so the same options object can be reused per `postId`:\n * ```angular-ts\n * import { infiniteQueryOptions, injectInfiniteQuery } from '@tanstack/angular-query'\n *\n * export const commentsOptions = (postId: string) =>\n * infiniteQueryOptions({\n * queryKey: ['post', postId, 'comments'],\n * queryFn: ({ pageParam }) => fetchComments(postId, pageParam),\n * initialPageParam: 0,\n * getNextPageParam: (lastPage) => lastPage.nextId,\n * })\n *\n * @Component({\n * selector: 'comments',\n * template: `\n * @if (commentsQuery.isPending()) {\n * Loading...\n * } @else if (commentsQuery.isError()) {\n * <span>Error: {{ commentsQuery.error()?.message }}</span>\n * } @else {\n * <ul>\n * @for (page of commentsQuery.data().pages; track $index) {\n * @for (comment of page.comments; track comment.id) {\n * <li>{{ comment.text }}</li>\n * }\n * }\n * </ul>\n * }\n * `,\n * })\n * export class Comments {\n * readonly postId = signal('1')\n * readonly commentsQuery = injectInfiniteQuery(() => commentsOptions(this.postId()))\n * }\n * ```\n *\n * @see {@link injectInfiniteQuery} to run an infinite query with these options.\n * @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to\n * `injectInfiniteQuery`.\n */\nexport function infiniteQueryOptions<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n options: UnusedSkipTokenInfiniteOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n): UnusedSkipTokenInfiniteOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n> &\n QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>\n\n/**\n * You can generally pass everything to `infiniteQueryOptions` that you can also pass to\n * `injectInfiniteQuery`. These options can be shared across functions and imperative APIs such as\n * `queryClient.fetchInfiniteQuery`. `options.queryKey` is required and is the query key to generate options\n * for.\n *\n * @returns The same options object, typed so that `queryKey` carries the inferred data type.\n * @remarks See {@link injectInfiniteQuery} for examples that fetch further pages (from a button click or\n * automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set.\n *\n * @example\n * A parameterized factory, so the same options object can be reused per `postId`:\n * ```angular-ts\n * import { infiniteQueryOptions, injectInfiniteQuery } from '@tanstack/angular-query'\n *\n * export const commentsOptions = (postId: string) =>\n * infiniteQueryOptions({\n * queryKey: ['post', postId, 'comments'],\n * queryFn: ({ pageParam }) => fetchComments(postId, pageParam),\n * initialPageParam: 0,\n * getNextPageParam: (lastPage) => lastPage.nextId,\n * })\n *\n * @Component({\n * selector: 'comments',\n * template: `\n * @if (commentsQuery.isPending()) {\n * Loading...\n * } @else if (commentsQuery.isError()) {\n * <span>Error: {{ commentsQuery.error()?.message }}</span>\n * } @else {\n * <ul>\n * @for (page of commentsQuery.data().pages; track $index) {\n * @for (comment of page.comments; track comment.id) {\n * <li>{{ comment.text }}</li>\n * }\n * }\n * </ul>\n * }\n * `,\n * })\n * export class Comments {\n * readonly postId = signal('1')\n * readonly commentsQuery = injectInfiniteQuery(() => commentsOptions(this.postId()))\n * }\n * ```\n *\n * @see {@link injectInfiniteQuery} to run an infinite query with these options.\n * @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to\n * `injectInfiniteQuery`.\n */\nexport function infiniteQueryOptions<\n TQueryFnData,\n TError = DefaultError,\n TData = InfiniteData<TQueryFnData>,\n TQueryKey extends QueryKey = QueryKey,\n TPageParam = unknown,\n>(\n options: UndefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n >,\n): UndefinedInitialDataInfiniteOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey,\n TPageParam\n> &\n QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>\n\nexport function infiniteQueryOptions(options: unknown) {\n return options\n}\n"],"names":[],"mappings":"AA8VO,SAAS,qBAAqB,SAAkB;AACrD,SAAO;AACT;"}
@@ -0,0 +1,5 @@
1
+ import { QueryKey, QueryObserver, QueryObserverOptions, QueryObserverResult } from '@tanstack/query-core';
2
+ /**
3
+ * Base implementation for `injectQuery` and `injectInfiniteQuery`.
4
+ */
5
+ export declare function injectBaseQuery<TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey>(optionsFn: () => QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>, Observer: typeof QueryObserver): readonly [import('@angular/core').Signal<QueryObserverResult<TData, TError>>, () => QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>];
@@ -0,0 +1,64 @@
1
+ import { inject, computed, untracked, effect } from "@angular/core";
2
+ import { QueryClient } from "@tanstack/query-core";
3
+ import { injectQueryZone } from "./utils/inject-query-zone.mjs";
4
+ import { injectIsRestoring } from "./inject-is-restoring.mjs";
5
+ import { injectPendingTasksLifecycle } from "./utils/inject-pending-tasks-lifecycle.mjs";
6
+ import { injectExternalStore } from "./utils/inject-external-store.mjs";
7
+ function injectBaseQuery(optionsFn, Observer) {
8
+ const outsideZone = injectQueryZone();
9
+ const queryClient = inject(QueryClient);
10
+ const isRestoring = injectIsRestoring();
11
+ const lifecycle = injectPendingTasksLifecycle();
12
+ const shouldBlockPendingTasks = (observer, result) => {
13
+ return observer.getCurrentQuery().state.fetchStatus !== "idle" || result.fetchStatus !== "idle" && result.isEnabled;
14
+ };
15
+ const defaultedOptionsSignal = computed(() => {
16
+ const defaultedOptions = queryClient.defaultQueryOptions(optionsFn());
17
+ defaultedOptions._optimisticResults = isRestoring() ? "isRestoring" : "optimistic";
18
+ defaultedOptions.notifyOnChangeProps = "all";
19
+ return defaultedOptions;
20
+ });
21
+ const observerSignal = computed(
22
+ () => new Observer(queryClient, untracked(defaultedOptionsSignal))
23
+ );
24
+ effect(() => {
25
+ const options = defaultedOptionsSignal();
26
+ outsideZone(() => untracked(() => observerSignal().setOptions(options)));
27
+ });
28
+ const resultSignal = injectExternalStore(() => {
29
+ const observer = observerSignal();
30
+ const restoring = isRestoring();
31
+ return {
32
+ getSnapshot: () => observer.getOptimisticResult(defaultedOptionsSignal()),
33
+ subscribe: restoring ? void 0 : (onStoreChange) => {
34
+ const unsubscribe = observer.subscribe(() => {
35
+ if (lifecycle.destroyed) return;
36
+ onStoreChange();
37
+ });
38
+ return () => {
39
+ lifecycle.setPending(false);
40
+ unsubscribe();
41
+ };
42
+ }
43
+ };
44
+ });
45
+ effect((onCleanup) => {
46
+ const result = resultSignal();
47
+ if (isRestoring()) {
48
+ lifecycle.setPending(false);
49
+ return;
50
+ }
51
+ lifecycle.setPending(shouldBlockPendingTasks(observerSignal(), result));
52
+ onCleanup(() => lifecycle.setPending(false));
53
+ });
54
+ const getObserver = () => untracked(() => {
55
+ const observer = observerSignal();
56
+ observer.setOptions(defaultedOptionsSignal());
57
+ return observer;
58
+ });
59
+ return [resultSignal, getObserver];
60
+ }
61
+ export {
62
+ injectBaseQuery
63
+ };
64
+ //# sourceMappingURL=inject-base-query.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inject-base-query.mjs","sources":["../src/inject-base-query.ts"],"sourcesContent":["import { computed, effect, inject, untracked } from '@angular/core'\nimport { QueryClient } from '@tanstack/query-core'\nimport { injectQueryZone } from './utils/inject-query-zone'\nimport { injectIsRestoring } from './inject-is-restoring'\nimport { injectPendingTasksLifecycle } from './utils/inject-pending-tasks-lifecycle'\nimport { injectExternalStore } from './utils/inject-external-store'\nimport type {\n QueryKey,\n QueryObserver,\n QueryObserverOptions,\n QueryObserverResult,\n} from '@tanstack/query-core'\n\n/**\n * Base implementation for `injectQuery` and `injectInfiniteQuery`.\n */\nexport function injectBaseQuery<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n>(\n optionsFn: () => QueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n Observer: typeof QueryObserver,\n) {\n const outsideZone = injectQueryZone()\n const queryClient = inject(QueryClient)\n const isRestoring = injectIsRestoring()\n const lifecycle = injectPendingTasksLifecycle()\n\n const shouldBlockPendingTasks = (\n observer: QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>,\n result: QueryObserverResult<TData, TError>,\n ) => {\n return (\n observer.getCurrentQuery().state.fetchStatus !== 'idle' ||\n (result.fetchStatus !== 'idle' && result.isEnabled)\n )\n }\n\n const defaultedOptionsSignal = computed(() => {\n const defaultedOptions = queryClient.defaultQueryOptions(optionsFn())\n defaultedOptions._optimisticResults = isRestoring()\n ? 'isRestoring'\n : 'optimistic'\n defaultedOptions.notifyOnChangeProps = 'all'\n return defaultedOptions\n })\n\n const observerSignal = computed(\n () => new Observer(queryClient, untracked(defaultedOptionsSignal)),\n )\n\n effect(() => {\n const options = defaultedOptionsSignal()\n outsideZone(() => untracked(() => observerSignal().setOptions(options)))\n })\n\n const resultSignal = injectExternalStore(() => {\n const observer = observerSignal()\n const restoring = isRestoring()\n return {\n getSnapshot: () => observer.getOptimisticResult(defaultedOptionsSignal()),\n subscribe: restoring\n ? undefined\n : (onStoreChange) => {\n const unsubscribe = observer.subscribe(() => {\n if (lifecycle.destroyed) return\n onStoreChange()\n })\n return () => {\n lifecycle.setPending(false)\n unsubscribe()\n }\n },\n }\n })\n\n effect((onCleanup) => {\n const result = resultSignal()\n if (isRestoring()) {\n lifecycle.setPending(false)\n return\n }\n\n lifecycle.setPending(shouldBlockPendingTasks(observerSignal(), result))\n onCleanup(() => lifecycle.setPending(false))\n })\n\n // Imperative methods use current options before starting work, even when\n // invoked before the subscription effect runs.\n const getObserver = () =>\n untracked(() => {\n const observer = observerSignal()\n observer.setOptions(defaultedOptionsSignal())\n return observer\n })\n\n return [resultSignal, getObserver] as const\n}\n"],"names":[],"mappings":";;;;;;AAgBO,SAAS,gBAOd,WAOA,UACA;AACA,QAAM,cAAc,gBAAA;AACpB,QAAM,cAAc,OAAO,WAAW;AACtC,QAAM,cAAc,kBAAA;AACpB,QAAM,YAAY,4BAAA;AAElB,QAAM,0BAA0B,CAC9B,UACA,WACG;AACH,WACE,SAAS,kBAAkB,MAAM,gBAAgB,UAChD,OAAO,gBAAgB,UAAU,OAAO;AAAA,EAE7C;AAEA,QAAM,yBAAyB,SAAS,MAAM;AAC5C,UAAM,mBAAmB,YAAY,oBAAoB,UAAA,CAAW;AACpE,qBAAiB,qBAAqB,YAAA,IAClC,gBACA;AACJ,qBAAiB,sBAAsB;AACvC,WAAO;AAAA,EACT,CAAC;AAED,QAAM,iBAAiB;AAAA,IACrB,MAAM,IAAI,SAAS,aAAa,UAAU,sBAAsB,CAAC;AAAA,EAAA;AAGnE,SAAO,MAAM;AACX,UAAM,UAAU,uBAAA;AAChB,gBAAY,MAAM,UAAU,MAAM,eAAA,EAAiB,WAAW,OAAO,CAAC,CAAC;AAAA,EACzE,CAAC;AAED,QAAM,eAAe,oBAAoB,MAAM;AAC7C,UAAM,WAAW,eAAA;AACjB,UAAM,YAAY,YAAA;AAClB,WAAO;AAAA,MACL,aAAa,MAAM,SAAS,oBAAoB,wBAAwB;AAAA,MACxE,WAAW,YACP,SACA,CAAC,kBAAkB;AACjB,cAAM,cAAc,SAAS,UAAU,MAAM;AAC3C,cAAI,UAAU,UAAW;AACzB,wBAAA;AAAA,QACF,CAAC;AACD,eAAO,MAAM;AACX,oBAAU,WAAW,KAAK;AAC1B,sBAAA;AAAA,QACF;AAAA,MACF;AAAA,IAAA;AAAA,EAER,CAAC;AAED,SAAO,CAAC,cAAc;AACpB,UAAM,SAAS,aAAA;AACf,QAAI,eAAe;AACjB,gBAAU,WAAW,KAAK;AAC1B;AAAA,IACF;AAEA,cAAU,WAAW,wBAAwB,eAAA,GAAkB,MAAM,CAAC;AACtE,cAAU,MAAM,UAAU,WAAW,KAAK,CAAC;AAAA,EAC7C,CAAC;AAID,QAAM,cAAc,MAClB,UAAU,MAAM;AACd,UAAM,WAAW,eAAA;AACjB,aAAS,WAAW,wBAAwB;AAC5C,WAAO;AAAA,EACT,CAAC;AAEH,SAAO,CAAC,cAAc,WAAW;AACnC;"}