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

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
@@ -0,0 +1,208 @@
1
+ import { DefaultError, InitialDataFunction, NonUndefinedGuard, OmitKeyof, QueryKey, QueryKeyWithDataTag, SkipToken } from '@tanstack/query-core';
2
+ import { CreateQueryOptions } from './types.js';
3
+ /**
4
+ * The options accepted by the `queryOptions` overload selected when no `initialData` is set — `data` may be
5
+ * `undefined` while the query is `pending`.
6
+ *
7
+ * @template TQueryFnData - The type your `queryFn` resolves to.
8
+ * @template TError - The type of errors your `queryFn` may throw.
9
+ * @template TData - The type `data` ends up as after `select` runs.
10
+ * @template TQueryKey - The type of your `queryKey`.
11
+ */
12
+ export type UndefinedInitialDataOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
13
+ /**
14
+ * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
15
+ * created or cached yet). If set to a function, the function will be called **once** during the shared/root
16
+ * query initialization, and be expected to synchronously return the initial data. Initial data is
17
+ * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
18
+ * cache.
19
+ */
20
+ initialData?: undefined | InitialDataFunction<NonUndefinedGuard<TQueryFnData>> | NonUndefinedGuard<TQueryFnData>;
21
+ };
22
+ /**
23
+ * The options accepted by the `queryOptions` overload selected when no `initialData` is set and `queryFn` is
24
+ * not `skipToken` — same as {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.
25
+ *
26
+ * @template TQueryFnData - The type your `queryFn` resolves to.
27
+ * @template TError - The type of errors your `queryFn` may throw.
28
+ * @template TData - The type `data` ends up as after `select` runs.
29
+ * @template TQueryKey - The type of your `queryKey`.
30
+ */
31
+ export type UnusedSkipTokenOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = OmitKeyof<CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'queryFn'> & {
32
+ /**
33
+ * `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If
34
+ * you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a
35
+ * fetch that fails with "Missing queryFn" unless `enabled` is `false` or a default query function has been
36
+ * defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.
37
+ */
38
+ queryFn?: Exclude<CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'], SkipToken | undefined>;
39
+ };
40
+ /**
41
+ * The options accepted by the `queryOptions` overload selected when `initialData` is set — `data` is never
42
+ * `undefined` (unless a `select` changes `TData` to include `undefined`).
43
+ *
44
+ * @template TQueryFnData - The type your `queryFn` resolves to.
45
+ * @template TError - The type of errors your `queryFn` may throw.
46
+ * @template TData - The type `data` ends up as after `select` runs.
47
+ * @template TQueryKey - The type of your `queryKey`.
48
+ */
49
+ export type DefinedInitialDataOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
50
+ initialData: NonUndefinedGuard<TQueryFnData> | (() => NonUndefinedGuard<TQueryFnData>);
51
+ };
52
+ /**
53
+ * You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options
54
+ * can be shared across functions and imperative APIs such as `queryClient.query`. `options.queryKey` is
55
+ * required and is the query key to generate options for.
56
+ *
57
+ * This overload is selected when `initialData` is set, so the resulting `data` is never `undefined` (unless
58
+ * a `select` changes `TData` to include `undefined`).
59
+ *
60
+ * @see {@link injectQuery} to run a query with these options.
61
+ * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
62
+ * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `injectQuery`,
63
+ * with `initialData` set.
64
+ * @returns The same options object, typed so that `queryKey` carries the inferred data type.
65
+ *
66
+ * @example
67
+ * ```angular-ts
68
+ * import { queryOptions, injectQuery } from '@tanstack/angular-query'
69
+ *
70
+ * export const postsOptions = queryOptions({
71
+ * queryKey: ['posts'],
72
+ * queryFn: fetchPosts,
73
+ * initialData: [],
74
+ * })
75
+ *
76
+ * @Component({
77
+ * selector: 'posts',
78
+ * template: `
79
+ * <!-- `postsQuery.data()` is never `undefined`, thanks to `initialData` — even if a refetch
80
+ * fails, so the list stays visible alongside the error. -->
81
+ * @if (postsQuery.isError()) {
82
+ * <span>Error: {{ postsQuery.error()?.message }}</span>
83
+ * }
84
+ * <ul>
85
+ * @for (post of postsQuery.data(); track post.id) {
86
+ * <li>{{ post.title }}</li>
87
+ * }
88
+ * </ul>
89
+ * `,
90
+ * })
91
+ * export class Posts {
92
+ * readonly postsQuery = injectQuery(() => postsOptions)
93
+ * }
94
+ * ```
95
+ */
96
+ export declare function queryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>): DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
97
+ /**
98
+ * You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options
99
+ * can be shared across functions and imperative APIs such as `queryClient.query`. `options.queryKey` is
100
+ * required and is the query key to generate options for.
101
+ *
102
+ * @see {@link injectQuery} to run a query with these options.
103
+ * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
104
+ * @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `injectQuery`.
105
+ * @returns The same options object, typed so that `queryKey` carries the inferred data type.
106
+ *
107
+ * @example
108
+ * A parameterized factory, so the same options object can be reused per `id`:
109
+ * ```angular-ts
110
+ * import { queryOptions, injectQuery } from '@tanstack/angular-query'
111
+ *
112
+ * export const postOptions = (id: string) =>
113
+ * queryOptions({
114
+ * queryKey: ['post', id],
115
+ * queryFn: () => fetchPost(id),
116
+ * })
117
+ *
118
+ * @Component({
119
+ * selector: 'post',
120
+ * template: `
121
+ * @if (postQuery.isPending()) {
122
+ * Loading...
123
+ * } @else if (postQuery.isError()) {
124
+ * <span>Error: {{ postQuery.error()?.message }}</span>
125
+ * } @else {
126
+ * <h1>{{ postQuery.data().title }}</h1>
127
+ * }
128
+ * `,
129
+ * })
130
+ * export class Post {
131
+ * readonly id = signal('1')
132
+ * readonly postQuery = injectQuery(() => postOptions(this.id()))
133
+ * }
134
+ * ```
135
+ */
136
+ export declare function queryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey>): UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey> & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
137
+ /**
138
+ * You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options
139
+ * can be shared across functions and imperative APIs such as `queryClient.query`. `options.queryKey` is
140
+ * required and is the query key to generate options for.
141
+ *
142
+ * @see {@link injectQuery} to run a query with these options.
143
+ * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
144
+ * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `injectQuery`.
145
+ * @returns The same options object, typed so that `queryKey` carries the inferred data type.
146
+ * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below.
147
+ *
148
+ * @example
149
+ * A parameterized factory, so the same options object can be reused per `id`:
150
+ * ```angular-ts
151
+ * import { queryOptions, injectQuery } from '@tanstack/angular-query'
152
+ *
153
+ * export const postOptions = (id: string) =>
154
+ * queryOptions({
155
+ * queryKey: ['post', id],
156
+ * queryFn: () => fetchPost(id),
157
+ * })
158
+ *
159
+ * @Component({
160
+ * selector: 'post',
161
+ * template: `
162
+ * @if (postQuery.isPending()) {
163
+ * Loading...
164
+ * } @else if (postQuery.isError()) {
165
+ * <span>Error: {{ postQuery.error()?.message }}</span>
166
+ * } @else {
167
+ * <h1>{{ postQuery.data().title }}</h1>
168
+ * }
169
+ * `,
170
+ * })
171
+ * export class Post {
172
+ * readonly id = signal('1')
173
+ * readonly postQuery = injectQuery(() => postOptions(this.id()))
174
+ * }
175
+ * ```
176
+ *
177
+ * @example
178
+ * A factory that disables the query, type safe, until `postId` is set:
179
+ * ```angular-ts
180
+ * import { queryOptions, skipToken, injectQuery } from '@tanstack/angular-query'
181
+ *
182
+ * export const postOptions = (postId: number | undefined) =>
183
+ * queryOptions({
184
+ * queryKey: ['post', postId],
185
+ * queryFn: postId != null ? () => fetchPost(postId) : skipToken,
186
+ * })
187
+ *
188
+ * @Component({
189
+ * selector: 'post',
190
+ * template: `
191
+ * @if (postId() == null) {
192
+ * Select a post
193
+ * } @else if (postQuery.isPending()) {
194
+ * Loading...
195
+ * } @else if (postQuery.isError()) {
196
+ * <span>Error: {{ postQuery.error()?.message }}</span>
197
+ * } @else {
198
+ * <h1>{{ postQuery.data().title }}</h1>
199
+ * }
200
+ * `,
201
+ * })
202
+ * export class Post {
203
+ * readonly postId = signal<number | undefined>(undefined)
204
+ * readonly postQuery = injectQuery(() => postOptions(this.postId()))
205
+ * }
206
+ * ```
207
+ */
208
+ export declare function queryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>): UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> & QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>;
@@ -0,0 +1,7 @@
1
+ function queryOptions(options) {
2
+ return options;
3
+ }
4
+ export {
5
+ queryOptions
6
+ };
7
+ //# sourceMappingURL=query-options.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-options.mjs","sources":["../src/query-options.ts"],"sourcesContent":["import type {\n DefaultError,\n InitialDataFunction,\n NonUndefinedGuard,\n OmitKeyof,\n QueryKey,\n QueryKeyWithDataTag,\n SkipToken,\n} from '@tanstack/query-core'\nimport type { CreateQueryOptions } from './types'\n\n/**\n * The options accepted by the `queryOptions` overload selected when no `initialData` is set — `data` may be\n * `undefined` while the query is `pending`.\n *\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport type UndefinedInitialDataOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {\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 | InitialDataFunction<NonUndefinedGuard<TQueryFnData>>\n | NonUndefinedGuard<TQueryFnData>\n}\n\n/**\n * The options accepted by the `queryOptions` overload selected when no `initialData` is set and `queryFn` is\n * not `skipToken` — same as {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.\n *\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport type UnusedSkipTokenOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\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 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'],\n SkipToken | undefined\n >\n}\n\n/**\n * The options accepted by the `queryOptions` overload selected when `initialData` is set — `data` is never\n * `undefined` (unless a `select` changes `TData` to include `undefined`).\n *\n * @template TQueryFnData - The type your `queryFn` resolves to.\n * @template TError - The type of errors your `queryFn` may throw.\n * @template TData - The type `data` ends up as after `select` runs.\n * @template TQueryKey - The type of your `queryKey`.\n */\nexport type DefinedInitialDataOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {\n initialData:\n | NonUndefinedGuard<TQueryFnData>\n | (() => NonUndefinedGuard<TQueryFnData>)\n}\n\n/**\n * You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options\n * can be shared across functions and imperative APIs such as `queryClient.query`. `options.queryKey` is\n * required and is the query key to generate options for.\n *\n * This overload is selected when `initialData` is set, so the resulting `data` is never `undefined` (unless\n * a `select` changes `TData` to include `undefined`).\n *\n * @see {@link injectQuery} to run a query with these options.\n * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.\n * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `injectQuery`,\n * with `initialData` set.\n * @returns The same options object, typed so that `queryKey` carries the inferred data type.\n *\n * @example\n * ```angular-ts\n * import { queryOptions, injectQuery } from '@tanstack/angular-query'\n *\n * export const postsOptions = queryOptions({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * initialData: [],\n * })\n *\n * @Component({\n * selector: 'posts',\n * template: `\n * <!-- `postsQuery.data()` is never `undefined`, thanks to `initialData` — even if a refetch\n * fails, so the list stays visible alongside the error. -->\n * @if (postsQuery.isError()) {\n * <span>Error: {{ postsQuery.error()?.message }}</span>\n * }\n * <ul>\n * @for (post of postsQuery.data(); track post.id) {\n * <li>{{ post.title }}</li>\n * }\n * </ul>\n * `,\n * })\n * export class Posts {\n * readonly postsQuery = injectQuery(() => postsOptions)\n * }\n * ```\n */\nexport function queryOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,\n): DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &\n QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>\n\n/**\n * You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options\n * can be shared across functions and imperative APIs such as `queryClient.query`. `options.queryKey` is\n * required and is the query key to generate options for.\n *\n * @see {@link injectQuery} to run a query with these options.\n * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.\n * @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `injectQuery`.\n * @returns The same options object, typed so that `queryKey` carries the inferred data type.\n *\n * @example\n * A parameterized factory, so the same options object can be reused per `id`:\n * ```angular-ts\n * import { queryOptions, injectQuery } from '@tanstack/angular-query'\n *\n * export const postOptions = (id: string) =>\n * queryOptions({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })\n *\n * @Component({\n * selector: 'post',\n * template: `\n * @if (postQuery.isPending()) {\n * Loading...\n * } @else if (postQuery.isError()) {\n * <span>Error: {{ postQuery.error()?.message }}</span>\n * } @else {\n * <h1>{{ postQuery.data().title }}</h1>\n * }\n * `,\n * })\n * export class Post {\n * readonly id = signal('1')\n * readonly postQuery = injectQuery(() => postOptions(this.id()))\n * }\n * ```\n */\nexport function queryOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey>,\n): UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey> &\n QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>\n\n/**\n * You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options\n * can be shared across functions and imperative APIs such as `queryClient.query`. `options.queryKey` is\n * required and is the query key to generate options for.\n *\n * @see {@link injectQuery} to run a query with these options.\n * @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.\n * @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `injectQuery`.\n * @returns The same options object, typed so that `queryKey` carries the inferred data type.\n * @remarks This is the only overload that accepts `queryFn: skipToken`, shown below.\n *\n * @example\n * A parameterized factory, so the same options object can be reused per `id`:\n * ```angular-ts\n * import { queryOptions, injectQuery } from '@tanstack/angular-query'\n *\n * export const postOptions = (id: string) =>\n * queryOptions({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })\n *\n * @Component({\n * selector: 'post',\n * template: `\n * @if (postQuery.isPending()) {\n * Loading...\n * } @else if (postQuery.isError()) {\n * <span>Error: {{ postQuery.error()?.message }}</span>\n * } @else {\n * <h1>{{ postQuery.data().title }}</h1>\n * }\n * `,\n * })\n * export class Post {\n * readonly id = signal('1')\n * readonly postQuery = injectQuery(() => postOptions(this.id()))\n * }\n * ```\n *\n * @example\n * A factory that disables the query, type safe, until `postId` is set:\n * ```angular-ts\n * import { queryOptions, skipToken, injectQuery } from '@tanstack/angular-query'\n *\n * export const postOptions = (postId: number | undefined) =>\n * queryOptions({\n * queryKey: ['post', postId],\n * queryFn: postId != null ? () => fetchPost(postId) : skipToken,\n * })\n *\n * @Component({\n * selector: 'post',\n * template: `\n * @if (postId() == null) {\n * Select a post\n * } @else if (postQuery.isPending()) {\n * Loading...\n * } @else if (postQuery.isError()) {\n * <span>Error: {{ postQuery.error()?.message }}</span>\n * } @else {\n * <h1>{{ postQuery.data().title }}</h1>\n * }\n * `,\n * })\n * export class Post {\n * readonly postId = signal<number | undefined>(undefined)\n * readonly postQuery = injectQuery(() => postOptions(this.postId()))\n * }\n * ```\n */\nexport function queryOptions<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,\n): UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &\n QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>\n\nexport function queryOptions(options: unknown) {\n return options\n}\n"],"names":[],"mappings":"AAiRO,SAAS,aAAa,SAAkB;AAC7C,SAAO;AACT;"}
@@ -0,0 +1,36 @@
1
+ import { QueryObserverResult } from '@tanstack/query-core';
2
+ import { ResourceSnapshot } from './utils/resource-types.js';
3
+ import { Resource, Signal } from '@angular/core';
4
+ export interface QueryResource<TValue> extends Resource<TValue> {
5
+ /**
6
+ * The current query state as a single snapshot.
7
+ */
8
+ readonly snapshot: Signal<ResourceSnapshot<TValue>>;
9
+ /**
10
+ * Requests a new query fetch only when the current query data is stale.
11
+ *
12
+ * Used for compatibility with Angular APIs that might want to reload a resource,
13
+ * like Signal Forms' validateAsync resource interface.
14
+ *
15
+ * @returns `true` if a reload was initiated, `false` if a reload was unnecessary or unsupported.
16
+ */
17
+ reload: () => boolean;
18
+ }
19
+ type QueryResourceSource<TValue> = {
20
+ readonly data: Signal<TValue>;
21
+ readonly status: Signal<QueryObserverResult['status']>;
22
+ readonly fetchStatus: Signal<QueryObserverResult['fetchStatus']>;
23
+ readonly error: Signal<unknown>;
24
+ readonly isStale: Signal<boolean>;
25
+ readonly refetch: () => unknown;
26
+ };
27
+ /**
28
+ * Converts an Angular Query result into Angular's Resource interface.
29
+ *
30
+ * Call this function once and reuse the returned resource.
31
+ *
32
+ * @param query An Angular Query or infinite-query result.
33
+ * @returns A Resource-compatible view of the query result.
34
+ */
35
+ export declare function toResource<TValue>(query: QueryResourceSource<TValue>): QueryResource<TValue>;
36
+ export {};
@@ -0,0 +1,70 @@
1
+ import { computed, untracked } from "@angular/core";
2
+ function toResource(query) {
3
+ const status = computed(() => {
4
+ const fetchStatus = query.fetchStatus();
5
+ const data = query.data();
6
+ if (fetchStatus === "fetching" || fetchStatus === "paused") {
7
+ return data === void 0 ? "loading" : "reloading";
8
+ }
9
+ switch (query.status()) {
10
+ case "success":
11
+ return "resolved";
12
+ case "error":
13
+ return "error";
14
+ case "pending":
15
+ return "idle";
16
+ }
17
+ });
18
+ const error = computed(() => {
19
+ return query.status() === "error" ? normalizeError(query.error()) : void 0;
20
+ });
21
+ const value = computed(() => {
22
+ if (status() === "error") {
23
+ throw error();
24
+ }
25
+ return query.data();
26
+ });
27
+ const snapshot = computed(() => {
28
+ const currentStatus = status();
29
+ if (currentStatus === "error") {
30
+ return { status: "error", error: error() };
31
+ }
32
+ return { status: currentStatus, value: query.data() };
33
+ });
34
+ const hasValue = (() => status() !== "error" && query.data() !== void 0);
35
+ return {
36
+ value,
37
+ status,
38
+ error,
39
+ snapshot,
40
+ isLoading: computed(() => {
41
+ const currentStatus = status();
42
+ return currentStatus === "loading" || currentStatus === "reloading";
43
+ }),
44
+ hasValue,
45
+ reload() {
46
+ const currentStatus = untracked(status);
47
+ if (currentStatus === "idle" || currentStatus === "loading" || currentStatus === "reloading") {
48
+ return false;
49
+ }
50
+ if (!untracked(query.isStale)) {
51
+ return false;
52
+ }
53
+ void query.refetch();
54
+ return true;
55
+ }
56
+ };
57
+ }
58
+ function normalizeError(error) {
59
+ if (isErrorLike(error)) {
60
+ return error;
61
+ }
62
+ return new Error(String(error), { cause: error });
63
+ }
64
+ function isErrorLike(error) {
65
+ return error instanceof Error || typeof error === "object" && error !== null && typeof error.name === "string" && typeof error.message === "string";
66
+ }
67
+ export {
68
+ toResource
69
+ };
70
+ //# sourceMappingURL=query-resource.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-resource.mjs","sources":["../src/query-resource.ts"],"sourcesContent":["import { computed, untracked } from '@angular/core'\nimport type { QueryObserverResult } from '@tanstack/query-core'\nimport type { ResourceSnapshot } from './utils/resource-types'\nimport type { Resource, ResourceStatus, Signal } from '@angular/core'\n\nexport interface QueryResource<TValue> extends Resource<TValue> {\n /**\n * The current query state as a single snapshot.\n */\n readonly snapshot: Signal<ResourceSnapshot<TValue>>\n\n /**\n * Requests a new query fetch only when the current query data is stale.\n *\n * Used for compatibility with Angular APIs that might want to reload a resource,\n * like Signal Forms' validateAsync resource interface.\n *\n * @returns `true` if a reload was initiated, `false` if a reload was unnecessary or unsupported.\n */\n reload: () => boolean\n}\n\ntype QueryResourceSource<TValue> = {\n readonly data: Signal<TValue>\n readonly status: Signal<QueryObserverResult['status']>\n readonly fetchStatus: Signal<QueryObserverResult['fetchStatus']>\n readonly error: Signal<unknown>\n readonly isStale: Signal<boolean>\n readonly refetch: () => unknown\n}\n\n/**\n * Converts an Angular Query result into Angular's Resource interface.\n *\n * Call this function once and reuse the returned resource.\n *\n * @param query An Angular Query or infinite-query result.\n * @returns A Resource-compatible view of the query result.\n */\nexport function toResource<TValue>(\n query: QueryResourceSource<TValue>,\n): QueryResource<TValue> {\n // Intentionally does not use resource from snapshot to have\n // support for the reload method for compatible libraries\n const status = computed<ResourceStatus>(() => {\n const fetchStatus = query.fetchStatus()\n const data = query.data()\n\n if (fetchStatus === 'fetching' || fetchStatus === 'paused') {\n return data === undefined ? 'loading' : 'reloading'\n }\n\n switch (query.status()) {\n case 'success':\n return 'resolved'\n case 'error':\n return 'error'\n case 'pending':\n return 'idle'\n }\n })\n\n const error = computed<Error | undefined>(() => {\n return query.status() === 'error'\n ? normalizeError(query.error())\n : undefined\n })\n\n const value = computed(() => {\n if (status() === 'error') {\n throw error()\n }\n\n return query.data()\n })\n\n const snapshot = computed<ResourceSnapshot<TValue>>(() => {\n const currentStatus = status()\n\n if (currentStatus === 'error') {\n return { status: 'error', error: error()! }\n }\n\n return { status: currentStatus, value: query.data() }\n })\n\n const hasValue = (() =>\n status() !== 'error' &&\n query.data() !== undefined) as QueryResource<TValue>['hasValue']\n\n return {\n value,\n status,\n error,\n snapshot,\n isLoading: computed(() => {\n const currentStatus = status()\n return currentStatus === 'loading' || currentStatus === 'reloading'\n }),\n hasValue,\n reload(): boolean {\n const currentStatus = untracked(status)\n if (\n currentStatus === 'idle' ||\n currentStatus === 'loading' ||\n currentStatus === 'reloading'\n ) {\n return false\n }\n\n if (!untracked(query.isStale)) {\n return false\n }\n\n void query.refetch()\n return true\n },\n }\n}\n\nfunction normalizeError(error: unknown): Error {\n if (isErrorLike(error)) {\n return error\n }\n\n return new Error(String(error), { cause: error })\n}\n\nfunction isErrorLike(error: unknown): error is Error {\n return (\n error instanceof Error ||\n (typeof error === 'object' &&\n error !== null &&\n typeof (error as Error).name === 'string' &&\n typeof (error as Error).message === 'string')\n )\n}\n"],"names":[],"mappings":";AAuCO,SAAS,WACd,OACuB;AAGvB,QAAM,SAAS,SAAyB,MAAM;AAC5C,UAAM,cAAc,MAAM,YAAA;AAC1B,UAAM,OAAO,MAAM,KAAA;AAEnB,QAAI,gBAAgB,cAAc,gBAAgB,UAAU;AAC1D,aAAO,SAAS,SAAY,YAAY;AAAA,IAC1C;AAEA,YAAQ,MAAM,UAAO;AAAA,MACnB,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,MACT,KAAK;AACH,eAAO;AAAA,IAAA;AAAA,EAEb,CAAC;AAED,QAAM,QAAQ,SAA4B,MAAM;AAC9C,WAAO,MAAM,aAAa,UACtB,eAAe,MAAM,MAAA,CAAO,IAC5B;AAAA,EACN,CAAC;AAED,QAAM,QAAQ,SAAS,MAAM;AAC3B,QAAI,OAAA,MAAa,SAAS;AACxB,YAAM,MAAA;AAAA,IACR;AAEA,WAAO,MAAM,KAAA;AAAA,EACf,CAAC;AAED,QAAM,WAAW,SAAmC,MAAM;AACxD,UAAM,gBAAgB,OAAA;AAEtB,QAAI,kBAAkB,SAAS;AAC7B,aAAO,EAAE,QAAQ,SAAS,OAAO,QAAM;AAAA,IACzC;AAEA,WAAO,EAAE,QAAQ,eAAe,OAAO,MAAM,OAAK;AAAA,EACpD,CAAC;AAED,QAAM,YAAY,MAChB,OAAA,MAAa,WACb,MAAM,WAAW;AAEnB,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW,SAAS,MAAM;AACxB,YAAM,gBAAgB,OAAA;AACtB,aAAO,kBAAkB,aAAa,kBAAkB;AAAA,IAC1D,CAAC;AAAA,IACD;AAAA,IACA,SAAkB;AAChB,YAAM,gBAAgB,UAAU,MAAM;AACtC,UACE,kBAAkB,UAClB,kBAAkB,aAClB,kBAAkB,aAClB;AACA,eAAO;AAAA,MACT;AAEA,UAAI,CAAC,UAAU,MAAM,OAAO,GAAG;AAC7B,eAAO;AAAA,MACT;AAEA,WAAK,MAAM,QAAA;AACX,aAAO;AAAA,IACT;AAAA,EAAA;AAEJ;AAEA,SAAS,eAAe,OAAuB;AAC7C,MAAI,YAAY,KAAK,GAAG;AACtB,WAAO;AAAA,EACT;AAEA,SAAO,IAAI,MAAM,OAAO,KAAK,GAAG,EAAE,OAAO,OAAO;AAClD;AAEA,SAAS,YAAY,OAAgC;AACnD,SACE,iBAAiB,SAChB,OAAO,UAAU,YAChB,UAAU,QACV,OAAQ,MAAgB,SAAS,YACjC,OAAQ,MAAgB,YAAY;AAE1C;"}
@@ -0,0 +1,10 @@
1
+ {
2
+ "$schema": "../../../node_modules/@angular-devkit/schematics/collection-schema.json",
3
+ "schematics": {
4
+ "ng-add": {
5
+ "description": "Configure TanStack Query in an Angular application.",
6
+ "factory": "./ng-add/index#ngAdd",
7
+ "schema": "./ng-add/schema.json"
8
+ }
9
+ }
10
+ }
@@ -0,0 +1,96 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ngAdd = ngAdd;
7
+ const utility_1 = require("@schematics/angular/utility");
8
+ const dependencies_1 = require("@schematics/angular/utility/dependencies");
9
+ const ng_ast_utils_1 = require("@schematics/angular/utility/ng-ast-utils");
10
+ const app_config_1 = require("@schematics/angular/utility/standalone/app_config");
11
+ const util_1 = require("@schematics/angular/utility/standalone/util");
12
+ const tasks_1 = require("@angular-devkit/schematics/tasks");
13
+ const schematics_1 = require("@angular-devkit/schematics");
14
+ const typescript_1 = __importDefault(require("typescript"));
15
+ // Replaced with package metadata by scripts/inject-schematic-package-info.js.
16
+ // The published schematic contains literal values and does not read package.json.
17
+ const PACKAGE_NAME = '@tanstack/angular-query';
18
+ const DEVTOOLS_PACKAGE_NAME = '@tanstack/angular-query-devtools';
19
+ const DEVTOOLS_PACKAGE_VERSION = '5.0.0-rc.0';
20
+ function hasPackageDependency(tree, name) {
21
+ const packageJsonPath = tree.exists('/package.json')
22
+ ? '/package.json'
23
+ : 'package.json';
24
+ const packageJson = JSON.parse(tree.readText(packageJsonPath));
25
+ return ['dependencies', 'devDependencies', 'optionalDependencies'].some((dependencyType) => packageJson[dependencyType]?.[name] !== undefined);
26
+ }
27
+ function addDevtoolsDependency() {
28
+ return (tree, context) => {
29
+ if (hasPackageDependency(tree, DEVTOOLS_PACKAGE_NAME))
30
+ return tree;
31
+ (0, dependencies_1.addPackageJsonDependency)(tree, {
32
+ type: dependencies_1.NodeDependencyType.Default,
33
+ name: DEVTOOLS_PACKAGE_NAME,
34
+ version: DEVTOOLS_PACKAGE_VERSION,
35
+ overwrite: false,
36
+ });
37
+ context.addTask(new tasks_1.NodePackageInstallTask());
38
+ return tree;
39
+ };
40
+ }
41
+ function hasProviderCall(tree, sourcePath) {
42
+ const source = typescript_1.default.createSourceFile(sourcePath, tree.readText(sourcePath), typescript_1.default.ScriptTarget.Latest, true);
43
+ const localProviderNames = new Set();
44
+ for (const statement of source.statements) {
45
+ if (!typescript_1.default.isImportDeclaration(statement) ||
46
+ !typescript_1.default.isStringLiteral(statement.moduleSpecifier) ||
47
+ statement.moduleSpecifier.text !== PACKAGE_NAME ||
48
+ !statement.importClause?.namedBindings ||
49
+ !typescript_1.default.isNamedImports(statement.importClause.namedBindings)) {
50
+ continue;
51
+ }
52
+ for (const element of statement.importClause.namedBindings.elements) {
53
+ if ((element.propertyName ?? element.name).text === 'provideTanStackQuery') {
54
+ localProviderNames.add(element.name.text);
55
+ }
56
+ }
57
+ }
58
+ if (localProviderNames.size === 0)
59
+ return false;
60
+ let found = false;
61
+ const visit = (node) => {
62
+ if (typescript_1.default.isCallExpression(node) &&
63
+ typescript_1.default.isIdentifier(node.expression) &&
64
+ localProviderNames.has(node.expression.text)) {
65
+ found = true;
66
+ return;
67
+ }
68
+ if (!found)
69
+ typescript_1.default.forEachChild(node, visit);
70
+ };
71
+ visit(source);
72
+ return found;
73
+ }
74
+ async function hasRootQueryProvider(tree, projectName) {
75
+ const mainFilePath = await (0, util_1.getMainFilePath)(tree, projectName);
76
+ const rootFilePath = (0, ng_ast_utils_1.isStandaloneApp)(tree, mainFilePath)
77
+ ? ((0, app_config_1.findAppConfig)((0, util_1.findBootstrapApplicationCall)(tree, mainFilePath), tree, mainFilePath)?.filePath ?? mainFilePath)
78
+ : (0, ng_ast_utils_1.getAppModulePath)(tree, mainFilePath);
79
+ return hasProviderCall(tree, rootFilePath);
80
+ }
81
+ function addQueryProvider(project) {
82
+ return async (tree) => {
83
+ if (await hasRootQueryProvider(tree, project))
84
+ return tree;
85
+ return (0, utility_1.addRootProvider)(project, ({ code, external }) => code `${external('provideTanStackQuery', PACKAGE_NAME)}(() => new ${external('QueryClient', PACKAGE_NAME)}(), ${external('withDevtools', DEVTOOLS_PACKAGE_NAME)}())`);
86
+ };
87
+ }
88
+ /**
89
+ * Configures TanStack Query at the application root.
90
+ *
91
+ * The QueryClient factory is resolved by each root injector, preventing query
92
+ * caches from being shared between SSR requests.
93
+ */
94
+ function ngAdd(options) {
95
+ return (0, schematics_1.chain)([addDevtoolsDependency(), addQueryProvider(options.project)]);
96
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,17 @@
1
+ {
2
+ "$schema": "http://json-schema.org/schema",
3
+ "$id": "TanStackAngularQueryNgAdd",
4
+ "title": "TanStack Angular Query ng-add options",
5
+ "type": "object",
6
+ "properties": {
7
+ "project": {
8
+ "type": "string",
9
+ "description": "The Angular project to configure.",
10
+ "$default": {
11
+ "$source": "projectName"
12
+ }
13
+ }
14
+ },
15
+ "required": ["project"],
16
+ "additionalProperties": false
17
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }