@tanstack/angular-query 5.0.0 → 5.108.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.
@@ -1 +1 @@
1
- {"version":3,"file":"inject-queries.mjs","names":[],"sources":["../src/inject-queries.ts"],"sourcesContent":["import {\n assertInInjectionContext,\n computed,\n effect,\n inject,\n untracked,\n} from '@angular/core'\nimport { QueriesObserver, QueryClient } from '@tanstack/query-core'\nimport { injectIsRestoring } from './inject-is-restoring'\nimport { injectExternalStore } from './utils/inject-external-store'\nimport { injectPendingTasksLifecycle } from './utils/inject-pending-tasks-lifecycle'\nimport { injectQueryZone } from './utils/inject-query-zone'\nimport { queryResultFields } from './utils/result-fields'\nimport { signalProxy } from './utils/signal-proxy'\nimport type { Signal } from '@angular/core'\nimport type {\n QueryObserverOptions,\n QueryObserverResult,\n} from '@tanstack/query-core'\nimport type {\n InjectQueriesOptions,\n QueriesResults,\n} from './inject-queries.types'\n\n/**\n * Injects multiple queries that run in parallel and react to Angular signals.\n * @param optionsFn - A function that returns the queries' options. Similar to `computed` from Angular,\n * this function runs in the reactive context, so signals read inside it drive the queries.\n * @returns A signal containing the query results in the same order as the input queries.\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/parallel-queries\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'users',\n * template: `\n * @for (query of userQueries(); track $index) {\n * @if (query.isSuccess()) {\n * <p>{{ query.data().name }}</p>\n * }\n * }\n * `,\n * })\n * export class UsersComponent {\n * readonly users = input.required<Array<User>>()\n *\n * readonly userQueries = injectQueries(() => ({\n * queries: this.users().map((user) => ({\n * queryKey: ['user', user.id],\n * queryFn: () => fetchUserById(user.id),\n * })),\n * }))\n * }\n * ```\n */\nexport function injectQueries<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n>(\n optionsFn: () => InjectQueriesOptions<T, TCombinedResult>,\n): Signal<TCombinedResult> {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectQueries)\n }\n const outsideZone = injectQueryZone()\n const queryClient = inject(QueryClient)\n const isRestoring = injectIsRestoring()\n const lifecycle = injectPendingTasksLifecycle()\n\n const optionsSignal = computed(optionsFn)\n\n const defaultedQueries = computed(() => {\n return optionsSignal().queries.map((opts) => {\n const defaultedOptions = queryClient.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n defaultedOptions._optimisticResults = isRestoring()\n ? 'isRestoring'\n : 'optimistic'\n defaultedOptions.notifyOnChangeProps = 'all'\n\n return defaultedOptions\n })\n })\n\n const shouldBlockPendingTasks = (\n observer: QueriesObserver<TCombinedResult>,\n results: Array<QueryObserverResult>,\n ) => {\n const queries = observer.getQueries()\n\n return results.some((result, index) => {\n return (\n queries[index]?.state.fetchStatus !== 'idle' ||\n (result.fetchStatus !== 'idle' && result.isEnabled)\n )\n })\n }\n\n const observerSignal = computed(\n () =>\n new QueriesObserver<TCombinedResult>(\n queryClient,\n untracked(defaultedQueries),\n ),\n )\n\n effect(() => {\n const queries = defaultedQueries()\n outsideZone(() => untracked(() => observerSignal().setQueries(queries)))\n })\n\n // Methods address the current array slot, including methods handed to combine.\n const refetches: Array<QueryObserverResult['refetch']> = []\n const getRefetch = (index: number): QueryObserverResult['refetch'] =>\n (refetches[index] ??= (options) =>\n outsideZone(() =>\n untracked(() => {\n const observer = observerSignal()\n observer.setQueries(defaultedQueries())\n const queryObserver = observer.getObservers()[index]\n if (!queryObserver) {\n return Promise.reject(\n new Error(`Cannot refetch removed query at index ${index}`),\n )\n }\n return queryObserver.refetch(options)\n }),\n ))\n\n const resultSignal = injectExternalStore(() => {\n const observer = observerSignal()\n const restoring = isRestoring()\n return {\n getSnapshot: () => {\n const results = observer.getOptimisticResult(\n defaultedQueries(),\n undefined,\n )[0]\n refetches.length = results.length\n return results.map((result, index) => ({\n ...result,\n refetch: getRefetch(index),\n }))\n },\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 results = resultSignal()\n if (isRestoring()) {\n lifecycle.setPending(false)\n return\n }\n\n lifecycle.setPending(shouldBlockPendingTasks(observerSignal(), results))\n onCleanup(() => lifecycle.setPending(false))\n })\n\n const createResultProxy = (index: number) => {\n const resultAtIndexSignal = computed(() => resultSignal()[index]!)\n return Object.assign(signalProxy(resultAtIndexSignal, queryResultFields), {\n refetch: getRefetch(index),\n })\n }\n\n const resultProxies: Array<ReturnType<typeof createResultProxy>> = []\n const proxiedResultsSignal = computed(() => {\n const results = resultSignal()\n resultProxies.length = results.length\n\n return results.map((_, index) => {\n return (resultProxies[index] ??= createResultProxy(index))\n })\n })\n\n // Combine in Angular's tracked computation. Core must notify for every raw\n // result change, including changes a previous combine function ignored.\n return computed(() => {\n const result = resultSignal()\n const { combine } = optionsSignal()\n\n if (combine)\n return combine(result as Parameters<NonNullable<typeof combine>>[0])\n\n return proxiedResultsSignal() as unknown as TCombinedResult\n })\n}\n"],"mappings":"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"}
1
+ {"version":3,"file":"inject-queries.mjs","names":[],"sources":["../src/inject-queries.ts"],"sourcesContent":["import {\n assertInInjectionContext,\n computed,\n effect,\n inject,\n untracked,\n} from '@angular/core'\nimport { QueriesObserver, QueryClient } from '@tanstack/query-core'\nimport { injectIsRestoring } from './inject-is-restoring'\nimport { injectExternalStore } from './utils/inject-external-store'\nimport { injectPendingTasksLifecycle } from './utils/inject-pending-tasks-lifecycle'\nimport { injectQueryZone } from './utils/inject-query-zone'\nimport { queryResultFields } from './utils/result-fields'\nimport { signalProxy } from './utils/signal-proxy'\nimport type { Signal } from '@angular/core'\nimport type {\n QueryObserverOptions,\n QueryObserverResult,\n} from '@tanstack/query-core'\nimport type {\n InjectQueriesOptions,\n QueriesResults,\n} from './inject-queries.types'\n\n/**\n * Injects a signal to fetch a variable number of queries.\n *\n * The `queries` key accepts an array with query option objects mostly identical to `injectQuery`'s. Having\n * the same query key more than once in the array of query objects may cause some data to be shared between\n * queries. To avoid this, consider de-duplicating the queries and map the results back to the desired\n * structure.\n *\n * The `combine` option can be used to combine the results of the queries into a single value.\n * @param optionsFn - A function returning the queries' options — an array of query option objects under\n * `queries`, and an optional `combine`. Similar to `computed` from Angular, this function runs in the\n * reactive context, so signals read inside it (e.g. to build the `queries` array) drive the queries.\n * @returns A `Signal` with the combined result. Without `combine`, this is an array with all the query\n * results, in the same order as the input. When `combine` is provided, this is the value returned by\n * `combine` instead.\n * @remarks Unlike `injectQuery`, `injectQueries` cannot infer the `data` argument of an _inline_ `select`\n * from its sibling `queryFn`. Because `injectQueries` infers the type of the whole `queries` array at once,\n * the `select` parameter of a query object written inline cannot be contextually typed from that same\n * object's `queryFn`, so it falls back to `unknown` — a\n * [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate the `select`\n * parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in a single\n * object _before_ it reaches `injectQueries`, to work around this — see the example below.\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/parallel-queries\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * <ul>\n * @for (query of postQueries(); track $index) {\n * @if (query.isPending()) {\n * <li>Loading...</li>\n * } @else if (query.isError()) {\n * <li>Error: {{ query.error()?.message }}</li>\n * } @else {\n * <li>{{ query.data().title }}</li>\n * }\n * }\n * </ul>\n * `,\n * })\n * export class Posts {\n * readonly ids = signal([1, 2, 3])\n *\n * readonly postQueries = injectQueries(() => ({\n * queries: this.ids().map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * staleTime: Infinity,\n * })),\n * }))\n * }\n * ```\n * @example\n * Combining results into a single value:\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * @if (combined().isPending) {\n * Loading...\n * } @else if (combined().isError) {\n * Error loading posts\n * } @else {\n * <ul>\n * @for (post of combined().data; track post?.id) {\n * <li>{{ post?.title }}</li>\n * }\n * </ul>\n * }\n * `,\n * })\n * export class Posts {\n * readonly ids = signal([1, 2, 3])\n *\n * readonly combined = injectQueries(() => ({\n * queries: this.ids().map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })),\n * combine: (postQueries) => ({\n * data: postQueries.map((query) => query.data),\n * isPending: postQueries.some((query) => query.isPending),\n * isError: postQueries.some((query) => query.isError),\n * }),\n * }))\n * }\n * ```\n * @example\n * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding\n * `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is\n * resolved before it reaches `injectQueries`:\n * ```angular-ts\n * const postOptions = (id: number) =>\n * queryOptions({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })\n *\n * @Component({\n * selector: 'post-title',\n * template: `<h1>{{ fixed()[0].data() }}</h1>`,\n * })\n * export class PostTitle {\n * readonly id = signal(1)\n *\n * readonly broken = injectQueries(() => ({\n * queries: [\n * {\n * ...postOptions(this.id()),\n * // ❌ `data` is `unknown` here\n * select: (data) => data.title,\n * },\n * ],\n * }))\n *\n * readonly fixed = injectQueries(() => ({\n * queries: [\n * queryOptions({\n * ...postOptions(this.id()),\n * // ✅ `data` is `Post`\n * select: (data) => data.title,\n * }),\n * ],\n * }))\n * }\n * ```\n */\nexport function injectQueries<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n>(\n optionsFn: () => InjectQueriesOptions<T, TCombinedResult>,\n): Signal<TCombinedResult> {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectQueries)\n }\n const outsideZone = injectQueryZone()\n const queryClient = inject(QueryClient)\n const isRestoring = injectIsRestoring()\n const lifecycle = injectPendingTasksLifecycle()\n\n const optionsSignal = computed(optionsFn)\n\n const defaultedQueries = computed(() => {\n return optionsSignal().queries.map((opts) => {\n const defaultedOptions = queryClient.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n defaultedOptions._optimisticResults = isRestoring()\n ? 'isRestoring'\n : 'optimistic'\n defaultedOptions.notifyOnChangeProps = 'all'\n\n return defaultedOptions\n })\n })\n\n const shouldBlockPendingTasks = (\n observer: QueriesObserver<TCombinedResult>,\n results: Array<QueryObserverResult>,\n ) => {\n const queries = observer.getQueries()\n\n return results.some((result, index) => {\n return (\n queries[index]?.state.fetchStatus !== 'idle' ||\n (result.fetchStatus !== 'idle' && result.isEnabled)\n )\n })\n }\n\n const observerSignal = computed(\n () =>\n new QueriesObserver<TCombinedResult>(\n queryClient,\n untracked(defaultedQueries),\n ),\n )\n\n effect(() => {\n const queries = defaultedQueries()\n outsideZone(() => untracked(() => observerSignal().setQueries(queries)))\n })\n\n // Methods address the current array slot, including methods handed to combine.\n const refetches: Array<QueryObserverResult['refetch']> = []\n const getRefetch = (index: number): QueryObserverResult['refetch'] =>\n (refetches[index] ??= (options) =>\n outsideZone(() =>\n untracked(() => {\n const observer = observerSignal()\n observer.setQueries(defaultedQueries())\n const queryObserver = observer.getObservers()[index]\n if (!queryObserver) {\n return Promise.reject(\n new Error(`Cannot refetch removed query at index ${index}`),\n )\n }\n return queryObserver.refetch(options)\n }),\n ))\n\n const resultSignal = injectExternalStore(() => {\n const observer = observerSignal()\n const restoring = isRestoring()\n return {\n getSnapshot: () => {\n const results = observer.getOptimisticResult(\n defaultedQueries(),\n undefined,\n )[0]\n refetches.length = results.length\n return results.map((result, index) => ({\n ...result,\n refetch: getRefetch(index),\n }))\n },\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 results = resultSignal()\n if (isRestoring()) {\n lifecycle.setPending(false)\n return\n }\n\n lifecycle.setPending(shouldBlockPendingTasks(observerSignal(), results))\n onCleanup(() => lifecycle.setPending(false))\n })\n\n const createResultProxy = (index: number) => {\n const resultAtIndexSignal = computed(() => resultSignal()[index]!)\n return Object.assign(signalProxy(resultAtIndexSignal, queryResultFields), {\n refetch: getRefetch(index),\n })\n }\n\n const resultProxies: Array<ReturnType<typeof createResultProxy>> = []\n const proxiedResultsSignal = computed(() => {\n const results = resultSignal()\n resultProxies.length = results.length\n\n return results.map((_, index) => {\n return (resultProxies[index] ??= createResultProxy(index))\n })\n })\n\n // Combine in Angular's tracked computation. Core must notify for every raw\n // result change, including changes a previous combine function ignored.\n return computed(() => {\n const result = resultSignal()\n const { combine } = optionsSignal()\n\n if (combine)\n return combine(result as Parameters<NonNullable<typeof combine>>[0])\n\n return proxiedResultsSignal() as unknown as TCombinedResult\n })\n}\n"],"mappings":"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"}
@@ -69,7 +69,16 @@ type InferDataAndError<T> = T extends {
69
69
  type GetCreateQueryResult<T> = GenericGetDefinedOrUndefinedQueryResult<T, InferDataAndError<T>['data'], CreateQueryResult<InferDataAndError<T>['data'], InferDataAndError<T>['error']>, DefinedCreateQueryResult<InferDataAndError<T>['data'], InferDataAndError<T>['error']>>;
70
70
  type GetQueryObserverResult<T> = GenericGetDefinedOrUndefinedQueryResult<T, InferDataAndError<T>['data'], QueryObserverResult<InferDataAndError<T>['data'], InferDataAndError<T>['error']>, DefinedQueryObserverResult<InferDataAndError<T>['data'], InferDataAndError<T>['error']>>;
71
71
  /**
72
- * Maps a tuple of query descriptions to the options accepted by `injectQueries`.
72
+ * The `queries` array accepted by `injectQueries`. Recursively unwraps each tuple element so every entry's
73
+ * `queryFn`/`select` are inferred individually, up to 20 elements — past that, tuple
74
+ * recursion falls back to a single homogeneous options type. An opaque array (e.g. `unknown[]`) is returned
75
+ * as-is; a non-tuple array of a known element type is mapped to that element type instead, with no such
76
+ * limit.
77
+ * @template T - The type of the `queries` array as written at the call site.
78
+ * @template TResults - The internal accumulator that this type builds during recursion. It is not meant to
79
+ * be set explicitly.
80
+ * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
81
+ * meant to be set explicitly.
73
82
  */
74
83
  export type QueriesOptions<T extends Array<any>, TResults extends Array<any> = [], TDepth extends ReadonlyArray<number> = []> = TDepth['length'] extends MAXIMUM_DEPTH ? Array<QueryObserverOptionsForCreateQueries> : T extends [] ? [] : T extends [infer Head] ? [...TResults, GetCreateQueryOptionsForCreateQueries<Head>] : T extends [infer Head, ...infer Tails] ? QueriesOptions<[
75
84
  ...Tails
@@ -81,7 +90,15 @@ export type QueriesOptions<T extends Array<any>, TResults extends Array<any> = [
81
90
  1
82
91
  ]> : ReadonlyArray<unknown> extends T ? T : T extends Array<QueryObserverOptionsForCreateQueries<infer TQueryFnData, infer TError, infer TData, infer TQueryKey>> ? Array<QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData, TQueryKey>> : Array<QueryObserverOptionsForCreateQueries>;
83
92
  /**
84
- * Maps a tuple of query descriptions to their individual signal-backed results.
93
+ * The result type returned by `injectQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}:
94
+ * each tuple element's result type is inferred individually, up to 20 elements — past that, tuple recursion
95
+ * falls back to a single homogeneous {@link CreateQueryResult} type. A non-tuple array is mapped per-element
96
+ * instead, with no such limit — every entry keeps its individually inferred type regardless of array length.
97
+ * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.
98
+ * @template TResults - The internal accumulator that this type builds during recursion. It is not meant to
99
+ * be set explicitly.
100
+ * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
101
+ * meant to be set explicitly.
85
102
  */
86
103
  export type QueriesResults<T extends Array<any>, TResults extends Array<any> = [], TDepth extends ReadonlyArray<number> = []> = TDepth['length'] extends MAXIMUM_DEPTH ? Array<CreateQueryResult> : T extends [] ? [] : T extends [infer Head] ? [...TResults, GetCreateQueryResult<Head>] : T extends [infer Head, ...infer Tails] ? QueriesResults<[
87
104
  ...Tails
@@ -106,11 +123,13 @@ type RawQueriesResults<T extends Array<any>, TResults extends Array<any> = [], T
106
123
  [K in keyof T]: GetQueryObserverResult<T[K]>;
107
124
  };
108
125
  /**
109
- * A reactive group of query options and an optional projection of their combined results.
126
+ * The options for `injectQueries`: the `queries` to run, and an optional `combine` function that
127
+ * derives a single result from all the query results.
110
128
  */
111
129
  export interface InjectQueriesOptions<T extends Array<any>, TCombinedResult = QueriesResults<T>> {
112
130
  /**
113
- * The ordered query options to observe; entries can be added, removed, or replaced reactively.
131
+ * The array of query options to run, one query per element. Entries can be added, removed, or replaced
132
+ * reactively.
114
133
  */
115
134
  queries: readonly [...QueriesOptions<T>] | readonly [
116
135
  ...{
@@ -118,7 +137,8 @@ export interface InjectQueriesOptions<T extends Array<any>, TCombinedResult = Qu
118
137
  }
119
138
  ];
120
139
  /**
121
- * Projects the current plain observer results into a single reactively computed value.
140
+ * Combines the plain results of all the queries into a single value, which `injectQueries` returns
141
+ * instead of the results array. The value is recomputed reactively.
122
142
  */
123
143
  combine?: (result: RawQueriesResults<T>) => TCombinedResult;
124
144
  }
package/inject-query.d.ts CHANGED
@@ -104,6 +104,7 @@ export declare function injectQuery<TQueryFnData = unknown, TError = DefaultErro
104
104
  * readonly postsQuery = injectQuery(() => ({
105
105
  * queryKey: ['posts', this.filter()],
106
106
  * queryFn: () => fetchPosts(this.filter()),
107
+ * // Signals can be combined with expressions
107
108
  * enabled: !!this.filter(),
108
109
  * }))
109
110
  * }
@@ -115,7 +116,8 @@ export declare function injectQuery<TQueryFnData = unknown, TError = DefaultErro
115
116
  * overloads above, so whether `data` is defined can't be inferred from the call site — useful when wrapping
116
117
  * `injectQuery` in your own helper function that forwards caller-provided options.
117
118
  * @param optionsFn - A function that returns query options. Similar to `computed` from Angular, this
118
- * function runs in the reactive context, so signals read inside it drive the query.
119
+ * function runs in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive
120
+ * the query.
119
121
  * @returns The query result.
120
122
  * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
121
123
  */
@@ -1 +1 @@
1
- {"version":3,"file":"inject-query.mjs","names":[],"sources":["../src/inject-query.ts"],"sourcesContent":["import { assertInInjectionContext, untracked } from '@angular/core'\nimport { QueryObserver } from '@tanstack/query-core'\nimport { injectBaseQuery } from './inject-base-query'\nimport { injectQueryZone } from './utils/inject-query-zone'\nimport { queryResultFields } from './utils/result-fields'\nimport { signalProxy } from './utils/signal-proxy'\nimport type {\n DefaultError,\n QueryKey,\n RefetchOptions,\n} from '@tanstack/query-core'\nimport type {\n DefinedInitialDataOptions,\n UndefinedInitialDataOptions,\n} from './query-options'\nimport type {\n CreateQueryOptions,\n CreateQueryResult,\n DefinedCreateQueryResult,\n} from './types'\n\n/**\n * This overload is selected when `initialData` is known to be defined on the options returned by `optionsFn`, so the\n * resulting `data` signal is never `undefined` (unless a `select` changes `TData` to include `undefined`).\n * @param optionsFn - A function returning the {@link DefinedInitialDataOptions} to use — everything you\n * can pass to `injectQuery`, with `initialData` known to be defined. Similar to `computed` from Angular, this function runs\n * in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.\n * @returns The query result, typed so that `data` is never `undefined` (unless a `select` changes `TData` to\n * include `undefined`). At runtime, `data` is still `undefined` if `select` throws on its first call.\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries\n * @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like\n * `queryClient.query`.\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * <!-- `postsQuery.data()` is `Post[]`, never `undefined`, thanks to `initialData` — even if a\n * refetch 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(() => ({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * initialData: [],\n * }))\n * }\n * ```\n */\nexport function injectQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n optionsFn: () => DefinedInitialDataOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >,\n): DefinedCreateQueryResult<TData, TError>\n\n/**\n * Injects a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.\n * @param optionsFn - A function returning the {@link UndefinedInitialDataOptions} to use — everything\n * you can pass to `injectQuery`. Similar to `computed` from Angular, this function runs in the reactive\n * context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.\n * @returns The query result. `status()` is `'error'` if the query has an error from a fetch that failed\n * after its retries or if `select` threw, `'success'` if the query has cached data (even if `select`\n * returns `undefined`) or data from `placeholderData`, and `'pending'` otherwise.\n * `isPending`/`isSuccess`/`isError` are type-guard methods for convenience.\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries\n * @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like\n * `queryClient.query`.\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * @if (postsQuery.isPending()) {\n * Loading...\n * } @else if (postsQuery.isError()) {\n * <span>Error: {{ postsQuery.error()?.message }}</span>\n * } @else {\n * <ul>\n * @for (post of postsQuery.data(); track post.id) {\n * <li>{{ post.title }}</li>\n * }\n * </ul>\n * }\n * `,\n * })\n * export class Posts {\n * readonly postsQuery = injectQuery(() => ({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * }))\n * }\n * ```\n * @example\n * Similar to `computed` from Angular, the function passed to `injectQuery` runs in the reactive context. In\n * the example below, the query is automatically enabled and executed when the filter signal changes to a\n * truthy value. When the filter signal changes back to a falsy value, the query is disabled.\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * <input [ngModel]=\"filter()\" (ngModelChange)=\"filter.set($event)\" />\n * @if (postsQuery.isPending()) {\n * Loading...\n * } @else if (postsQuery.isError()) {\n * <span>Error: {{ postsQuery.error()?.message }}</span>\n * } @else {\n * <ul>\n * @for (post of postsQuery.data(); track post.id) {\n * <li>{{ post.title }}</li>\n * }\n * </ul>\n * }\n * `,\n * })\n * export class Posts {\n * readonly filter = signal('')\n *\n * readonly postsQuery = injectQuery(() => ({\n * queryKey: ['posts', this.filter()],\n * queryFn: () => fetchPosts(this.filter()),\n * enabled: !!this.filter(),\n * }))\n * }\n * ```\n */\nexport function injectQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n optionsFn: () => UndefinedInitialDataOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >,\n): CreateQueryResult<TData, TError>\n\n/**\n * This overload accepts the general {@link CreateQueryOptions} shape rather than the `initialData`-aware\n * overloads above, so whether `data` is defined can't be inferred from the call site — useful when wrapping\n * `injectQuery` in your own helper function that forwards caller-provided options.\n * @param optionsFn - A function that returns query options. Similar to `computed` from Angular, this\n * function runs in the reactive context, so signals read inside it drive the query.\n * @returns The query result.\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries\n */\nexport function injectQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n optionsFn: () => CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): CreateQueryResult<TData, TError>\n\nexport function injectQuery(\n optionsFn: () => CreateQueryOptions,\n): DefinedCreateQueryResult | CreateQueryResult {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectQuery)\n }\n const outsideZone = injectQueryZone()\n const [resultSignal, getObserver] = injectBaseQuery(optionsFn, QueryObserver)\n return Object.assign(signalProxy(resultSignal, queryResultFields), {\n refetch: (options?: RefetchOptions) =>\n outsideZone(() => untracked(() => getObserver().refetch(options))),\n }) as unknown as DefinedCreateQueryResult | CreateQueryResult\n}\n"],"mappings":";;;;;;;AA8KA,SAAgB,YACd,WAC8C;CAC9C,IAAI,OAAO,cAAc,eAAe,WACtC,yBAAyB,WAAW;CAEtC,MAAM,cAAc,gBAAgB;CACpC,MAAM,CAAC,cAAc,eAAe,gBAAgB,WAAW,aAAa;CAC5E,OAAO,OAAO,OAAO,YAAY,cAAc,iBAAiB,GAAG,EACjE,UAAU,YACR,kBAAkB,gBAAgB,YAAY,CAAC,CAAC,QAAQ,OAAO,CAAC,CAAC,EACrE,CAAC;AACH"}
1
+ {"version":3,"file":"inject-query.mjs","names":[],"sources":["../src/inject-query.ts"],"sourcesContent":["import { assertInInjectionContext, untracked } from '@angular/core'\nimport { QueryObserver } from '@tanstack/query-core'\nimport { injectBaseQuery } from './inject-base-query'\nimport { injectQueryZone } from './utils/inject-query-zone'\nimport { queryResultFields } from './utils/result-fields'\nimport { signalProxy } from './utils/signal-proxy'\nimport type {\n DefaultError,\n QueryKey,\n RefetchOptions,\n} from '@tanstack/query-core'\nimport type {\n DefinedInitialDataOptions,\n UndefinedInitialDataOptions,\n} from './query-options'\nimport type {\n CreateQueryOptions,\n CreateQueryResult,\n DefinedCreateQueryResult,\n} from './types'\n\n/**\n * This overload is selected when `initialData` is known to be defined on the options returned by `optionsFn`, so the\n * resulting `data` signal is never `undefined` (unless a `select` changes `TData` to include `undefined`).\n * @param optionsFn - A function returning the {@link DefinedInitialDataOptions} to use — everything you\n * can pass to `injectQuery`, with `initialData` known to be defined. Similar to `computed` from Angular, this function runs\n * in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.\n * @returns The query result, typed so that `data` is never `undefined` (unless a `select` changes `TData` to\n * include `undefined`). At runtime, `data` is still `undefined` if `select` throws on its first call.\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries\n * @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like\n * `queryClient.query`.\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * <!-- `postsQuery.data()` is `Post[]`, never `undefined`, thanks to `initialData` — even if a\n * refetch 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(() => ({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * initialData: [],\n * }))\n * }\n * ```\n */\nexport function injectQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n optionsFn: () => DefinedInitialDataOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >,\n): DefinedCreateQueryResult<TData, TError>\n\n/**\n * Injects a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.\n * @param optionsFn - A function returning the {@link UndefinedInitialDataOptions} to use — everything\n * you can pass to `injectQuery`. Similar to `computed` from Angular, this function runs in the reactive\n * context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.\n * @returns The query result. `status()` is `'error'` if the query has an error from a fetch that failed\n * after its retries or if `select` threw, `'success'` if the query has cached data (even if `select`\n * returns `undefined`) or data from `placeholderData`, and `'pending'` otherwise.\n * `isPending`/`isSuccess`/`isError` are type-guard methods for convenience.\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries\n * @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like\n * `queryClient.query`.\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * @if (postsQuery.isPending()) {\n * Loading...\n * } @else if (postsQuery.isError()) {\n * <span>Error: {{ postsQuery.error()?.message }}</span>\n * } @else {\n * <ul>\n * @for (post of postsQuery.data(); track post.id) {\n * <li>{{ post.title }}</li>\n * }\n * </ul>\n * }\n * `,\n * })\n * export class Posts {\n * readonly postsQuery = injectQuery(() => ({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * }))\n * }\n * ```\n * @example\n * Similar to `computed` from Angular, the function passed to `injectQuery` runs in the reactive context. In\n * the example below, the query is automatically enabled and executed when the filter signal changes to a\n * truthy value. When the filter signal changes back to a falsy value, the query is disabled.\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * <input [ngModel]=\"filter()\" (ngModelChange)=\"filter.set($event)\" />\n * @if (postsQuery.isPending()) {\n * Loading...\n * } @else if (postsQuery.isError()) {\n * <span>Error: {{ postsQuery.error()?.message }}</span>\n * } @else {\n * <ul>\n * @for (post of postsQuery.data(); track post.id) {\n * <li>{{ post.title }}</li>\n * }\n * </ul>\n * }\n * `,\n * })\n * export class Posts {\n * readonly filter = signal('')\n *\n * readonly postsQuery = injectQuery(() => ({\n * queryKey: ['posts', this.filter()],\n * queryFn: () => fetchPosts(this.filter()),\n * // Signals can be combined with expressions\n * enabled: !!this.filter(),\n * }))\n * }\n * ```\n */\nexport function injectQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n optionsFn: () => UndefinedInitialDataOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >,\n): CreateQueryResult<TData, TError>\n\n/**\n * This overload accepts the general {@link CreateQueryOptions} shape rather than the `initialData`-aware\n * overloads above, so whether `data` is defined can't be inferred from the call site — useful when wrapping\n * `injectQuery` in your own helper function that forwards caller-provided options.\n * @param optionsFn - A function that returns query options. Similar to `computed` from Angular, this\n * function runs in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive\n * the query.\n * @returns The query result.\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries\n */\nexport function injectQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n optionsFn: () => CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): CreateQueryResult<TData, TError>\n\nexport function injectQuery(\n optionsFn: () => CreateQueryOptions,\n): DefinedCreateQueryResult | CreateQueryResult {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectQuery)\n }\n const outsideZone = injectQueryZone()\n const [resultSignal, getObserver] = injectBaseQuery(optionsFn, QueryObserver)\n return Object.assign(signalProxy(resultSignal, queryResultFields), {\n refetch: (options?: RefetchOptions) =>\n outsideZone(() => untracked(() => getObserver().refetch(options))),\n }) as unknown as DefinedCreateQueryResult | CreateQueryResult\n}\n"],"mappings":";;;;;;;AAgLA,SAAgB,YACd,WAC8C;CAC9C,IAAI,OAAO,cAAc,eAAe,WACtC,yBAAyB,WAAW;CAEtC,MAAM,cAAc,gBAAgB;CACpC,MAAM,CAAC,cAAc,eAAe,gBAAgB,WAAW,aAAa;CAC5E,OAAO,OAAO,OAAO,YAAY,cAAc,iBAAiB,GAAG,EACjE,UAAU,YACR,kBAAkB,gBAAgB,YAAY,CAAC,CAAC,QAAQ,OAAO,CAAC,CAAC,EACrE,CAAC;AACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/angular-query",
3
- "version": "5.0.0",
3
+ "version": "5.108.0",
4
4
  "description": "Signals for managing, caching and syncing asynchronous and remote data in Angular",
5
5
  "author": "Arnoud de Vries",
6
6
  "license": "MIT",
@@ -45,7 +45,7 @@
45
45
  },
46
46
  "sideEffects": false,
47
47
  "dependencies": {
48
- "@tanstack/query-core": "5.107.2"
48
+ "@tanstack/query-core": "5.108.0"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "@angular/common": ">=20.1.0",
package/providers.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { QueryClient } from '@tanstack/query-core';
2
2
  import { EnvironmentProviders } from '@angular/core';
3
3
  /**
4
- * Provides a `QueryClient` and optional TanStack Query features.
5
- * The factory runs once per injector in Angular's injection context, so it can
6
- * call `inject()` and each SSR request can receive an independent cache.
4
+ * Sets up providers necessary to enable TanStack Query functionality for Angular applications. Provides a
5
+ * `QueryClient` and optional TanStack Query features. The factory runs once per injector in Angular's
6
+ * injection context, so it can call `inject()` and each SSR request can receive an independent cache.
7
7
  * @param queryClientFactory - Creates or resolves a `QueryClient` in the injection context.
8
8
  * @param features - Optional features to configure additional Query functionality.
9
9
  * @returns A single {@link EnvironmentProviders} value (do not spread into `providers`).
@@ -21,10 +21,22 @@ import { EnvironmentProviders } from '@angular/core';
21
21
  * providers: [provideTanStackQuery(() => new QueryClient())],
22
22
  * })
23
23
  * ```
24
+ * @example
25
+ * The same, in an `NgModule`-based application:
26
+ * ```ts
27
+ * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'
24
28
  *
25
- * You can also enable optional developer tools by adding `withDevtools`. By
26
- * default the tools will then be loaded when your app is in development mode.
27
- *
29
+ * @NgModule({
30
+ * declarations: [AppComponent],
31
+ * imports: [BrowserModule],
32
+ * providers: [provideTanStackQuery(() => new QueryClient())],
33
+ * bootstrap: [AppComponent],
34
+ * })
35
+ * export class AppModule {}
36
+ * ```
37
+ * @example
38
+ * Enabling optional developer tools by adding `withDevtools` — by default, the tools are then loaded when
39
+ * your app is in development mode:
28
40
  * ```ts
29
41
  * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'
30
42
  * import { withDevtools } from '@tanstack/angular-query-devtools'
@@ -35,6 +47,19 @@ import { EnvironmentProviders } from '@angular/core';
35
47
  * ],
36
48
  * })
37
49
  * ```
50
+ * @example
51
+ * Resolving the `QueryClient` from an `InjectionToken` — an advanced optimization that lets TanStack Query
52
+ * be absent from the main application bundle, useful for including it on lazy-loaded routes only while
53
+ * still sharing a `QueryClient`. This is a small optimization; for most applications it's preferable to
54
+ * provide the `QueryClient` in the main application config, as in the examples above:
55
+ * ```ts
56
+ * export const MY_QUERY_CLIENT = new InjectionToken('', {
57
+ * factory: () => new QueryClient(),
58
+ * })
59
+ *
60
+ * // In a lazy loaded route's providers array:
61
+ * providers: [provideTanStackQuery(() => inject(MY_QUERY_CLIENT))]
62
+ * ```
38
63
  */
39
64
  export declare function provideTanStackQuery(queryClientFactory: () => QueryClient, ...features: ReadonlyArray<QueryFeature>): EnvironmentProviders;
40
65
  declare const queryFeatureBrand: unique symbol;
package/providers.mjs CHANGED
@@ -47,9 +47,9 @@ function configureQueryClient() {
47
47
  destroyRef.onDestroy(() => queryClient.unmount());
48
48
  }
49
49
  /**
50
- * Provides a `QueryClient` and optional TanStack Query features.
51
- * The factory runs once per injector in Angular's injection context, so it can
52
- * call `inject()` and each SSR request can receive an independent cache.
50
+ * Sets up providers necessary to enable TanStack Query functionality for Angular applications. Provides a
51
+ * `QueryClient` and optional TanStack Query features. The factory runs once per injector in Angular's
52
+ * injection context, so it can call `inject()` and each SSR request can receive an independent cache.
53
53
  * @param queryClientFactory - Creates or resolves a `QueryClient` in the injection context.
54
54
  * @param features - Optional features to configure additional Query functionality.
55
55
  * @returns A single {@link EnvironmentProviders} value (do not spread into `providers`).
@@ -67,10 +67,22 @@ function configureQueryClient() {
67
67
  * providers: [provideTanStackQuery(() => new QueryClient())],
68
68
  * })
69
69
  * ```
70
+ * @example
71
+ * The same, in an `NgModule`-based application:
72
+ * ```ts
73
+ * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'
70
74
  *
71
- * You can also enable optional developer tools by adding `withDevtools`. By
72
- * default the tools will then be loaded when your app is in development mode.
73
- *
75
+ * @NgModule({
76
+ * declarations: [AppComponent],
77
+ * imports: [BrowserModule],
78
+ * providers: [provideTanStackQuery(() => new QueryClient())],
79
+ * bootstrap: [AppComponent],
80
+ * })
81
+ * export class AppModule {}
82
+ * ```
83
+ * @example
84
+ * Enabling optional developer tools by adding `withDevtools` — by default, the tools are then loaded when
85
+ * your app is in development mode:
74
86
  * ```ts
75
87
  * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'
76
88
  * import { withDevtools } from '@tanstack/angular-query-devtools'
@@ -81,6 +93,19 @@ function configureQueryClient() {
81
93
  * ],
82
94
  * })
83
95
  * ```
96
+ * @example
97
+ * Resolving the `QueryClient` from an `InjectionToken` — an advanced optimization that lets TanStack Query
98
+ * be absent from the main application bundle, useful for including it on lazy-loaded routes only while
99
+ * still sharing a `QueryClient`. This is a small optimization; for most applications it's preferable to
100
+ * provide the `QueryClient` in the main application config, as in the examples above:
101
+ * ```ts
102
+ * export const MY_QUERY_CLIENT = new InjectionToken('', {
103
+ * factory: () => new QueryClient(),
104
+ * })
105
+ *
106
+ * // In a lazy loaded route's providers array:
107
+ * providers: [provideTanStackQuery(() => inject(MY_QUERY_CLIENT))]
108
+ * ```
84
109
  */
85
110
  function provideTanStackQuery(queryClientFactory, ...features) {
86
111
  return makeEnvironmentProviders([
package/providers.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"providers.mjs","names":[],"sources":["../src/providers.ts"],"sourcesContent":["import { isPlatformBrowser, isPlatformServer } from '@angular/common'\nimport {\n DOCUMENT,\n DestroyRef,\n InjectionToken,\n PLATFORM_ID,\n TransferState,\n inject,\n makeEnvironmentProviders,\n makeStateKey,\n provideEnvironmentInitializer,\n} from '@angular/core'\nimport { QueryClient, dehydrate, hydrate } from '@tanstack/query-core'\nimport { INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY } from './hydration-state-key'\nimport { injectQueryZone } from './utils/inject-query-zone'\nimport type { EnvironmentProviders } from '@angular/core'\nimport type { DehydratedState } from '@tanstack/query-core'\n\nconst INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE = new InjectionToken<boolean>('', {\n providedIn: 'root',\n factory: () => true,\n})\n\n/**\n * Mounts the injected client, configures server defaults, and connects TransferState hydration.\n */\nfunction configureQueryClient() {\n const queryClient = inject(QueryClient)\n const destroyRef = inject(DestroyRef)\n const platformId = inject(PLATFORM_ID)\n\n if (isPlatformServer(platformId)) {\n // DOM emulation can fool core's runtime detection. Apply server defaults to\n // this client without changing other clients or global scheduling providers.\n const defaults = queryClient.getDefaultOptions()\n queryClient.setDefaultOptions({\n ...defaults,\n queries: { gcTime: Infinity, retry: false, ...defaults.queries },\n mutations: { gcTime: Infinity, ...defaults.mutations },\n })\n }\n const shouldHydrate = inject(INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE)\n const hydrationStateKey = inject(\n INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY,\n )\n\n if (inject(DOCUMENT, { optional: true })) {\n const transferState = inject(TransferState)\n\n if (shouldHydrate && isPlatformServer(platformId)) {\n transferState.onSerialize(hydrationStateKey, () => dehydrate(queryClient))\n } else if (shouldHydrate && isPlatformBrowser(platformId)) {\n const dehydratedState = transferState.get(hydrationStateKey, null)\n if (dehydratedState) {\n hydrate(queryClient, dehydratedState)\n transferState.remove(hydrationStateKey)\n }\n }\n }\n\n queryClient.mount()\n destroyRef.onDestroy(() => queryClient.unmount())\n}\n\n/**\n * Provides a `QueryClient` and optional TanStack Query features.\n * The factory runs once per injector in Angular's injection context, so it can\n * call `inject()` and each SSR request can receive an independent cache.\n * @param queryClientFactory - Creates or resolves a `QueryClient` in the injection context.\n * @param features - Optional features to configure additional Query functionality.\n * @returns A single {@link EnvironmentProviders} value (do not spread into `providers`).\n * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start\n * @see https://tanstack.com/query/v5/docs/framework/angular/devtools\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/ssr\n * @example\n * ```ts\n * import {\n * provideTanStackQuery,\n * QueryClient,\n * } from '@tanstack/angular-query'\n *\n * bootstrapApplication(AppComponent, {\n * providers: [provideTanStackQuery(() => new QueryClient())],\n * })\n * ```\n *\n * You can also enable optional developer tools by adding `withDevtools`. By\n * default the tools will then be loaded when your app is in development mode.\n *\n * ```ts\n * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'\n * import { withDevtools } from '@tanstack/angular-query-devtools'\n *\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideTanStackQuery(() => new QueryClient(), withDevtools()),\n * ],\n * })\n * ```\n */\nexport function provideTanStackQuery(\n queryClientFactory: () => QueryClient,\n ...features: ReadonlyArray<QueryFeature>\n): EnvironmentProviders {\n return makeEnvironmentProviders([\n {\n provide: QueryClient,\n useFactory: () => injectQueryZone()(queryClientFactory),\n },\n ...features.map(getQueryFeatureProviders),\n provideEnvironmentInitializer(configureQueryClient),\n ])\n}\n\nconst queryFeatureBrand: unique symbol = Symbol('QueryFeature')\n\n/**\n * Opaque configuration returned by Query feature functions such as `withHydrationKey`.\n * Pass features to `provideTanStackQuery`; applications do not construct them directly.\n */\nexport interface QueryFeature {\n /** @internal */\n readonly [queryFeatureBrand]: true\n}\n\ninterface InternalQueryFeature extends QueryFeature {\n readonly ɵproviders: EnvironmentProviders\n}\n\n/**\n * Creates a feature shared by Angular Query integration packages.\n * @internal\n * @param providers - Providers owned by this Query feature.\n * @returns An opaque feature that installs the supplied environment providers.\n */\nexport function queryFeature(providers: EnvironmentProviders): QueryFeature {\n const feature: InternalQueryFeature = {\n [queryFeatureBrand]: true,\n ɵproviders: providers,\n }\n\n return feature\n}\n\n/**\n * Gets the environment providers owned by an opaque Query feature.\n * @internal\n * @param feature - The feature to unwrap.\n * @returns The environment providers to install.\n */\nexport function getQueryFeatureProviders(\n feature: QueryFeature,\n): EnvironmentProviders {\n return (feature as InternalQueryFeature).ɵproviders\n}\n\n/**\n * Sets a non-default serialization key for this injector's `QueryClient` cache (server dehydrate /\n * browser hydrate via `TransferState`). Use this when you have multiple `QueryClient` instances\n * so each has its own key. The default key applies when you do not add this feature.\n *\n * ```ts\n * providers: [\n * provideTanStackQuery(\n * () => new QueryClient(),\n * withHydrationKey('my-secondary-query-cache'),\n * ),\n * ]\n * ```\n * @param key - A unique string for this client's `TransferState` entry.\n * @returns A feature that stores this client's cache under the supplied key.\n */\nexport function withHydrationKey(key: string): QueryFeature {\n return queryFeature(\n makeEnvironmentProviders([\n {\n provide: INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY,\n useValue: makeStateKey<DehydratedState>(key),\n },\n ]),\n )\n}\n\n/**\n * Disables `TransferState` hydration and dehydration for the current environment injector.\n * @returns A feature that prevents automatic cache transfer for this injector.\n */\nexport function withNoQueryHydration(): QueryFeature {\n return queryFeature(\n makeEnvironmentProviders([\n {\n provide: INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE,\n useValue: false,\n },\n ]),\n )\n}\n"],"mappings":";;;;;;AAkBA,IAAM,uCAAuC,IAAI,eAAwB,IAAI;CAC3E,YAAY;CACZ,eAAe;AACjB,CAAC;;;;AAKD,SAAS,uBAAuB;CAC9B,MAAM,cAAc,OAAO,WAAW;CACtC,MAAM,aAAa,OAAO,UAAU;CACpC,MAAM,aAAa,OAAO,WAAW;CAErC,IAAI,iBAAiB,UAAU,GAAG;EAGhC,MAAM,WAAW,YAAY,kBAAkB;EAC/C,YAAY,kBAAkB;GAC5B,GAAG;GACH,SAAS;IAAE,QAAQ;IAAU,OAAO;IAAO,GAAG,SAAS;GAAQ;GAC/D,WAAW;IAAE,QAAQ;IAAU,GAAG,SAAS;GAAU;EACvD,CAAC;CACH;CACA,MAAM,gBAAgB,OAAO,oCAAoC;CACjE,MAAM,oBAAoB,OACxB,8CACF;CAEA,IAAI,OAAO,UAAU,EAAE,UAAU,KAAK,CAAC,GAAG;EACxC,MAAM,gBAAgB,OAAO,aAAa;EAE1C,IAAI,iBAAiB,iBAAiB,UAAU,GAC9C,cAAc,YAAY,yBAAyB,UAAU,WAAW,CAAC;OACpE,IAAI,iBAAiB,kBAAkB,UAAU,GAAG;GACzD,MAAM,kBAAkB,cAAc,IAAI,mBAAmB,IAAI;GACjE,IAAI,iBAAiB;IACnB,QAAQ,aAAa,eAAe;IACpC,cAAc,OAAO,iBAAiB;GACxC;EACF;CACF;CAEA,YAAY,MAAM;CAClB,WAAW,gBAAgB,YAAY,QAAQ,CAAC;AAClD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,qBACd,oBACA,GAAG,UACmB;CACtB,OAAO,yBAAyB;EAC9B;GACE,SAAS;GACT,kBAAkB,gBAAgB,CAAC,CAAC,kBAAkB;EACxD;EACA,GAAG,SAAS,IAAI,wBAAwB;EACxC,8BAA8B,oBAAoB;CACpD,CAAC;AACH;AAEA,IAAM,oBAAmC,OAAO,cAAc;;;;;;;AAqB9D,SAAgB,aAAa,WAA+C;CAM1E,OAAO;GAJJ,oBAAoB;EACrB,YAAY;CAGP;AACT;;;;;;;AAQA,SAAgB,yBACd,SACsB;CACtB,OAAQ,QAAiC;AAC3C;;;;;;;;;;;;;;;;;AAkBA,SAAgB,iBAAiB,KAA2B;CAC1D,OAAO,aACL,yBAAyB,CACvB;EACE,SAAS;EACT,UAAU,aAA8B,GAAG;CAC7C,CACF,CAAC,CACH;AACF;;;;;AAMA,SAAgB,uBAAqC;CACnD,OAAO,aACL,yBAAyB,CACvB;EACE,SAAS;EACT,UAAU;CACZ,CACF,CAAC,CACH;AACF"}
1
+ {"version":3,"file":"providers.mjs","names":[],"sources":["../src/providers.ts"],"sourcesContent":["import { isPlatformBrowser, isPlatformServer } from '@angular/common'\nimport {\n DOCUMENT,\n DestroyRef,\n InjectionToken,\n PLATFORM_ID,\n TransferState,\n inject,\n makeEnvironmentProviders,\n makeStateKey,\n provideEnvironmentInitializer,\n} from '@angular/core'\nimport { QueryClient, dehydrate, hydrate } from '@tanstack/query-core'\nimport { INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY } from './hydration-state-key'\nimport { injectQueryZone } from './utils/inject-query-zone'\nimport type { EnvironmentProviders } from '@angular/core'\nimport type { DehydratedState } from '@tanstack/query-core'\n\nconst INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE = new InjectionToken<boolean>('', {\n providedIn: 'root',\n factory: () => true,\n})\n\n/**\n * Mounts the injected client, configures server defaults, and connects TransferState hydration.\n */\nfunction configureQueryClient() {\n const queryClient = inject(QueryClient)\n const destroyRef = inject(DestroyRef)\n const platformId = inject(PLATFORM_ID)\n\n if (isPlatformServer(platformId)) {\n // DOM emulation can fool core's runtime detection. Apply server defaults to\n // this client without changing other clients or global scheduling providers.\n const defaults = queryClient.getDefaultOptions()\n queryClient.setDefaultOptions({\n ...defaults,\n queries: { gcTime: Infinity, retry: false, ...defaults.queries },\n mutations: { gcTime: Infinity, ...defaults.mutations },\n })\n }\n const shouldHydrate = inject(INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE)\n const hydrationStateKey = inject(\n INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY,\n )\n\n if (inject(DOCUMENT, { optional: true })) {\n const transferState = inject(TransferState)\n\n if (shouldHydrate && isPlatformServer(platformId)) {\n transferState.onSerialize(hydrationStateKey, () => dehydrate(queryClient))\n } else if (shouldHydrate && isPlatformBrowser(platformId)) {\n const dehydratedState = transferState.get(hydrationStateKey, null)\n if (dehydratedState) {\n hydrate(queryClient, dehydratedState)\n transferState.remove(hydrationStateKey)\n }\n }\n }\n\n queryClient.mount()\n destroyRef.onDestroy(() => queryClient.unmount())\n}\n\n/**\n * Sets up providers necessary to enable TanStack Query functionality for Angular applications. Provides a\n * `QueryClient` and optional TanStack Query features. The factory runs once per injector in Angular's\n * injection context, so it can call `inject()` and each SSR request can receive an independent cache.\n * @param queryClientFactory - Creates or resolves a `QueryClient` in the injection context.\n * @param features - Optional features to configure additional Query functionality.\n * @returns A single {@link EnvironmentProviders} value (do not spread into `providers`).\n * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start\n * @see https://tanstack.com/query/v5/docs/framework/angular/devtools\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/ssr\n * @example\n * ```ts\n * import {\n * provideTanStackQuery,\n * QueryClient,\n * } from '@tanstack/angular-query'\n *\n * bootstrapApplication(AppComponent, {\n * providers: [provideTanStackQuery(() => new QueryClient())],\n * })\n * ```\n * @example\n * The same, in an `NgModule`-based application:\n * ```ts\n * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'\n *\n * @NgModule({\n * declarations: [AppComponent],\n * imports: [BrowserModule],\n * providers: [provideTanStackQuery(() => new QueryClient())],\n * bootstrap: [AppComponent],\n * })\n * export class AppModule {}\n * ```\n * @example\n * Enabling optional developer tools by adding `withDevtools` — by default, the tools are then loaded when\n * your app is in development mode:\n * ```ts\n * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'\n * import { withDevtools } from '@tanstack/angular-query-devtools'\n *\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideTanStackQuery(() => new QueryClient(), withDevtools()),\n * ],\n * })\n * ```\n * @example\n * Resolving the `QueryClient` from an `InjectionToken` — an advanced optimization that lets TanStack Query\n * be absent from the main application bundle, useful for including it on lazy-loaded routes only while\n * still sharing a `QueryClient`. This is a small optimization; for most applications it's preferable to\n * provide the `QueryClient` in the main application config, as in the examples above:\n * ```ts\n * export const MY_QUERY_CLIENT = new InjectionToken('', {\n * factory: () => new QueryClient(),\n * })\n *\n * // In a lazy loaded route's providers array:\n * providers: [provideTanStackQuery(() => inject(MY_QUERY_CLIENT))]\n * ```\n */\nexport function provideTanStackQuery(\n queryClientFactory: () => QueryClient,\n ...features: ReadonlyArray<QueryFeature>\n): EnvironmentProviders {\n return makeEnvironmentProviders([\n {\n provide: QueryClient,\n useFactory: () => injectQueryZone()(queryClientFactory),\n },\n ...features.map(getQueryFeatureProviders),\n provideEnvironmentInitializer(configureQueryClient),\n ])\n}\n\nconst queryFeatureBrand: unique symbol = Symbol('QueryFeature')\n\n/**\n * Opaque configuration returned by Query feature functions such as `withHydrationKey`.\n * Pass features to `provideTanStackQuery`; applications do not construct them directly.\n */\nexport interface QueryFeature {\n /** @internal */\n readonly [queryFeatureBrand]: true\n}\n\ninterface InternalQueryFeature extends QueryFeature {\n readonly ɵproviders: EnvironmentProviders\n}\n\n/**\n * Creates a feature shared by Angular Query integration packages.\n * @internal\n * @param providers - Providers owned by this Query feature.\n * @returns An opaque feature that installs the supplied environment providers.\n */\nexport function queryFeature(providers: EnvironmentProviders): QueryFeature {\n const feature: InternalQueryFeature = {\n [queryFeatureBrand]: true,\n ɵproviders: providers,\n }\n\n return feature\n}\n\n/**\n * Gets the environment providers owned by an opaque Query feature.\n * @internal\n * @param feature - The feature to unwrap.\n * @returns The environment providers to install.\n */\nexport function getQueryFeatureProviders(\n feature: QueryFeature,\n): EnvironmentProviders {\n return (feature as InternalQueryFeature).ɵproviders\n}\n\n/**\n * Sets a non-default serialization key for this injector's `QueryClient` cache (server dehydrate /\n * browser hydrate via `TransferState`). Use this when you have multiple `QueryClient` instances\n * so each has its own key. The default key applies when you do not add this feature.\n *\n * ```ts\n * providers: [\n * provideTanStackQuery(\n * () => new QueryClient(),\n * withHydrationKey('my-secondary-query-cache'),\n * ),\n * ]\n * ```\n * @param key - A unique string for this client's `TransferState` entry.\n * @returns A feature that stores this client's cache under the supplied key.\n */\nexport function withHydrationKey(key: string): QueryFeature {\n return queryFeature(\n makeEnvironmentProviders([\n {\n provide: INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY,\n useValue: makeStateKey<DehydratedState>(key),\n },\n ]),\n )\n}\n\n/**\n * Disables `TransferState` hydration and dehydration for the current environment injector.\n * @returns A feature that prevents automatic cache transfer for this injector.\n */\nexport function withNoQueryHydration(): QueryFeature {\n return queryFeature(\n makeEnvironmentProviders([\n {\n provide: INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE,\n useValue: false,\n },\n ]),\n )\n}\n"],"mappings":";;;;;;AAkBA,IAAM,uCAAuC,IAAI,eAAwB,IAAI;CAC3E,YAAY;CACZ,eAAe;AACjB,CAAC;;;;AAKD,SAAS,uBAAuB;CAC9B,MAAM,cAAc,OAAO,WAAW;CACtC,MAAM,aAAa,OAAO,UAAU;CACpC,MAAM,aAAa,OAAO,WAAW;CAErC,IAAI,iBAAiB,UAAU,GAAG;EAGhC,MAAM,WAAW,YAAY,kBAAkB;EAC/C,YAAY,kBAAkB;GAC5B,GAAG;GACH,SAAS;IAAE,QAAQ;IAAU,OAAO;IAAO,GAAG,SAAS;GAAQ;GAC/D,WAAW;IAAE,QAAQ;IAAU,GAAG,SAAS;GAAU;EACvD,CAAC;CACH;CACA,MAAM,gBAAgB,OAAO,oCAAoC;CACjE,MAAM,oBAAoB,OACxB,8CACF;CAEA,IAAI,OAAO,UAAU,EAAE,UAAU,KAAK,CAAC,GAAG;EACxC,MAAM,gBAAgB,OAAO,aAAa;EAE1C,IAAI,iBAAiB,iBAAiB,UAAU,GAC9C,cAAc,YAAY,yBAAyB,UAAU,WAAW,CAAC;OACpE,IAAI,iBAAiB,kBAAkB,UAAU,GAAG;GACzD,MAAM,kBAAkB,cAAc,IAAI,mBAAmB,IAAI;GACjE,IAAI,iBAAiB;IACnB,QAAQ,aAAa,eAAe;IACpC,cAAc,OAAO,iBAAiB;GACxC;EACF;CACF;CAEA,YAAY,MAAM;CAClB,WAAW,gBAAgB,YAAY,QAAQ,CAAC;AAClD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA,SAAgB,qBACd,oBACA,GAAG,UACmB;CACtB,OAAO,yBAAyB;EAC9B;GACE,SAAS;GACT,kBAAkB,gBAAgB,CAAC,CAAC,kBAAkB;EACxD;EACA,GAAG,SAAS,IAAI,wBAAwB;EACxC,8BAA8B,oBAAoB;CACpD,CAAC;AACH;AAEA,IAAM,oBAAmC,OAAO,cAAc;;;;;;;AAqB9D,SAAgB,aAAa,WAA+C;CAM1E,OAAO;GAJJ,oBAAoB;EACrB,YAAY;CAGP;AACT;;;;;;;AAQA,SAAgB,yBACd,SACsB;CACtB,OAAQ,QAAiC;AAC3C;;;;;;;;;;;;;;;;;AAkBA,SAAgB,iBAAiB,KAA2B;CAC1D,OAAO,aACL,yBAAyB,CACvB;EACE,SAAS;EACT,UAAU,aAA8B,GAAG;CAC7C,CACF,CAAC,CACH;AACF;;;;;AAMA,SAAgB,uBAAqC;CACnD,OAAO,aACL,yBAAyB,CACvB;EACE,SAAS;EACT,UAAU;CACZ,CACF,CAAC,CACH;AACF"}
@@ -47,6 +47,13 @@ export type UnusedSkipTokenOptions<TQueryFnData = unknown, TError = DefaultError
47
47
  * @template TQueryKey - The type of your `queryKey`.
48
48
  */
49
49
  export type DefinedInitialDataOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
50
+ /**
51
+ * If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
52
+ * created or cached yet). If set to a function, the function will be called **once** during the shared/root
53
+ * query initialization, and be expected to synchronously return the initial data. Initial data is
54
+ * considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
55
+ * cache.
56
+ */
50
57
  initialData: NonUndefinedGuard<TQueryFnData> | (() => NonUndefinedGuard<TQueryFnData>);
51
58
  };
52
59
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"query-options.mjs","names":[],"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 `initialData` is omitted, may be\n * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is\n * `pending`.\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 `queryFn` is not `skipToken` and\n * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` — same as\n * {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.\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 `initialData` is omitted, may\n * be `undefined`, or is a function that may return `undefined`. If you don't intend to run the query yet,\n * set `enabled: false` — omitting `queryFn` alone still triggers a fetch that fails with \"Missing queryFn\"\n * unless `enabled` is `false` or a default query function has been defined. A default query function only\n * 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 known to be defined —\n * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`).\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 known to be defined, so the resulting `data` is never\n * `undefined` (unless a `select` changes `TData` to include `undefined`).\n * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `injectQuery`,\n * with `initialData` known to be defined.\n * @returns The same options object, typed so that `queryKey` carries the inferred data type.\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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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"],"mappings":";AA0QA,SAAgB,aAAa,SAAkB;CAC7C,OAAO;AACT"}
1
+ {"version":3,"file":"query-options.mjs","names":[],"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 `initialData` is omitted, may be\n * `undefined`, or is a function that may return `undefined` — `data` may be `undefined` while the query is\n * `pending`.\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 `queryFn` is not `skipToken` and\n * `initialData` is omitted, may be `undefined`, or is a function that may return `undefined` — same as\n * {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.\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 `initialData` is omitted, may\n * be `undefined`, or is a function that may return `undefined`. If you don't intend to run the query yet,\n * set `enabled: false` — omitting `queryFn` alone still triggers a fetch that fails with \"Missing queryFn\"\n * unless `enabled` is `false` or a default query function has been defined. A default query function only\n * 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 known to be defined —\n * `data` is never `undefined` (unless a `select` changes `TData` to include `undefined`).\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 /**\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<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 known to be defined, so the resulting `data` is never\n * `undefined` (unless a `select` changes `TData` to include `undefined`).\n * @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `injectQuery`,\n * with `initialData` known to be defined.\n * @returns The same options object, typed so that `queryKey` carries the inferred data type.\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 * @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 * @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 * @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 * @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 * @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 * @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 * @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 * @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"],"mappings":";AAiRA,SAAgB,aAAa,SAAkB;CAC7C,OAAO;AACT"}
@@ -6,9 +6,9 @@ const dependencies_1 = require("@schematics/angular/utility/dependencies");
6
6
  const source_1 = require("./source");
7
7
  const workspace_1 = require("./workspace");
8
8
  const PACKAGE_NAME = '@tanstack/angular-query';
9
- const PACKAGE_VERSION = '5.0.0';
9
+ const PACKAGE_VERSION = '5.108.0';
10
10
  const DEVTOOLS_PACKAGE_NAME = '@tanstack/angular-query-devtools';
11
- const DEVTOOLS_PACKAGE_VERSION = '5.0.0';
11
+ const DEVTOOLS_PACKAGE_VERSION = '5.108.0';
12
12
  const MIGRATION_GUIDE = 'https://tanstack.com/query/latest/docs/framework/angular/guides/migrating-from-experimental';
13
13
  const dependencyTypes = [
14
14
  dependencies_1.NodeDependencyType.Default,
@@ -16,7 +16,7 @@ const typescript_1 = __importDefault(require("typescript"));
16
16
  // The published schematic contains literal values and does not read package.json.
17
17
  const PACKAGE_NAME = '@tanstack/angular-query';
18
18
  const DEVTOOLS_PACKAGE_NAME = '@tanstack/angular-query-devtools';
19
- const DEVTOOLS_PACKAGE_VERSION = '5.0.0';
19
+ const DEVTOOLS_PACKAGE_VERSION = '5.108.0';
20
20
  function hasPackageDependency(tree, name) {
21
21
  const packageJsonPath = tree.exists('/package.json')
22
22
  ? '/package.json'
package/types.d.ts CHANGED
@@ -4,8 +4,15 @@ import { InfiniteQueryResultFields, MutationResultFields, QueryResultFields } fr
4
4
  import { MapToSignals } from './utils/signal-proxy.js';
5
5
  type SignalFunction<T extends () => any> = T & Signal<ReturnType<T>>;
6
6
  /**
7
- * Options accepted by `injectQuery`, with cache data projected through an optional `select`.
8
- * Angular owns result notifications and exposes errors through signals rather than error boundaries.
7
+ * The options accepted by `injectQuery`, with cache data projected through an optional `select`. Same as
8
+ * {@link QueryObserverOptions} from `@tanstack/query-core`, minus `notifyOnChangeProps`, `suspense`, and
9
+ * `throwOnError`: Angular owns result notifications and exposes errors through signals rather than error
10
+ * boundaries.
11
+ * @template TQueryFnData - The type your `queryFn` resolves to.
12
+ * @template TError - The type of errors your `queryFn` may throw.
13
+ * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no
14
+ * `select` is used.
15
+ * @template TQueryKey - The type of your `queryKey`.
9
16
  */
10
17
  export type CreateQueryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = OmitKeyof<QueryObserverOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey>, 'notifyOnChangeProps' | 'suspense' | 'throwOnError'>;
11
18
  type CreateStatusBasedQueryResult<TStatus extends QueryObserverResult['status'], TData = unknown, TError = DefaultError> = Extract<QueryObserverResult<TData, TError>, {
@@ -21,7 +28,13 @@ type CreateStatusBasedDefinedInfiniteQueryResult<TStatus extends DefinedInfinite
21
28
  status: TStatus;
22
29
  }>;
23
30
  /**
24
- * Signal-backed guards that narrow a query result and its data and error fields by status.
31
+ * Signal-backed guards that narrow a query result and its data and error fields by status: the
32
+ * `isSuccess`/`isError`/`isPending` methods on a query result. Unlike `react-query`'s derived booleans, each
33
+ * is a `Signal` you call to read its current boolean value reactively, and the call is also a type guard —
34
+ * `if (query.isSuccess())` — so that `query.data` narrows away `undefined` inside the branch, the same way
35
+ * `status` narrowing works on the plain object `react-query` returns.
36
+ * @template TData - The type `data` ends up as after `select` runs.
37
+ * @template TError - The type of errors your `queryFn` may throw.
25
38
  */
26
39
  export interface BaseQueryNarrowing<TData = unknown, TError = DefaultError> {
27
40
  /**
@@ -89,7 +102,17 @@ export interface DefinedInfiniteQueryNarrowing<TData = unknown, TError = Default
89
102
  isPending: SignalFunction<(this: DefinedCreateInfiniteQueryResult<TData, TError>) => this is never>;
90
103
  }
91
104
  /**
92
- * Options accepted by `injectInfiniteQuery`, including page parameters and pagination callbacks.
105
+ * The options accepted by `injectInfiniteQuery`, including page parameters and pagination callbacks. Same as
106
+ * {@link InfiniteQueryObserverOptions} from `@tanstack/query-core` — for the infinite-query-specific options
107
+ * (`getNextPageParam`, `initialPageParam`, etc.) — minus `notifyOnChangeProps`, `suspense`, and
108
+ * `throwOnError`, like {@link CreateQueryOptions}.
109
+ * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
110
+ * @template TError - The type of errors your `queryFn` may throw.
111
+ * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` here, though
112
+ * `injectInfiniteQuery` itself defaults it to `InfiniteData<TQueryFnData>` — the shape `data` actually has
113
+ * when no `select` is used.
114
+ * @template TQueryKey - The type of your `queryKey`.
115
+ * @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
93
116
  */
94
117
  export interface CreateInfiniteQueryOptions<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown> extends OmitKeyof<InfiniteQueryObserverOptions<TQueryFnData, TError, TData, TQueryKey, TPageParam>, 'notifyOnChangeProps' | 'suspense' | 'throwOnError'> {
95
118
  }
@@ -189,7 +212,15 @@ type CreateStatusBasedMutationResult<TStatus extends CreateBaseMutationResult['s
189
212
  status: TStatus;
190
213
  }>;
191
214
  /**
192
- * Signal-backed guards that narrow mutation data, errors, and variables by the current status.
215
+ * Signal-backed guards that narrow mutation data, errors, and variables by the current status: the
216
+ * `isSuccess`/`isError`/`isPending`/`isIdle` methods on a mutation result. Each is a `Signal` you call to
217
+ * read its current boolean value reactively, and the call is also a type guard — `if (mutation.isSuccess())`
218
+ * — so that `mutation.data` narrows away `undefined` inside the branch.
219
+ * @template TData - The type your mutation function resolves to.
220
+ * @template TError - The type of errors your mutation function may throw.
221
+ * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`.
222
+ * @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
223
+ * their `onMutateResult` parameter — useful for optimistic-update rollback data.
193
224
  */
194
225
  export interface BaseMutationNarrowing<TData = unknown, TError = DefaultError, TVariables = unknown, TOnMutateResult = unknown> {
195
226
  /**