openapi-typesafe-react-query 1.0.0-rc.4 → 1.0.0-rc.6

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,32 @@
2
2
 
3
3
  This package is a fork of `openapi-react-query`. The entries above `0.5.4` are releases of openapi-typesafe-react-query; `0.5.4` and the entries below it are the upstream history up to the fork point (upstream commit `d46a319a`), with `openapi-react-query` versions.
4
4
 
5
+ ## 1.0.0-rc.6
6
+
7
+ ### Patch Changes
8
+
9
+ - [#89](https://github.com/openapi-typesafe/openapi-typesafe/pull/89) [`ebb5b46`](https://github.com/openapi-typesafe/openapi-typesafe/commit/ebb5b46684bc20b78727d295924189c02d2287ce) Thanks [@fedorello](https://github.com/fedorello)! - Keep one query key for a `FormData` or `File` body built while the component renders (the file's date in the key made a new request on every render), name a raw body's kind in `bodyType` so it never shares a key with a JSON body of the same shape, and leave out init fields set to `undefined`, so `{ headers: undefined }` has the same key as no init.
10
+ - Updated dependencies [[`dfb0fe3`](https://github.com/openapi-typesafe/openapi-typesafe/commit/dfb0fe3c61a75d2b8ca512577f4b699049171a64)]:
11
+ - openapi-typesafe-fetch@1.0.0-rc.6
12
+
13
+ ## 1.0.0-rc.5
14
+
15
+ ### Patch Changes
16
+
17
+ - [#67](https://github.com/openapi-typesafe/openapi-typesafe/pull/67) [`fbaded2`](https://github.com/openapi-typesafe/openapi-typesafe/commit/fbaded241385d032d5b28d2c93d5e0a7d6ae292b) Thanks [@fedorello](https://github.com/fedorello)! - Two requests no longer share a cache entry: the init in a query key has its `headers` as a plain
18
+ object of the names and values they send (a `Headers` object hashed as `{}` before), a
19
+ `URLSearchParams`, `FormData`, `Blob` or bytes body by its content (hashed as `{}` before too), and
20
+ the `baseUrl` of the fetch client, so two clients with different base URLs get their own entries.
21
+ `createClient(fetchClient, { keyScope })` puts a name for the API in the keys instead of the base
22
+ URL: give the server and the browser the same one when they reach the API by different URLs, so
23
+ the browser reads the data the server rendered.
24
+ Read keys from `queryOptions(...).queryKey`; `[method, path]` still matches every query. Each
25
+ request is sent with the init of its own call, and stops when the query is cancelled also when the
26
+ init has its own `signal`. `useQuery` with an `initialData` that is never `undefined` types `data`
27
+ as defined, as TanStack Query does.
28
+ - Updated dependencies [[`0f0792b`](https://github.com/openapi-typesafe/openapi-typesafe/commit/0f0792b8efa4f5139653cd285455f7d6165ddb95), [`fbaded2`](https://github.com/openapi-typesafe/openapi-typesafe/commit/fbaded241385d032d5b28d2c93d5e0a7d6ae292b), [`0f0792b`](https://github.com/openapi-typesafe/openapi-typesafe/commit/0f0792b8efa4f5139653cd285455f7d6165ddb95), [`0f0792b`](https://github.com/openapi-typesafe/openapi-typesafe/commit/0f0792b8efa4f5139653cd285455f7d6165ddb95), [`0f0792b`](https://github.com/openapi-typesafe/openapi-typesafe/commit/0f0792b8efa4f5139653cd285455f7d6165ddb95), [`0f0792b`](https://github.com/openapi-typesafe/openapi-typesafe/commit/0f0792b8efa4f5139653cd285455f7d6165ddb95), [`0f0792b`](https://github.com/openapi-typesafe/openapi-typesafe/commit/0f0792b8efa4f5139653cd285455f7d6165ddb95), [`a74608e`](https://github.com/openapi-typesafe/openapi-typesafe/commit/a74608ec36b0a938594e0d0fac10c9fb222c1742), [`0f0792b`](https://github.com/openapi-typesafe/openapi-typesafe/commit/0f0792b8efa4f5139653cd285455f7d6165ddb95)]:
29
+ - openapi-typesafe-fetch@1.0.0-rc.5
30
+
5
31
  ## 1.0.0-rc.4
6
32
 
7
33
  ### Patch Changes
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # openapi-typesafe-react-query
2
2
 
3
- openapi-typesafe-react-query is a small, type-safe wrapper (about 1 kB minified) around [@tanstack/react-query](https://tanstack.com/query/latest/docs/framework/react/overview) to work with OpenAPI schema.
3
+ openapi-typesafe-react-query is a small, type-safe wrapper (about 2 kB minified, 1 kB gzipped) around [@tanstack/react-query](https://tanstack.com/query/latest/docs/framework/react/overview) to work with OpenAPI schema.
4
4
 
5
5
  It works by using [openapi-typesafe-fetch](../openapi-typesafe-fetch) and [openapi-typesafe](../openapi-typesafe) so URLs, parameters, request bodies and responses are checked against your schema, with no manual types,
6
6
  no `any` and no `as` assertions.
package/dist/index.cjs CHANGED
@@ -4,6 +4,111 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  const reactQuery = require('@tanstack/react-query');
6
6
 
7
+ const TYPE_TAG_START = "[object ".length;
8
+ const TYPE_TAG_END = -1;
9
+ function isClass(value, name) {
10
+ const type = globalThis[name];
11
+ return typeof type === "function" && value instanceof type || Object.prototype.toString.call(value).slice(TYPE_TAG_START, TYPE_TAG_END) === name;
12
+ }
13
+ function plainHeaders(headers) {
14
+ if (!(Symbol.iterator in headers)) {
15
+ return headers;
16
+ }
17
+ const record = {};
18
+ for (const pair of headers) {
19
+ const [name, value] = Array.from(pair);
20
+ const key = String(name).toLowerCase();
21
+ record[key] = key in record ? `${record[key]}, ${String(value)}` : String(value);
22
+ }
23
+ return record;
24
+ }
25
+ function blobKey(blob) {
26
+ const { name } = blob;
27
+ return { type: blob.type, size: blob.size, name };
28
+ }
29
+ function formDataKey(form) {
30
+ if (typeof form.entries !== "function") {
31
+ return [];
32
+ }
33
+ return Array.from(form.entries(), ([name, value]) => [
34
+ name,
35
+ typeof value === "string" ? value : blobKey(value)
36
+ ]);
37
+ }
38
+ function bodyBytes(body) {
39
+ if (ArrayBuffer.isView(body)) {
40
+ return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
41
+ }
42
+ return isClass(body, "ArrayBuffer") ? new Uint8Array(body) : null;
43
+ }
44
+ function rawBodyKey(body) {
45
+ if (typeof body !== "object" || body === null) {
46
+ return void 0;
47
+ }
48
+ if (isClass(body, "URLSearchParams")) {
49
+ return { body: String(body), bodyType: "URLSearchParams" };
50
+ }
51
+ if (isClass(body, "FormData")) {
52
+ return { body: formDataKey(body), bodyType: "FormData" };
53
+ }
54
+ if (isClass(body, "Blob") || isClass(body, "File")) {
55
+ return { body: blobKey(body), bodyType: "Blob" };
56
+ }
57
+ const bytes = bodyBytes(body);
58
+ return bytes === null ? void 0 : { body: Array.from(bytes), bodyType: "bytes" };
59
+ }
60
+ function definedFields(fields) {
61
+ return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== void 0));
62
+ }
63
+ function queryKeyInit(init, client) {
64
+ const { signal: _signal, ...rest } = init ?? {};
65
+ const keyInit = definedFields(rest);
66
+ if (typeof rest.headers === "object" && rest.headers !== null) {
67
+ keyInit.headers = plainHeaders(rest.headers);
68
+ }
69
+ const rawBody = rawBodyKey(rest.body);
70
+ if (rawBody !== void 0) {
71
+ Object.assign(keyInit, rawBody);
72
+ }
73
+ if (client.keyScope !== void 0) {
74
+ keyInit.keyScope = client.keyScope;
75
+ } else if (!rest.baseUrl && client.baseUrl) {
76
+ keyInit.baseUrl = client.baseUrl;
77
+ }
78
+ return Object.keys(keyInit).length === 0 ? void 0 : keyInit;
79
+ }
80
+
81
+ const ABORT_EVENT = "abort";
82
+ function withoutRelease(init) {
83
+ return { init, release: () => void 0 };
84
+ }
85
+ function withQuerySignal(init, querySignal) {
86
+ const { signal: ownSignal, ...rest } = init ?? {};
87
+ if (!ownSignal) {
88
+ return withoutRelease({ ...rest, signal: querySignal });
89
+ }
90
+ const controller = new AbortController();
91
+ const sources = [ownSignal, querySignal];
92
+ const aborted = sources.find((source) => source.aborted);
93
+ if (aborted !== void 0) {
94
+ controller.abort(aborted.reason);
95
+ return withoutRelease({ ...rest, signal: controller.signal });
96
+ }
97
+ const listeners = sources.map((source) => {
98
+ const listener = () => controller.abort(source.reason);
99
+ source.addEventListener(ABORT_EVENT, listener, { once: true });
100
+ return () => source.removeEventListener(ABORT_EVENT, listener);
101
+ });
102
+ return {
103
+ init: { ...rest, signal: controller.signal },
104
+ release: () => {
105
+ for (const remove of listeners) {
106
+ remove();
107
+ }
108
+ }
109
+ };
110
+ }
111
+
7
112
  const INFINITE_QUERY_KEY_MARKER = "infinite";
8
113
  const RESPONSE_ERROR_NAME = "ResponseError";
9
114
  class ResponseWithoutErrorBody extends Error {
@@ -29,33 +134,49 @@ function throwIfFailed(result) {
29
134
  }
30
135
  }
31
136
  const DEFAULT_PAGE_PARAM_NAME = "cursor";
32
- function pageInit(init, { pageParamName, pageParam, signal }) {
137
+ function pageInit(init, { pageParamName, pageParam }) {
33
138
  const { params, ...rest } = init ?? {};
34
139
  const page = pageParam === void 0 ? {} : { [pageParamName]: pageParam };
35
- return { ...rest, signal, params: { ...params, query: { ...params?.query, ...page } } };
140
+ return { ...rest, params: { ...params, query: { ...params?.query, ...page } } };
36
141
  }
37
- function createClient(client) {
38
- const queryFn = async ({
39
- queryKey,
40
- signal
41
- }) => {
42
- const [method, path, init] = queryKey;
142
+ function createClient(client, { keyScope } = {}) {
143
+ const keyClient = { baseUrl: client.baseUrl, keyScope };
144
+ const fetchPage = async (method, path, init, signal) => {
43
145
  const mth = method.toUpperCase();
44
146
  const fn = client[mth];
45
- const result = await fn(path, { signal, ...init });
46
- throwIfFailed(result);
47
- return result.data ?? null;
147
+ const request = withQuerySignal(init, signal);
148
+ try {
149
+ const result = await fn(path, request.init);
150
+ throwIfFailed(result);
151
+ return result.data;
152
+ } finally {
153
+ request.release();
154
+ }
155
+ };
156
+ const queryOptions = (method, path, ...[init, options]) => {
157
+ const keyInit = queryKeyInit(init, keyClient);
158
+ return {
159
+ queryKey: keyInit === void 0 ? [method, path] : [method, path, keyInit],
160
+ // TanStack Query rejects `undefined` query data. The fetch client gives `undefined` for
161
+ // every success without a body: a 204, `Content-Length: 0`, an empty chunked body, a HEAD
162
+ // request (upstream #2234). A parsed body is never `undefined`, so this changes nothing else.
163
+ queryFn: async ({ signal }) => await fetchPage(method, path, init, signal) ?? null,
164
+ // Without options, `Options` is its constraint, which has no `initialData` to keep.
165
+ ...options
166
+ // The declared type types a defined `initialData` as the query data, a conditional type of
167
+ // the generic options that TypeScript cannot relate to the object; it is the same object.
168
+ };
48
169
  };
49
- const queryOptions = (method, path, ...[init, options]) => ({
50
- queryKey: init === void 0 ? [method, path] : [method, path, init],
51
- queryFn,
52
- ...options
53
- });
54
170
  return {
55
171
  queryOptions,
56
- useQuery: (method, path, ...[init, options, queryClient]) => reactQuery.useQuery(
57
- queryOptions(method, path, init, options),
58
- queryClient
172
+ useQuery: (method, path, ...[init, options, queryClient]) => (
173
+ // TanStack Query's `useQuery` returns `DefinedUseQueryResult` for options with defined
174
+ // `initialData`; while `Options` is generic it cannot pick that overload, and the declared
175
+ // `QueryResult` gives the caller the same answer. Both are the same object at runtime.
176
+ reactQuery.useQuery(
177
+ queryOptions(method, path, init, options),
178
+ queryClient
179
+ )
59
180
  ),
60
181
  useSuspenseQuery: (method, path, ...[init, options, queryClient]) => reactQuery.useSuspenseQuery(
61
182
  queryOptions(method, path, init, options),
@@ -65,21 +186,12 @@ function createClient(client) {
65
186
  useInfiniteQuery: (method, path, init, options, queryClient) => {
66
187
  const { pageParamName = DEFAULT_PAGE_PARAM_NAME, placeholderData, ...restOptions } = options;
67
188
  const { queryKey } = queryOptions(method, path, init);
68
- const mth = method.toUpperCase();
69
- const fn = client[mth];
70
189
  return reactQuery.useInfiniteQuery(
71
190
  {
72
191
  queryKey: [...queryKey, INFINITE_QUERY_KEY_MARKER],
73
- // The request comes from the arguments; the key only identifies the cache entry.
74
- queryFn: async ({ pageParam, signal }) => {
75
- const result = await fn(
76
- path,
77
- // biome-ignore lint/suspicious/noExplicitAny: a generic init; see queryFn
78
- pageInit(init, { pageParamName, pageParam, signal })
79
- );
80
- throwIfFailed(result);
81
- return result.data;
82
- },
192
+ // An empty page stays `undefined`, as in upstream: TanStack Query rejects only
193
+ // `undefined` query data, and the infinite query data is the `{ pages }` object.
194
+ queryFn: ({ pageParam, signal }) => fetchPage(method, path, pageInit(init, { pageParamName, pageParam }), signal),
83
195
  ...restOptions,
84
196
  // Typed with an `unknown` page param for the caller (`InfinitePlaceholderData`). TanStack
85
197
  // passes the previous data of this query, with its own page params, and takes it back.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["import {\n type DataTag,\n type DefaultError,\n type InfiniteData,\n type QueryClient,\n type QueryFunctionContext,\n type SkipToken,\n type UseInfiniteQueryOptions,\n type UseInfiniteQueryResult,\n type UseMutationOptions,\n type UseMutationResult,\n type UseQueryOptions,\n type UseQueryResult,\n type UseSuspenseQueryOptions,\n type UseSuspenseQueryResult,\n useInfiniteQuery,\n useMutation,\n useQuery,\n useSuspenseQuery,\n} from \"@tanstack/react-query\";\nimport type {\n ClientMethod,\n DefaultParamsOption,\n Client as FetchClient,\n FetchResponse,\n MaybeOptionalInit,\n PathOperation,\n} from \"openapi-typesafe-fetch\";\n// The helper types come from the client, which declares them: types inferred from the hooks then\n// print the client's `helpers` entry, of a peer every user has, and not `openapi-typesafe-helpers`,\n// which Yarn PnP does not let a library reach (ADR-034).\nimport type {\n HttpMethod,\n MediaType,\n PathsWithMethod,\n RequiredKeysOf,\n} from \"openapi-typesafe-fetch/helpers\";\n\n// Helper type to dynamically infer the type from the `select` property\ntype InferSelectReturnType<TData, TSelect> = TSelect extends (data: TData) => infer R ? R : TData;\n\n/**\n * Query data of a response type: a success without a body is `undefined` in the fetch client and\n * `null` in the query, as `queryFn` resolves it (upstream #2234, #2464).\n */\ntype QueryData<Data> = undefined extends Data ? Exclude<Data, undefined> | null : Data;\n\n/**\n * What the hooks throw when a request fails and the response has no error body: a non-OK status\n * with an empty body, a JSON `null` body, or one whose operation declares no content for it. The\n * fetch client gives `error: undefined` (or `null`) then; throwing that left `error` empty in\n * TanStack Query while its type said there was an error body. Tell it apart with\n * `isResponseError(error)`: `error instanceof Error` also matches a network or parse error. The\n * message names the status, not the URL, which can carry secrets.\n */\nexport interface ResponseError extends Error {\n readonly name: \"ResponseError\";\n /** The response that failed. */\n readonly response: Response;\n /** Its HTTP status, as `response.status`. */\n readonly status: number;\n}\n\n/**\n * The error of a hook: the error body of a failed response, a `ResponseError` when it has none, or\n * what the request threw before there was a response to read: a network error (`TypeError`), an\n * abort, a body that is not JSON (`SyntaxError`) or a middleware error. TanStack Query types that\n * last part as `DefaultError` (`Error` unless `Register` says otherwise; a registered `unknown`\n * makes the whole type `unknown`, as for TanStack's own hooks). `undefined` and `null` are left\n * out: a failed response without an error body throws a `ResponseError`.\n */\nexport type QueryError<ErrorBody> =\n | Exclude<ErrorBody, undefined | null>\n | ResponseError\n | DefaultError;\n\n/**\n * An object whose `queryKey` is tagged with the query's data and error types: the type that\n * TanStack Query 5.102 exports as `QueryKeyWithDataTag`, for the whole peer range. A named object\n * type, so the declarations of an exported `queryOptions` result print it by name. Spelled out,\n * the tag prints TanStack's `dataTagSymbol` keys, which a declaration file cannot import, and\n * the library's users get TS2304, or `any` cached data with `skipLibCheck`.\n */\nexport type QueryKeyWithDataTag<Key, Data, Error> = {\n queryKey: DataTag<Key, Data, Error>;\n};\n\ntype InitWithUnknowns<Init> = Init & { [key: string]: unknown };\n\n/**\n * The arguments after the path: the init, required when the operation requires a parameter or a\n * body, then `Rest`. The condition is openapi-react-query's, as `InitParam` of the fetch client\n * is openapi-fetch's (ADR-030, decision 2): TypeScript relates two conditional types only when\n * their `extends` types are the same, so a hook type copied from openapi-react-query takes these\n * hooks. For a union of inits, `MaybeOptionalInit` leaves out `undefined` when one is required,\n * so `Parameters<typeof $api.queryOptions>` still requires it then (upstream #2178).\n */\ntype InitArguments<Init, Rest extends unknown[]> =\n RequiredKeysOf<Init> extends never\n ? [InitWithUnknowns<Init>?, ...Rest]\n : [InitWithUnknowns<Init>, ...Rest];\n\nexport type QueryKey<\n Paths extends {},\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n Init = MaybeOptionalInit<Paths[Path], Method>,\n> = Init extends undefined ? readonly [Method, Path] : readonly [Method, Path, Init];\n\n/**\n * The last element of an infinite query's key. `useQuery` and `useInfiniteQuery` cache different\n * data (`TData` and `InfiniteData<TData>`), so the same request must not share one key (upstream\n * #2184, ADR-022). A prefix such as `[method, path]` still matches both. Not exported: it is not\n * needed outside the package, and a named export is public API; `InfiniteQueryKey` types the key.\n */\nconst INFINITE_QUERY_KEY_MARKER = \"infinite\";\n\nexport type InfiniteQueryKey<\n Paths extends {},\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n> = readonly [...QueryKey<Paths, Method, Path>, typeof INFINITE_QUERY_KEY_MARKER];\n\nexport type QueryOptionsFunction<Paths extends {}, Media extends MediaType> = <\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n Init extends MaybeOptionalInit<Paths[Path], Method>,\n // note: Required is used to avoid repeating NonNullable in UseQuery types\n Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>,\n Options extends Omit<\n UseQueryOptions<\n QueryData<Response[\"data\"]>,\n QueryError<Response[\"error\"]>,\n InferSelectReturnType<QueryData<Response[\"data\"]>, Options[\"select\"]>,\n QueryKey<Paths, Method, Path>\n >,\n \"queryKey\" | \"queryFn\"\n >,\n>(\n method: Method,\n path: Path,\n ...[init, options]: InitArguments<Init, [Options?]>\n) => NoInfer<\n Omit<\n UseQueryOptions<\n QueryData<Response[\"data\"]>,\n QueryError<Response[\"error\"]>,\n InferSelectReturnType<QueryData<Response[\"data\"]>, Options[\"select\"]>,\n QueryKey<Paths, Method, Path>\n >,\n \"queryFn\" | \"queryKey\"\n > &\n QueryKeyWithDataTag<\n QueryKey<Paths, Method, Path>,\n QueryData<Response[\"data\"]>,\n QueryError<Response[\"error\"]>\n > & {\n queryFn: Exclude<\n UseQueryOptions<\n QueryData<Response[\"data\"]>,\n QueryError<Response[\"error\"]>,\n InferSelectReturnType<QueryData<Response[\"data\"]>, Options[\"select\"]>,\n QueryKey<Paths, Method, Path>\n >[\"queryFn\"],\n SkipToken | undefined\n >;\n }\n>;\n\nexport type UseQueryMethod<Paths extends {}, Media extends MediaType> = <\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n Init extends MaybeOptionalInit<Paths[Path], Method>,\n // note: Required is used to avoid repeating NonNullable in UseQuery types\n Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>,\n Options extends Omit<\n UseQueryOptions<\n QueryData<Response[\"data\"]>,\n QueryError<Response[\"error\"]>,\n InferSelectReturnType<QueryData<Response[\"data\"]>, Options[\"select\"]>,\n QueryKey<Paths, Method, Path>\n >,\n \"queryKey\" | \"queryFn\"\n >,\n>(\n method: Method,\n url: Path,\n ...[init, options, queryClient]: InitArguments<Init, [Options?, QueryClient?]>\n) => UseQueryResult<\n InferSelectReturnType<QueryData<Response[\"data\"]>, Options[\"select\"]>,\n QueryError<Response[\"error\"]>\n>;\n\n/**\n * The type of the page params: the initial one and the ones `getNextPageParam` and\n * `getPreviousPageParam` return (upstream #2458). It was `unknown`. It stays `unknown` when a\n * return type is untyped, so code that compiled still compiles (roadmap §3): TypeScript cannot\n * infer the return type of a callback that computes it from an unannotated `lastPageParam`,\n * whose type depends on that return type, and gives `never` or `unknown`.\n */\ntype PageParam<Initial, Next, Previous> =\n IsUntyped<Next> extends true\n ? unknown\n : [Previous] extends [NoPreviousPageParam]\n ? NullishToUnknown<Initial | NonNullable<Next>>\n : IsUntyped<Previous> extends true\n ? unknown\n : NullishToUnknown<Initial | NonNullable<Next> | NonNullable<Previous>>;\n\n/** The `Previous` type parameter when the options have no `getPreviousPageParam`. */\ndeclare const NO_PREVIOUS_PAGE_PARAM: unique symbol;\ntype NoPreviousPageParam = typeof NO_PREVIOUS_PAGE_PARAM;\n\ntype IsUntyped<T> = [T] extends [never] ? true : unknown extends T ? true : false;\n\n/** Only `undefined` or `null` names no type: a cursor API's `initialPageParam: undefined`. */\ntype NullishToUnknown<T> = [T] extends [undefined | null] ? unknown : T;\n\n/** Read only for the return type; `never` arguments add no inference for TanStack's page param. */\ntype PageParamFunction<Result> = (...args: never) => Result;\n\n/**\n * Inference sites of the page param types. Intersected before `Options`, so TanStack's own\n * inference in the implementation reads the full signatures of `Options`.\n */\ninterface PageParamSources<Initial, Next, Previous> {\n initialPageParam: Initial;\n getNextPageParam: PageParamFunction<Next>;\n getPreviousPageParam?: PageParamFunction<Previous>;\n}\n\n/**\n * `placeholderData` of `useInfiniteQuery`, with an `unknown` page param as before: TypeScript types\n * a `(previousData) => previousData` callback while it still infers the page param, so it got\n * `unknown` there and failed against the typed page param.\n */\ntype InfinitePlaceholderData<\n Data,\n Error,\n Paths extends {},\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n> = UseInfiniteQueryOptions<\n Data,\n Error,\n InfiniteData<Data, unknown>,\n InfiniteQueryKey<Paths, Method, Path>,\n unknown\n>[\"placeholderData\"];\n\nexport type UseInfiniteQueryMethod<Paths extends {}, Media extends MediaType> = <\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n Init extends MaybeOptionalInit<Paths[Path], Method>,\n Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>,\n Options extends Omit<\n UseInfiniteQueryOptions<\n Response[\"data\"],\n QueryError<Response[\"error\"]>,\n InferSelectReturnType<\n InfiniteData<Response[\"data\"], PageParam<Initial, Next, Previous>>,\n Options[\"select\"]\n >,\n InfiniteQueryKey<Paths, Method, Path>,\n PageParam<Initial, Next, Previous>\n >,\n \"queryKey\" | \"queryFn\" | \"placeholderData\"\n > & {\n placeholderData?: InfinitePlaceholderData<\n Response[\"data\"],\n QueryError<Response[\"error\"]>,\n Paths,\n Method,\n Path\n >;\n pageParamName?: string;\n },\n Initial = unknown,\n Next = never,\n Previous = NoPreviousPageParam,\n // biome-ignore lint/complexity/useMaxParams: public signature of 1.x (ADR-036)\n>(\n method: Method,\n url: Path,\n init: InitWithUnknowns<Init>,\n options: PageParamSources<Initial, Next, Previous> & Options,\n queryClient?: QueryClient,\n) => UseInfiniteQueryResult<\n InferSelectReturnType<\n InfiniteData<Response[\"data\"], PageParam<Initial, Next, Previous>>,\n Options[\"select\"]\n >,\n QueryError<Response[\"error\"]>\n>;\n\nexport type UseSuspenseQueryMethod<Paths extends {}, Media extends MediaType> = <\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n Init extends MaybeOptionalInit<Paths[Path], Method>,\n // note: Required is used to avoid repeating NonNullable in UseQuery types\n Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>,\n Options extends Omit<\n UseSuspenseQueryOptions<\n QueryData<Response[\"data\"]>,\n QueryError<Response[\"error\"]>,\n InferSelectReturnType<QueryData<Response[\"data\"]>, Options[\"select\"]>,\n QueryKey<Paths, Method, Path>\n >,\n \"queryKey\" | \"queryFn\"\n >,\n>(\n method: Method,\n url: Path,\n ...[init, options, queryClient]: InitArguments<Init, [Options?, QueryClient?]>\n) => UseSuspenseQueryResult<\n InferSelectReturnType<QueryData<Response[\"data\"]>, Options[\"select\"]>,\n QueryError<Response[\"error\"]>\n>;\n\nexport type UseMutationMethod<Paths extends {}, Media extends MediaType> = <\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n Init extends MaybeOptionalInit<Paths[Path], Method>,\n // note: Required is used to avoid repeating NonNullable in UseQuery types\n Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>,\n TOnMutateResult = unknown,\n>(\n method: Method,\n url: Path,\n options?: Omit<\n UseMutationOptions<Response[\"data\"], QueryError<Response[\"error\"]>, Init, TOnMutateResult>,\n \"mutationKey\" | \"mutationFn\"\n >,\n queryClient?: QueryClient,\n) => UseMutationResult<Response[\"data\"], QueryError<Response[\"error\"]>, Init, TOnMutateResult>;\n\nexport interface OpenapiQueryClient<Paths extends {}, Media extends MediaType = MediaType> {\n queryOptions: QueryOptionsFunction<Paths, Media>;\n useQuery: UseQueryMethod<Paths, Media>;\n useSuspenseQuery: UseSuspenseQueryMethod<Paths, Media>;\n useInfiniteQuery: UseInfiniteQueryMethod<Paths, Media>;\n useMutation: UseMutationMethod<Paths, Media>;\n}\n\nexport type MethodResponse<\n // biome-ignore lint/suspicious/noExplicitAny: matches a client of any paths, as upstream's\n CreatedClient extends OpenapiQueryClient<any, any>,\n Method extends HttpMethod,\n Path extends CreatedClient extends OpenapiQueryClient<infer Paths, infer _Media>\n ? PathsWithMethod<Paths, Method>\n : never,\n Options = object,\n> =\n CreatedClient extends OpenapiQueryClient<\n // biome-ignore lint/suspicious/noExplicitAny: unknown rejects the generated interfaces\n infer Paths extends { [key: string]: any },\n infer Media extends MediaType\n >\n ? NonNullable<FetchResponse<Paths[Path][Method], Options, Media>[\"data\"]>\n : never;\n\n/** The `name` of every `ResponseError`. */\nconst RESPONSE_ERROR_NAME = \"ResponseError\";\n\n/** The `ResponseError` of a failed response without an error body. */\nclass ResponseWithoutErrorBody extends Error implements ResponseError {\n override readonly name = RESPONSE_ERROR_NAME;\n readonly response: Response;\n readonly status: number;\n\n constructor(response: Response) {\n const statusText = response.statusText ? ` ${response.statusText}` : \"\";\n super(`Request failed with status ${response.status}${statusText} and no error body`);\n this.response = response;\n this.status = response.status;\n }\n}\n\n/**\n * Whether `error` is the `ResponseError` of a failed response without an error body. It narrows a\n * hook's `error`, where `error instanceof Error` also matches network and parse errors. It checks\n * the `name`, not the class, so a `ResponseError` of another copy of this package (its CommonJS and\n * ES module builds loaded side by side) is one too. An error body from JSON is never an `Error`.\n */\nexport function isResponseError(error: unknown): error is ResponseError {\n return error instanceof Error && error.name === RESPONSE_ERROR_NAME;\n}\n\n/**\n * Throw the error of a failed fetch result. `if (error)` missed two failures: a non-OK response\n * with an empty body (`error` is `undefined`, upstream #2070, #2829) and a falsy error body such as\n * `0`. Without an error body a `ResponseError` is thrown, so the hooks' `error` is never\n * `undefined` (ADR-013, decision 3). A JSON `null` body is no error body either: thrown as is, it\n * left `error` `null` while the query's status was `\"error\"`.\n */\nfunction throwIfFailed(result: { error?: unknown; response: Response }): void {\n if (result.error !== undefined && result.error !== null) {\n throw result.error;\n }\n if (!result.response.ok) {\n throw new ResponseWithoutErrorBody(result.response);\n }\n}\n\n/** The query parameter that carries the page param unless `pageParamName` names another. */\nconst DEFAULT_PAGE_PARAM_NAME = \"cursor\";\n\ninterface PageRequest {\n readonly pageParamName: string;\n readonly pageParam: unknown;\n readonly signal: AbortSignal;\n}\n\n/**\n * The request init of one page. An `undefined` page param (the first page with\n * `initialPageParam: undefined`) is left out instead of being sent as `0` (upstream #2715, #2340,\n * ADR-022), so a cursor API gets no cursor on the first page.\n */\nfunction pageInit(init: unknown, { pageParamName, pageParam, signal }: PageRequest) {\n const { params, ...rest } = (init ?? {}) as { params?: { query?: DefaultParamsOption } };\n const page = pageParam === undefined ? {} : { [pageParamName]: pageParam };\n return { ...rest, signal, params: { ...params, query: { ...params?.query, ...page } } };\n}\n\n/**\n * Hooks and query options for a fetch client. A `QueryClient` other than the one from the React\n * context is passed to each hook as its last argument; `createClient` does not take one.\n */\n// biome-ignore lint/complexity/noExcessiveLinesPerFunction: inherited, kept until 1.1 (ADR-036)\nexport default function createClient<Paths extends {}, Media extends MediaType = MediaType>(\n client: FetchClient<Paths, Media>,\n): OpenapiQueryClient<Paths, Media> {\n const queryFn = async <Method extends HttpMethod, Path extends PathsWithMethod<Paths, Method>>({\n queryKey,\n signal,\n }: QueryFunctionContext<QueryKey<Paths, Method, Path>>) => {\n // While `Path` is generic, TypeScript cannot work out that the key is a tuple: the init is a\n // conditional type per operation (`MaybeOptionalInit`), and the key's type waits for it.\n const [method, path, init] = queryKey as readonly [Method, Path, unknown?];\n const mth = method.toUpperCase() as Uppercase<typeof method>;\n const fn = client[mth] as ClientMethod<Paths, typeof method, Media>;\n // The init is `unknown` here. An `any` init lets the call infer the generic response type\n // that `queryOptions` declares; a typed init makes TypeScript compare two unresolved\n // conditional types, which it cannot do.\n // biome-ignore lint/suspicious/noExplicitAny: see the comment above\n const result = await fn(path, { signal, ...(init as any) });\n throwIfFailed(result);\n // TanStack Query rejects `undefined` query data. The fetch client gives `undefined` for every\n // success without a body: a 204, `Content-Length: 0`, an empty chunked body, a HEAD request\n // (upstream #2234). A parsed body is never `undefined`, so this changes nothing else.\n return result.data ?? null;\n };\n\n const queryOptions: QueryOptionsFunction<Paths, Media> = (method, path, ...[init, options]) => ({\n queryKey: (init === undefined\n ? ([method, path] as const)\n : ([method, path, init] as const)) as DataTag<\n QueryKey<Paths, typeof method, typeof path>,\n // biome-ignore lint/suspicious/noExplicitAny: the declared return type sets the data type\n any,\n // biome-ignore lint/suspicious/noExplicitAny: the declared return type sets the error type\n any\n >,\n queryFn,\n ...options,\n });\n\n return {\n queryOptions,\n useQuery: (method, path, ...[init, options, queryClient]) =>\n useQuery(\n queryOptions(method, path, init as InitWithUnknowns<typeof init>, options),\n queryClient,\n ),\n useSuspenseQuery: (method, path, ...[init, options, queryClient]) =>\n useSuspenseQuery(\n queryOptions(method, path, init as InitWithUnknowns<typeof init>, options),\n queryClient,\n ),\n // biome-ignore lint/complexity/useMaxParams: public signature of 1.x (ADR-036)\n useInfiniteQuery: (method, path, init, options, queryClient) => {\n const { pageParamName = DEFAULT_PAGE_PARAM_NAME, placeholderData, ...restOptions } = options;\n const { queryKey } = queryOptions(method, path, init);\n const mth = method.toUpperCase() as Uppercase<typeof method>;\n const fn = client[mth] as ClientMethod<Paths, typeof method, Media>;\n return useInfiniteQuery(\n {\n queryKey: [...queryKey, INFINITE_QUERY_KEY_MARKER] as const,\n // The request comes from the arguments; the key only identifies the cache entry.\n queryFn: async ({ pageParam, signal }) => {\n const result = await fn(\n path,\n // biome-ignore lint/suspicious/noExplicitAny: a generic init; see queryFn\n pageInit(init, { pageParamName, pageParam, signal }) as any,\n );\n throwIfFailed(result);\n // An empty page stays `undefined`, as in upstream: TanStack Query rejects only\n // `undefined` query data, and the infinite query data is the `{ pages }` object.\n return result.data;\n },\n ...restOptions,\n // Typed with an `unknown` page param for the caller (`InfinitePlaceholderData`). TanStack\n // passes the previous data of this query, with its own page params, and takes it back.\n // biome-ignore lint/suspicious/noExplicitAny: TanStack's type carries its own page params\n placeholderData: placeholderData as any,\n },\n queryClient,\n );\n },\n useMutation: (method, path, options, queryClient) =>\n useMutation(\n {\n mutationKey: [method, path],\n mutationFn: async (init) => {\n const mth = method.toUpperCase() as Uppercase<typeof method>;\n const fn = client[mth] as ClientMethod<Paths, typeof method, Media>;\n const result = await fn(path, init as InitWithUnknowns<typeof init>);\n throwIfFailed(result);\n // TanStack Query accepts `undefined` mutation data, so a success without a body stays\n // `undefined`, as in upstream; only query data needs `null` (upstream #2234). The cast\n // only bridges the generic types: `Response[\"data\"]` still has `undefined` for an\n // operation with a response without a body.\n const { data } = result;\n return data as Exclude<typeof data, undefined>;\n },\n ...options,\n },\n queryClient,\n ),\n };\n}\n"],"names":["useQuery","useSuspenseQuery","useInfiniteQuery","useMutation"],"mappings":";;;;;;AAmHA,MAAM,yBAAA,GAA4B,UAAA;AAuPlC,MAAM,mBAAA,GAAsB,eAAA;AAG5B,MAAM,iCAAiC,KAAA,CAA+B;AAAA,EAClD,IAAA,GAAO,mBAAA;AAAA,EAChB,QAAA;AAAA,EACA,MAAA;AAAA,EAET,YAAY,QAAA,EAAoB;AAC9B,IAAA,MAAM,aAAa,QAAA,CAAS,UAAA,GAAa,CAAA,CAAA,EAAI,QAAA,CAAS,UAAU,CAAA,CAAA,GAAK,EAAA;AACrE,IAAA,KAAA,CAAM,CAAA,2BAAA,EAA8B,QAAA,CAAS,MAAM,CAAA,EAAG,UAAU,CAAA,kBAAA,CAAoB,CAAA;AACpF,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAChB,IAAA,IAAA,CAAK,SAAS,QAAA,CAAS,MAAA;AAAA,EACzB;AACF;AAQO,SAAS,gBAAgB,KAAA,EAAwC;AACtE,EAAA,OAAO,KAAA,YAAiB,KAAA,IAAS,KAAA,CAAM,IAAA,KAAS,mBAAA;AAClD;AASA,SAAS,cAAc,MAAA,EAAuD;AAC5E,EAAA,IAAI,MAAA,CAAO,KAAA,KAAU,MAAA,IAAa,MAAA,CAAO,UAAU,IAAA,EAAM;AACvD,IAAA,MAAM,MAAA,CAAO,KAAA;AAAA,EACf;AACA,EAAA,I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aAAA,CAAc,MAAM,CAAA;AAGpB,YAAA,OAAO,MAAA,CAAO,IAAA;AAAA,UAChB,CAAA;AAAA,UACA,GAAG,WAAA;AAAA;AAAA;AAAA;AAAA,UAIH;AAAA,SACF;AAAA,QACA;AAAA,OACF;AAAA,IACF,CAAA;AAAA,IACA,WAAA,EAAa,CAAC,MAAA,EAAQ,IAAA,EAAM,SAAS,WAAA,KACnCC,sBAAA;AAAA,MACE;AAAA,QACE,WAAA,EAAa,CAAC,MAAA,EAAQ,IAAI,CAAA;AAAA,QAC1B,UAAA,EAAY,OAAO,IAAA,KAAS;AAC1B,UAAA,MAAM,GAAA,GAAM,OAAO,WAAA,EAAY;AAC/B,UAAA,MAAM,EAAA,GAAK,OAAO,GAAG,CAAA;AACrB,UAAA,MAAM,MAAA,GAAS,MAAM,EAAA,CAAG,IAAA,EAAM,IAAqC,CAAA;AACnE,UAAA,aAAA,CAAc,MAAM,CAAA;AAKpB,UAAA,MAAM,EAAE,MAAK,GAAI,MAAA;AACjB,UAAA,OAAO,IAAA;AAAA,QACT,CAAA;AAAA,QACA,GAAG;AAAA,OACL;AAAA,MACA;AAAA;AACF,GACJ;AACF;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":["../src/query-key.ts","../src/query-signal.ts","../src/index.ts"],"sourcesContent":["/**\n * The request part of a query key (ADR-046). TanStack Query hashes a key as JSON: a `Headers`\n * object or a list of header pairs hashed as `{}` or by its order, and so did a FormData, a Blob,\n * an ArrayBuffer or a URLSearchParams body. Two requests that differed in them shared one cache\n * entry, and the `queryFn` of that entry sent the request of the first. Two clients with\n * different base URLs shared entries too. The key's init holds the headers and such a body as\n * plain values, and the base URL the request goes to or the client's key scope, so the key names\n * what was fetched.\n */\n\n/** Headers as a plain object, which TanStack Query hashes by its names and values. */\ntype HeadersRecord = Readonly<Record<string, unknown>>;\n\n/** What the key takes from the fetch client and the options of `createClient`. */\nexport interface KeyClient {\n /** The fetch client's base URL, `\"\"` without one. */\n readonly baseUrl: string;\n /** The name of the API in every key, in place of the base URL. */\n readonly keyScope?: string | undefined;\n}\n\n/** `[object Name]`: the type tag is between these indexes of `Object.prototype.toString`. */\nconst TYPE_TAG_START = \"[object \".length;\nconst TYPE_TAG_END = -1;\n\n/**\n * Whether a value is of the class `name`: an instance of this realm's global class of that name\n * (React Native's classes have no type tag), or a value with its type tag (a class of another\n * realm or of the `undici` package), as the fetch client tells bodies (ADR-030).\n */\nfunction isClass(value: object, name: string): boolean {\n const type = (globalThis as Record<string, unknown>)[name];\n return (\n (typeof type === \"function\" && value instanceof type) ||\n Object.prototype.toString.call(value).slice(TYPE_TAG_START, TYPE_TAG_END) === name\n );\n}\n\n/**\n * The headers of an init as a plain object. A `Headers` object and a list of pairs, which are both\n * iterable, become the names and values the request sends: names in lowercase, a repeated one\n * joined with `, `, as `Headers` writes them. They are read without `Headers`, which threw for an\n * invalid name or value while the component rendered; the request reports it as a query error. A\n * plain object stays as it is, since its `null` and array values mean more than a string.\n */\nfunction plainHeaders(headers: object): HeadersRecord {\n if (!(Symbol.iterator in headers)) {\n return headers as HeadersRecord;\n }\n const record: Record<string, string> = {};\n for (const pair of headers as Iterable<unknown>) {\n const [name, value] = Array.from(pair as ArrayLike<unknown>);\n const key = String(name).toLowerCase();\n record[key] = key in record ? `${record[key]}, ${String(value)}` : String(value);\n }\n return record;\n}\n\n/**\n * A Blob or a File in a key: its type, size, and the name of a File. Its bytes cannot be read while\n * the component renders, so two Blobs of the same type and size share an entry. The date of a File\n * is left out: `FormData.append` and `new File` set it to the current time, so a body built while\n * rendering got a new key, and a new request, on every render.\n */\nfunction blobKey(blob: Blob): object {\n const { name } = blob as Partial<File>;\n return { type: blob.type, size: blob.size, name };\n}\n\n/** The fields of a FormData in a key, in order, with a file as `blobKey`. */\nfunction formDataKey(form: FormData): unknown[] {\n // React Native's FormData has no `entries`, so its fields cannot be read.\n if (typeof form.entries !== \"function\") {\n return [];\n }\n return Array.from(form.entries(), ([name, value]) => [\n name,\n typeof value === \"string\" ? value : blobKey(value),\n ]);\n}\n\n/** The bytes of an ArrayBuffer or a typed array, or null for another value. */\nfunction bodyBytes(body: object): Uint8Array | null {\n if (ArrayBuffer.isView(body)) {\n return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n }\n return isClass(body, \"ArrayBuffer\") ? new Uint8Array(body as ArrayBuffer) : null;\n}\n\n/** A body that JSON cannot hold, as a value TanStack Query hashes, and the name of its kind. */\ninterface RawBodyKey {\n readonly body: unknown;\n readonly bodyType: \"URLSearchParams\" | \"FormData\" | \"Blob\" | \"bytes\";\n}\n\n/**\n * A body that JSON cannot hold by its content: a URLSearchParams as its text, a FormData as its\n * fields, a Blob as `blobKey` and bytes as their numbers. Undefined for any other body.\n */\nfunction rawBodyKey(body: unknown): RawBodyKey | undefined {\n if (typeof body !== \"object\" || body === null) {\n return undefined;\n }\n if (isClass(body, \"URLSearchParams\")) {\n return { body: String(body), bodyType: \"URLSearchParams\" };\n }\n if (isClass(body, \"FormData\")) {\n return { body: formDataKey(body as FormData), bodyType: \"FormData\" };\n }\n if (isClass(body, \"Blob\") || isClass(body, \"File\")) {\n return { body: blobKey(body as Blob), bodyType: \"Blob\" };\n }\n const bytes = bodyBytes(body);\n return bytes === null ? undefined : { body: Array.from(bytes), bodyType: \"bytes\" };\n}\n\n/**\n * The init fields that are not `undefined`. A field set to `undefined` (`headers: token ? … :\n * undefined`) sends the same request as none, so it must not make the init count as not empty.\n */\nfunction definedFields(fields: object): Record<string, unknown> {\n return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));\n}\n\n/**\n * The init of a query key: the request init with its headers and body as plain values, and the\n * client's key scope, or its base URL when the init has none. The `signal` is left out: TanStack\n * Query gives each request its own. A body that JSON cannot hold also names its kind in\n * `bodyType`, a field no init has, so it never shares a key with a JSON body of the same content.\n * Undefined when nothing is left, so a call without an init and one with an empty init, or one\n * of only `undefined` fields, have the key `[method, path]`.\n */\nexport function queryKeyInit(init: unknown, client: KeyClient): object | undefined {\n const { signal: _signal, ...rest } = (init ?? {}) as {\n signal?: unknown;\n headers?: unknown;\n baseUrl?: unknown;\n body?: unknown;\n };\n const keyInit = definedFields(rest);\n if (typeof rest.headers === \"object\" && rest.headers !== null) {\n keyInit.headers = plainHeaders(rest.headers);\n }\n const rawBody = rawBodyKey(rest.body);\n if (rawBody !== undefined) {\n Object.assign(keyInit, rawBody);\n }\n if (client.keyScope !== undefined) {\n keyInit.keyScope = client.keyScope;\n } else if (!rest.baseUrl && client.baseUrl) {\n keyInit.baseUrl = client.baseUrl;\n }\n return Object.keys(keyInit).length === 0 ? undefined : keyInit;\n}\n","/**\n * The signal of a query's request. TanStack Query gives every request a signal, which it aborts\n * when the query is cancelled or no longer used; the init of the call may bring its own. The hooks\n * sent one of them: `useQuery` the call's, so a cancelled query kept its request, and\n * `useInfiniteQuery` TanStack's, so the call's signal did nothing. The request now stops when\n * either is aborted.\n */\n\n/** The init to send, and how to stop listening to the signals once the request has settled. */\nexport interface QueryRequest {\n readonly init: Record<string, unknown>;\n readonly release: () => void;\n}\n\nconst ABORT_EVENT = \"abort\";\n\nfunction withoutRelease(init: Record<string, unknown>): QueryRequest {\n return { init, release: () => undefined };\n}\n\n/** The init with a signal that aborts when the init's own signal or the query's does. */\nexport function withQuerySignal(init: unknown, querySignal: AbortSignal): QueryRequest {\n const { signal: ownSignal, ...rest } = (init ?? {}) as { signal?: AbortSignal | null };\n if (!ownSignal) {\n return withoutRelease({ ...rest, signal: querySignal });\n }\n const controller = new AbortController();\n const sources = [ownSignal, querySignal];\n const aborted = sources.find((source) => source.aborted);\n if (aborted !== undefined) {\n controller.abort(aborted.reason);\n return withoutRelease({ ...rest, signal: controller.signal });\n }\n const listeners = sources.map((source) => {\n const listener = () => controller.abort(source.reason);\n source.addEventListener(ABORT_EVENT, listener, { once: true });\n return () => source.removeEventListener(ABORT_EVENT, listener);\n });\n return {\n init: { ...rest, signal: controller.signal },\n release: () => {\n for (const remove of listeners) {\n remove();\n }\n },\n };\n}\n","import {\n type DataTag,\n type DefaultError,\n type DefinedUseQueryResult,\n type InfiniteData,\n type QueryClient,\n type QueryFunctionContext,\n type SkipToken,\n type UseInfiniteQueryOptions,\n type UseInfiniteQueryResult,\n type UseMutationOptions,\n type UseMutationResult,\n type UseQueryOptions,\n type UseQueryResult,\n type UseSuspenseQueryOptions,\n type UseSuspenseQueryResult,\n useInfiniteQuery,\n useMutation,\n useQuery,\n useSuspenseQuery,\n} from \"@tanstack/react-query\";\nimport type {\n ClientMethod,\n DefaultParamsOption,\n Client as FetchClient,\n FetchResponse,\n MaybeOptionalInit,\n PathOperation,\n} from \"openapi-typesafe-fetch\";\n// The helper types come from the client, which declares them: types inferred from the hooks then\n// print the client's `helpers` entry, of a peer every user has, and not `openapi-typesafe-helpers`,\n// which Yarn PnP does not let a library reach (ADR-034).\nimport type {\n HttpMethod,\n MediaType,\n PathsWithMethod,\n RequiredKeysOf,\n} from \"openapi-typesafe-fetch/helpers\";\nimport { queryKeyInit } from \"./query-key.js\";\nimport { withQuerySignal } from \"./query-signal.js\";\n\n// Helper type to dynamically infer the type from the `select` property\ntype InferSelectReturnType<TData, TSelect> = TSelect extends (data: TData) => infer R ? R : TData;\n\n/**\n * Query data of a response type: a success without a body is `undefined` in the fetch client and\n * `null` in the query, as `queryFn` resolves it (upstream #2234, #2464).\n */\ntype QueryData<Data> = undefined extends Data ? Exclude<Data, undefined> | null : Data;\n\n/**\n * What the hooks throw when a request fails and the response has no error body: a non-OK status\n * with an empty body, a JSON `null` body, or one whose operation declares no content for it. The\n * fetch client gives `error: undefined` (or `null`) then; throwing that left `error` empty in\n * TanStack Query while its type said there was an error body. Tell it apart with\n * `isResponseError(error)`: `error instanceof Error` also matches a network or parse error. The\n * message names the status, not the URL, which can carry secrets.\n */\nexport interface ResponseError extends Error {\n readonly name: \"ResponseError\";\n /** The response that failed. */\n readonly response: Response;\n /** Its HTTP status, as `response.status`. */\n readonly status: number;\n}\n\n/**\n * The error of a hook: the error body of a failed response, a `ResponseError` when it has none, or\n * what the request threw before there was a response to read: a network error (`TypeError`), an\n * abort, a body that is not JSON (`SyntaxError`) or a middleware error. TanStack Query types that\n * last part as `DefaultError` (`Error` unless `Register` says otherwise; a registered `unknown`\n * makes the whole type `unknown`, as for TanStack's own hooks). `undefined` and `null` are left\n * out: a failed response without an error body throws a `ResponseError`.\n */\nexport type QueryError<ErrorBody> =\n | Exclude<ErrorBody, undefined | null>\n | ResponseError\n | DefaultError;\n\n/**\n * An object whose `queryKey` is tagged with the query's data and error types: the type that\n * TanStack Query 5.102 exports as `QueryKeyWithDataTag`, for the whole peer range. A named object\n * type, so the declarations of an exported `queryOptions` result print it by name. Spelled out,\n * the tag prints TanStack's `dataTagSymbol` keys, which a declaration file cannot import, and\n * the library's users get TS2304, or `any` cached data with `skipLibCheck`.\n */\nexport type QueryKeyWithDataTag<Key, Data, Error> = {\n queryKey: DataTag<Key, Data, Error>;\n};\n\ntype InitWithUnknowns<Init> = Init & { [key: string]: unknown };\n\n/**\n * The arguments after the path: the init, required when the operation requires a parameter or a\n * body, then `Rest`. The condition is openapi-react-query's, as `InitParam` of the fetch client\n * is openapi-fetch's (ADR-030, decision 2): TypeScript relates two conditional types only when\n * their `extends` types are the same, so a hook type copied from openapi-react-query takes these\n * hooks. For a union of inits, `MaybeOptionalInit` leaves out `undefined` when one is required,\n * so `Parameters<typeof $api.queryOptions>` still requires it then (upstream #2178).\n */\ntype InitArguments<Init, Rest extends unknown[]> =\n RequiredKeysOf<Init> extends never\n ? [InitWithUnknowns<Init>?, ...Rest]\n : [InitWithUnknowns<Init>, ...Rest];\n\n/**\n * The key of a query: the method, the path and the request. Its init is the init of the call with\n * the headers and the body as plain values, and the client's `keyScope`, or its `baseUrl` when the\n * init has none, so two requests never share a key; it is left out when nothing is left. Read a\n * query's key from `queryOptions(...).queryKey` rather than writing it out.\n */\nexport type QueryKey<\n Paths extends {},\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n Init = MaybeOptionalInit<Paths[Path], Method>,\n> = Init extends undefined ? readonly [Method, Path] : readonly [Method, Path, Init];\n\n/**\n * The last element of an infinite query's key. `useQuery` and `useInfiniteQuery` cache different\n * data (`TData` and `InfiniteData<TData>`), so the same request must not share one key (upstream\n * #2184, ADR-022). A prefix such as `[method, path]` still matches both. Not exported: it is not\n * needed outside the package, and a named export is public API; `InfiniteQueryKey` types the key.\n */\nconst INFINITE_QUERY_KEY_MARKER = \"infinite\";\n\nexport type InfiniteQueryKey<\n Paths extends {},\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n> = readonly [...QueryKey<Paths, Method, Path>, typeof INFINITE_QUERY_KEY_MARKER];\n\n/**\n * Whether the options give an `initialData` that is never `undefined`: a value, or a function that\n * never returns `undefined`. Then `data` is never `undefined` either, as for TanStack Query's own\n * `useQuery` with `DefinedInitialDataOptions`.\n */\ntype HasDefinedInitialData<Options> = Options extends { initialData: infer Initial }\n ? Initial extends (...args: never) => infer Returned\n ? undefined extends Returned\n ? false\n : true\n : undefined extends Initial\n ? false\n : true\n : false;\n\n/** The result of `useQuery`: its `data` is defined when the options give defined initial data. */\ntype QueryResult<Data, Error, Options> =\n HasDefinedInitialData<Options> extends true\n ? DefinedUseQueryResult<Data, Error>\n : UseQueryResult<Data, Error>;\n\n/**\n * A defined `initialData` of the options, in the type `queryOptions` returns, so TanStack Query's\n * `useQuery` takes the result as options with defined initial data. It is typed as the query data,\n * as TanStack's `DefinedInitialDataOptions` types it: the type of a literal such as `[{ id: 1 }]`\n * lacks the optional properties of the data, and TanStack's overload rejected it.\n */\ntype InitialDataOf<Options, Data> =\n HasDefinedInitialData<Options> extends true ? { initialData: Data | (() => Data) } : unknown;\n\nexport type QueryOptionsFunction<Paths extends {}, Media extends MediaType> = <\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n Init extends MaybeOptionalInit<Paths[Path], Method>,\n // note: Required is used to avoid repeating NonNullable in UseQuery types\n Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>,\n Options extends Omit<\n UseQueryOptions<\n QueryData<Response[\"data\"]>,\n QueryError<Response[\"error\"]>,\n InferSelectReturnType<QueryData<Response[\"data\"]>, Options[\"select\"]>,\n QueryKey<Paths, Method, Path>\n >,\n \"queryKey\" | \"queryFn\"\n >,\n>(\n method: Method,\n path: Path,\n ...[init, options]: InitArguments<Init, [Options?]>\n) => NoInfer<\n Omit<\n UseQueryOptions<\n QueryData<Response[\"data\"]>,\n QueryError<Response[\"error\"]>,\n InferSelectReturnType<QueryData<Response[\"data\"]>, Options[\"select\"]>,\n QueryKey<Paths, Method, Path>\n >,\n \"queryFn\" | \"queryKey\"\n > &\n QueryKeyWithDataTag<\n QueryKey<Paths, Method, Path>,\n QueryData<Response[\"data\"]>,\n QueryError<Response[\"error\"]>\n > &\n InitialDataOf<Options, QueryData<Response[\"data\"]>> & {\n queryFn: Exclude<\n UseQueryOptions<\n QueryData<Response[\"data\"]>,\n QueryError<Response[\"error\"]>,\n InferSelectReturnType<QueryData<Response[\"data\"]>, Options[\"select\"]>,\n QueryKey<Paths, Method, Path>\n >[\"queryFn\"],\n SkipToken | undefined\n >;\n }\n>;\n\nexport type UseQueryMethod<Paths extends {}, Media extends MediaType> = <\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n Init extends MaybeOptionalInit<Paths[Path], Method>,\n // note: Required is used to avoid repeating NonNullable in UseQuery types\n Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>,\n Options extends Omit<\n UseQueryOptions<\n QueryData<Response[\"data\"]>,\n QueryError<Response[\"error\"]>,\n InferSelectReturnType<QueryData<Response[\"data\"]>, Options[\"select\"]>,\n QueryKey<Paths, Method, Path>\n >,\n \"queryKey\" | \"queryFn\"\n >,\n>(\n method: Method,\n url: Path,\n ...[init, options, queryClient]: InitArguments<Init, [Options?, QueryClient?]>\n) => QueryResult<\n InferSelectReturnType<QueryData<Response[\"data\"]>, Options[\"select\"]>,\n QueryError<Response[\"error\"]>,\n Options\n>;\n\n/**\n * The type of the page params: the initial one and the ones `getNextPageParam` and\n * `getPreviousPageParam` return (upstream #2458). It was `unknown`. It stays `unknown` when a\n * return type is untyped, so code that compiled still compiles (roadmap §3): TypeScript cannot\n * infer the return type of a callback that computes it from an unannotated `lastPageParam`,\n * whose type depends on that return type, and gives `never` or `unknown`.\n */\ntype PageParam<Initial, Next, Previous> =\n IsUntyped<Next> extends true\n ? unknown\n : [Previous] extends [NoPreviousPageParam]\n ? NullishToUnknown<Initial | NonNullable<Next>>\n : IsUntyped<Previous> extends true\n ? unknown\n : NullishToUnknown<Initial | NonNullable<Next> | NonNullable<Previous>>;\n\n/** The `Previous` type parameter when the options have no `getPreviousPageParam`. */\ndeclare const NO_PREVIOUS_PAGE_PARAM: unique symbol;\ntype NoPreviousPageParam = typeof NO_PREVIOUS_PAGE_PARAM;\n\ntype IsUntyped<T> = [T] extends [never] ? true : unknown extends T ? true : false;\n\n/** Only `undefined` or `null` names no type: a cursor API's `initialPageParam: undefined`. */\ntype NullishToUnknown<T> = [T] extends [undefined | null] ? unknown : T;\n\n/** Read only for the return type; `never` arguments add no inference for TanStack's page param. */\ntype PageParamFunction<Result> = (...args: never) => Result;\n\n/**\n * Inference sites of the page param types. Intersected before `Options`, so TanStack's own\n * inference in the implementation reads the full signatures of `Options`.\n */\ninterface PageParamSources<Initial, Next, Previous> {\n initialPageParam: Initial;\n getNextPageParam: PageParamFunction<Next>;\n getPreviousPageParam?: PageParamFunction<Previous>;\n}\n\n/**\n * `placeholderData` of `useInfiniteQuery`, with an `unknown` page param as before: TypeScript types\n * a `(previousData) => previousData` callback while it still infers the page param, so it got\n * `unknown` there and failed against the typed page param.\n */\ntype InfinitePlaceholderData<\n Data,\n Error,\n Paths extends {},\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n> = UseInfiniteQueryOptions<\n Data,\n Error,\n InfiniteData<Data, unknown>,\n InfiniteQueryKey<Paths, Method, Path>,\n unknown\n>[\"placeholderData\"];\n\nexport type UseInfiniteQueryMethod<Paths extends {}, Media extends MediaType> = <\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n Init extends MaybeOptionalInit<Paths[Path], Method>,\n Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>,\n Options extends Omit<\n UseInfiniteQueryOptions<\n Response[\"data\"],\n QueryError<Response[\"error\"]>,\n InferSelectReturnType<\n InfiniteData<Response[\"data\"], PageParam<Initial, Next, Previous>>,\n Options[\"select\"]\n >,\n InfiniteQueryKey<Paths, Method, Path>,\n PageParam<Initial, Next, Previous>\n >,\n \"queryKey\" | \"queryFn\" | \"placeholderData\"\n > & {\n placeholderData?: InfinitePlaceholderData<\n Response[\"data\"],\n QueryError<Response[\"error\"]>,\n Paths,\n Method,\n Path\n >;\n pageParamName?: string;\n },\n Initial = unknown,\n Next = never,\n Previous = NoPreviousPageParam,\n // biome-ignore lint/complexity/useMaxParams: public signature of 1.x (ADR-036)\n>(\n method: Method,\n url: Path,\n init: InitWithUnknowns<Init>,\n options: PageParamSources<Initial, Next, Previous> & Options,\n queryClient?: QueryClient,\n) => UseInfiniteQueryResult<\n InferSelectReturnType<\n InfiniteData<Response[\"data\"], PageParam<Initial, Next, Previous>>,\n Options[\"select\"]\n >,\n QueryError<Response[\"error\"]>\n>;\n\nexport type UseSuspenseQueryMethod<Paths extends {}, Media extends MediaType> = <\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n Init extends MaybeOptionalInit<Paths[Path], Method>,\n // note: Required is used to avoid repeating NonNullable in UseQuery types\n Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>,\n Options extends Omit<\n UseSuspenseQueryOptions<\n QueryData<Response[\"data\"]>,\n QueryError<Response[\"error\"]>,\n InferSelectReturnType<QueryData<Response[\"data\"]>, Options[\"select\"]>,\n QueryKey<Paths, Method, Path>\n >,\n \"queryKey\" | \"queryFn\"\n >,\n>(\n method: Method,\n url: Path,\n ...[init, options, queryClient]: InitArguments<Init, [Options?, QueryClient?]>\n) => UseSuspenseQueryResult<\n InferSelectReturnType<QueryData<Response[\"data\"]>, Options[\"select\"]>,\n QueryError<Response[\"error\"]>\n>;\n\nexport type UseMutationMethod<Paths extends {}, Media extends MediaType> = <\n Method extends HttpMethod,\n Path extends PathsWithMethod<Paths, Method>,\n Init extends MaybeOptionalInit<Paths[Path], Method>,\n // note: Required is used to avoid repeating NonNullable in UseQuery types\n Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>,\n TOnMutateResult = unknown,\n>(\n method: Method,\n url: Path,\n options?: Omit<\n UseMutationOptions<Response[\"data\"], QueryError<Response[\"error\"]>, Init, TOnMutateResult>,\n \"mutationKey\" | \"mutationFn\"\n >,\n queryClient?: QueryClient,\n) => UseMutationResult<Response[\"data\"], QueryError<Response[\"error\"]>, Init, TOnMutateResult>;\n\nexport interface OpenapiQueryClient<Paths extends {}, Media extends MediaType = MediaType> {\n queryOptions: QueryOptionsFunction<Paths, Media>;\n useQuery: UseQueryMethod<Paths, Media>;\n useSuspenseQuery: UseSuspenseQueryMethod<Paths, Media>;\n useInfiniteQuery: UseInfiniteQueryMethod<Paths, Media>;\n useMutation: UseMutationMethod<Paths, Media>;\n}\n\nexport type MethodResponse<\n // biome-ignore lint/suspicious/noExplicitAny: matches a client of any paths, as upstream's\n CreatedClient extends OpenapiQueryClient<any, any>,\n Method extends HttpMethod,\n Path extends CreatedClient extends OpenapiQueryClient<infer Paths, infer _Media>\n ? PathsWithMethod<Paths, Method>\n : never,\n Options = object,\n> =\n CreatedClient extends OpenapiQueryClient<\n // biome-ignore lint/suspicious/noExplicitAny: unknown rejects the generated interfaces\n infer Paths extends { [key: string]: any },\n infer Media extends MediaType\n >\n ? NonNullable<FetchResponse<Paths[Path][Method], Options, Media>[\"data\"]>\n : never;\n\n/** The `name` of every `ResponseError`. */\nconst RESPONSE_ERROR_NAME = \"ResponseError\";\n\n/** The `ResponseError` of a failed response without an error body. */\nclass ResponseWithoutErrorBody extends Error implements ResponseError {\n override readonly name = RESPONSE_ERROR_NAME;\n readonly response: Response;\n readonly status: number;\n\n constructor(response: Response) {\n const statusText = response.statusText ? ` ${response.statusText}` : \"\";\n super(`Request failed with status ${response.status}${statusText} and no error body`);\n this.response = response;\n this.status = response.status;\n }\n}\n\n/**\n * Whether `error` is the `ResponseError` of a failed response without an error body. It narrows a\n * hook's `error`, where `error instanceof Error` also matches network and parse errors. It checks\n * the `name`, not the class, so a `ResponseError` of another copy of this package (its CommonJS and\n * ES module builds loaded side by side) is one too. An error body from JSON is never an `Error`.\n */\nexport function isResponseError(error: unknown): error is ResponseError {\n return error instanceof Error && error.name === RESPONSE_ERROR_NAME;\n}\n\n/**\n * Throw the error of a failed fetch result. `if (error)` missed two failures: a non-OK response\n * with an empty body (`error` is `undefined`, upstream #2070, #2829) and a falsy error body such as\n * `0`. Without an error body a `ResponseError` is thrown, so the hooks' `error` is never\n * `undefined` (ADR-013, decision 3). A JSON `null` body is no error body either: thrown as is, it\n * left `error` `null` while the query's status was `\"error\"`.\n */\nfunction throwIfFailed(result: { error?: unknown; response: Response }): void {\n if (result.error !== undefined && result.error !== null) {\n throw result.error;\n }\n if (!result.response.ok) {\n throw new ResponseWithoutErrorBody(result.response);\n }\n}\n\n/** The query parameter that carries the page param unless `pageParamName` names another. */\nconst DEFAULT_PAGE_PARAM_NAME = \"cursor\";\n\ninterface PageRequest {\n readonly pageParamName: string;\n readonly pageParam: unknown;\n}\n\n/**\n * The request init of one page. An `undefined` page param (the first page with\n * `initialPageParam: undefined`) is left out instead of being sent as `0` (upstream #2715, #2340,\n * ADR-022), so a cursor API gets no cursor on the first page.\n */\nfunction pageInit(init: unknown, { pageParamName, pageParam }: PageRequest) {\n const { params, ...rest } = (init ?? {}) as { params?: { query?: DefaultParamsOption } };\n const page = pageParam === undefined ? {} : { [pageParamName]: pageParam };\n return { ...rest, params: { ...params, query: { ...params?.query, ...page } } };\n}\n\n/** Options of `createClient`. */\nexport interface CreateClientOptions {\n /**\n * The name of the API in every query key, in place of the fetch client's `baseUrl`. Give the\n * same name where the server and the browser reach one API by different URLs, so the browser\n * reads the data the server rendered with; give different names to clients of one base URL that\n * fetch different data, such as one per tenant header.\n */\n keyScope?: string;\n}\n\n/**\n * Hooks and query options for a fetch client. A `QueryClient` other than the one from the React\n * context is passed to each hook as its last argument; `createClient` does not take one.\n */\n// biome-ignore lint/complexity/noExcessiveLinesPerFunction: inherited, kept until 1.1 (ADR-036)\nexport default function createClient<Paths extends {}, Media extends MediaType = MediaType>(\n client: FetchClient<Paths, Media>,\n { keyScope }: CreateClientOptions = {},\n): OpenapiQueryClient<Paths, Media> {\n const keyClient = { baseUrl: client.baseUrl, keyScope };\n /**\n * Send one request of a query: the call's own init, with a signal that TanStack Query can abort.\n * The key only names the cache entry, as for `useInfiniteQuery`: a function in the init (a\n * `fetch`, a `middleware`) cannot be part of a key, so the request is read from the call.\n */\n const fetchPage = async <Method extends HttpMethod, Path extends PathsWithMethod<Paths, Method>>(\n method: Method,\n path: Path,\n init: unknown,\n signal: AbortSignal,\n ) => {\n const mth = method.toUpperCase() as Uppercase<typeof method>;\n const fn = client[mth] as ClientMethod<Paths, typeof method, Media>;\n const request = withQuerySignal(init, signal);\n try {\n // The init is `unknown` here. An `any` init lets the call infer the generic response type\n // that `queryOptions` declares; a typed init makes TypeScript compare two unresolved\n // conditional types, which it cannot do.\n // biome-ignore lint/suspicious/noExplicitAny: see the comment above\n const result = await fn(path, request.init as any);\n throwIfFailed(result);\n return result.data;\n } finally {\n request.release();\n }\n };\n\n const queryOptions: QueryOptionsFunction<Paths, Media> = (method, path, ...[init, options]) => {\n const keyInit = queryKeyInit(init, keyClient);\n return {\n queryKey: (keyInit === undefined\n ? ([method, path] as const)\n : ([method, path, keyInit] as const)) as DataTag<\n QueryKey<Paths, typeof method, typeof path>,\n // biome-ignore lint/suspicious/noExplicitAny: the declared return type sets the data type\n any,\n // biome-ignore lint/suspicious/noExplicitAny: the declared return type sets the error type\n any\n >,\n // TanStack Query rejects `undefined` query data. The fetch client gives `undefined` for\n // every success without a body: a 204, `Content-Length: 0`, an empty chunked body, a HEAD\n // request (upstream #2234). A parsed body is never `undefined`, so this changes nothing else.\n queryFn: async ({ signal }: QueryFunctionContext) =>\n (await fetchPage(method, path, init, signal)) ?? null,\n // Without options, `Options` is its constraint, which has no `initialData` to keep.\n ...(options as typeof options & {}),\n // The declared type types a defined `initialData` as the query data, a conditional type of\n // the generic options that TypeScript cannot relate to the object; it is the same object.\n } as never;\n };\n\n return {\n queryOptions,\n useQuery: (method, path, ...[init, options, queryClient]) =>\n // TanStack Query's `useQuery` returns `DefinedUseQueryResult` for options with defined\n // `initialData`; while `Options` is generic it cannot pick that overload, and the declared\n // `QueryResult` gives the caller the same answer. Both are the same object at runtime.\n useQuery(\n queryOptions(method, path, init as InitWithUnknowns<typeof init>, options),\n queryClient,\n ) as never,\n useSuspenseQuery: (method, path, ...[init, options, queryClient]) =>\n useSuspenseQuery(\n queryOptions(method, path, init as InitWithUnknowns<typeof init>, options),\n queryClient,\n ),\n // biome-ignore lint/complexity/useMaxParams: public signature of 1.x (ADR-036)\n useInfiniteQuery: (method, path, init, options, queryClient) => {\n const { pageParamName = DEFAULT_PAGE_PARAM_NAME, placeholderData, ...restOptions } = options;\n const { queryKey } = queryOptions(method, path, init);\n return useInfiniteQuery(\n {\n queryKey: [...queryKey, INFINITE_QUERY_KEY_MARKER] as const,\n // An empty page stays `undefined`, as in upstream: TanStack Query rejects only\n // `undefined` query data, and the infinite query data is the `{ pages }` object.\n queryFn: ({ pageParam, signal }) =>\n fetchPage(method, path, pageInit(init, { pageParamName, pageParam }), signal),\n ...restOptions,\n // Typed with an `unknown` page param for the caller (`InfinitePlaceholderData`). TanStack\n // passes the previous data of this query, with its own page params, and takes it back.\n // biome-ignore lint/suspicious/noExplicitAny: TanStack's type carries its own page params\n placeholderData: placeholderData as any,\n },\n queryClient,\n );\n },\n useMutation: (method, path, options, queryClient) =>\n useMutation(\n {\n mutationKey: [method, path],\n mutationFn: async (init) => {\n const mth = method.toUpperCase() as Uppercase<typeof method>;\n const fn = client[mth] as ClientMethod<Paths, typeof method, Media>;\n const result = await fn(path, init as InitWithUnknowns<typeof init>);\n throwIfFailed(result);\n // TanStack Query accepts `undefined` mutation data, so a success without a body stays\n // `undefined`, as in upstream; only query data needs `null` (upstream #2234). The cast\n // only bridges the generic types: `Response[\"data\"]` still has `undefined` for an\n // operation with a response without a body.\n const { data } = result;\n return data as Exclude<typeof data, undefined>;\n },\n ...options,\n },\n queryClient,\n ),\n };\n}\n"],"names":["useQuery","useSuspenseQuery","useInfiniteQuery","useMutation"],"mappings":";;;;;;AAsBA,MAAM,iBAAiB,UAAA,CAAW,MAAA;AAClC,MAAM,YAAA,GAAe,EAAA;AAOrB,SAAS,OAAA,CAAQ,OAAe,IAAA,EAAuB;AACrD,EAAA,MAAM,IAAA,GAAQ,WAAuC,IAAI,CAAA;AACzD,EAAA,OACG,OAAO,IAAA,KAAS,UAAA,IAAc,KAAA,YAAiB,QAChD,MAAA,CAAO,SAAA,CAAU,QAAA,CAAS,IAAA,CAAK,KAAK,CAAA,CAAE,KAAA,CAAM,cAAA,EAAgB,YAAY,CAAA,KAAM,IAAA;AAElF;AASA,SAAS,aAAa,OAAA,EAAgC;AACpD,EAAA,IAAI,EAAE,MAAA,CAAO,QAAA,IAAY,OAAA,CAAA,EAAU;AACjC,IAAA,OAAO,OAAA;AAAA,EACT;AACA,EAAA,MAAM,SAAiC,EAAC;AACxC,EAAA,KAAA,MAAW,QAAQ,OAAA,EAA8B;AAC/C,IAAA,MAAM,CAAC,IAAA,EAAM,KAAK,CAAA,GAAI,KAAA,CAAM,KAAK,IAA0B,CAAA;AAC3D,IAAA,MAAM,GAAA,GAAM,MAAA,CAAO,IAAI,CAAA,CAAE,WAAA,EAAY;AACrC,IAAA,MAAA,CAAO,GAAG,CAAA,GAAI,GAAA,IAAO,MAAA,GAAS,GAAG,MAAA,CAAO,GAAG,CAA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,MAAA,EAAQ,MAAM,IAAI,CAAA;AACpD,MAAA,OAAOC,2BAAA;AAAA,QACL;AAAA,UACE,QAAA,EAAU,CAAC,GAAG,QAAA,EAAU,yBAAyB,CAAA;AAAA;AAAA;AAAA,UAGjD,SAAS,CAAC,EAAE,SAAA,EAAW,MAAA,OACrB,SAAA,CAAU,MAAA,EAAQ,IAAA,EAAM,QAAA,CAAS,MAAM,EAAE,aAAA,EAAe,SAAA,EAAW,GAAG,MAAM,CAAA;AAAA,UAC9E,GAAG,WAAA;AAAA;AAAA;AAAA;AAAA,UAIH;AAAA,SACF;AAAA,QACA;AAAA,OACF;AAAA,IACF,CAAA;AAAA,IACA,WAAA,EAAa,CAAC,MAAA,EAAQ,IAAA,EAAM,SAAS,WAAA,KACnCC,sBAAA;AAAA,MACE;AAAA,QACE,WAAA,EAAa,CAAC,MAAA,EAAQ,IAAI,CAAA;AAAA,QAC1B,UAAA,EAAY,OAAO,IAAA,KAAS;AAC1B,UAAA,MAAM,GAAA,GAAM,OAAO,WAAA,EAAY;AAC/B,UAAA,MAAM,EAAA,GAAK,OAAO,GAAG,CAAA;AACrB,UAAA,MAAM,MAAA,GAAS,MAAM,EAAA,CAAG,IAAA,EAAM,IAAqC,CAAA;AACnE,UAAA,aAAA,CAAc,MAAM,CAAA;AAKpB,UAAA,MAAM,EAAE,MAAK,GAAI,MAAA;AACjB,UAAA,OAAO,IAAA;AAAA,QACT,CAAA;AAAA,QACA,GAAG;AAAA,OACL;AAAA,MACA;AAAA;AACF,GACJ;AACF;;;;"}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { UseQueryOptions, DefaultError, DataTag, SkipToken, QueryClient, UseQueryResult, UseSuspenseQueryOptions, UseSuspenseQueryResult, UseInfiniteQueryOptions, InfiniteData, UseInfiniteQueryResult, UseMutationOptions, UseMutationResult } from '@tanstack/react-query';
1
+ import { UseQueryOptions, DefaultError, DataTag, SkipToken, QueryClient, DefinedUseQueryResult, UseQueryResult, UseSuspenseQueryOptions, UseSuspenseQueryResult, UseInfiniteQueryOptions, InfiniteData, UseInfiniteQueryResult, UseMutationOptions, UseMutationResult } from '@tanstack/react-query';
2
2
  import { MaybeOptionalInit, FetchResponse, PathOperation, Client } from 'openapi-typesafe-fetch';
3
3
  import { HttpMethod, PathsWithMethod, MediaType, RequiredKeysOf } from 'openapi-typesafe-fetch/helpers';
4
4
 
@@ -54,6 +54,12 @@ type InitWithUnknowns<Init> = Init & {
54
54
  * so `Parameters<typeof $api.queryOptions>` still requires it then (upstream #2178).
55
55
  */
56
56
  type InitArguments<Init, Rest extends unknown[]> = RequiredKeysOf<Init> extends never ? [InitWithUnknowns<Init>?, ...Rest] : [InitWithUnknowns<Init>, ...Rest];
57
+ /**
58
+ * The key of a query: the method, the path and the request. Its init is the init of the call with
59
+ * the headers and the body as plain values, and the client's `keyScope`, or its `baseUrl` when the
60
+ * init has none, so two requests never share a key; it is left out when nothing is left. Read a
61
+ * query's key from `queryOptions(...).queryKey` rather than writing it out.
62
+ */
57
63
  type QueryKey<Paths extends {}, Method extends HttpMethod, Path extends PathsWithMethod<Paths, Method>, Init = MaybeOptionalInit<Paths[Path], Method>> = Init extends undefined ? readonly [Method, Path] : readonly [Method, Path, Init];
58
64
  /**
59
65
  * The last element of an infinite query's key. `useQuery` and `useInfiniteQuery` cache different
@@ -63,10 +69,29 @@ type QueryKey<Paths extends {}, Method extends HttpMethod, Path extends PathsWit
63
69
  */
64
70
  declare const INFINITE_QUERY_KEY_MARKER = "infinite";
65
71
  type InfiniteQueryKey<Paths extends {}, Method extends HttpMethod, Path extends PathsWithMethod<Paths, Method>> = readonly [...QueryKey<Paths, Method, Path>, typeof INFINITE_QUERY_KEY_MARKER];
66
- type QueryOptionsFunction<Paths extends {}, Media extends MediaType> = <Method extends HttpMethod, Path extends PathsWithMethod<Paths, Method>, Init extends MaybeOptionalInit<Paths[Path], Method>, Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>, Options extends Omit<UseQueryOptions<QueryData<Response["data"]>, QueryError<Response["error"]>, InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryKey<Paths, Method, Path>>, "queryKey" | "queryFn">>(method: Method, path: Path, ...[init, options]: InitArguments<Init, [Options?]>) => NoInfer<Omit<UseQueryOptions<QueryData<Response["data"]>, QueryError<Response["error"]>, InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryKey<Paths, Method, Path>>, "queryFn" | "queryKey"> & QueryKeyWithDataTag<QueryKey<Paths, Method, Path>, QueryData<Response["data"]>, QueryError<Response["error"]>> & {
72
+ /**
73
+ * Whether the options give an `initialData` that is never `undefined`: a value, or a function that
74
+ * never returns `undefined`. Then `data` is never `undefined` either, as for TanStack Query's own
75
+ * `useQuery` with `DefinedInitialDataOptions`.
76
+ */
77
+ type HasDefinedInitialData<Options> = Options extends {
78
+ initialData: infer Initial;
79
+ } ? Initial extends (...args: never) => infer Returned ? undefined extends Returned ? false : true : undefined extends Initial ? false : true : false;
80
+ /** The result of `useQuery`: its `data` is defined when the options give defined initial data. */
81
+ type QueryResult<Data, Error, Options> = HasDefinedInitialData<Options> extends true ? DefinedUseQueryResult<Data, Error> : UseQueryResult<Data, Error>;
82
+ /**
83
+ * A defined `initialData` of the options, in the type `queryOptions` returns, so TanStack Query's
84
+ * `useQuery` takes the result as options with defined initial data. It is typed as the query data,
85
+ * as TanStack's `DefinedInitialDataOptions` types it: the type of a literal such as `[{ id: 1 }]`
86
+ * lacks the optional properties of the data, and TanStack's overload rejected it.
87
+ */
88
+ type InitialDataOf<Options, Data> = HasDefinedInitialData<Options> extends true ? {
89
+ initialData: Data | (() => Data);
90
+ } : unknown;
91
+ type QueryOptionsFunction<Paths extends {}, Media extends MediaType> = <Method extends HttpMethod, Path extends PathsWithMethod<Paths, Method>, Init extends MaybeOptionalInit<Paths[Path], Method>, Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>, Options extends Omit<UseQueryOptions<QueryData<Response["data"]>, QueryError<Response["error"]>, InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryKey<Paths, Method, Path>>, "queryKey" | "queryFn">>(method: Method, path: Path, ...[init, options]: InitArguments<Init, [Options?]>) => NoInfer<Omit<UseQueryOptions<QueryData<Response["data"]>, QueryError<Response["error"]>, InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryKey<Paths, Method, Path>>, "queryFn" | "queryKey"> & QueryKeyWithDataTag<QueryKey<Paths, Method, Path>, QueryData<Response["data"]>, QueryError<Response["error"]>> & InitialDataOf<Options, QueryData<Response["data"]>> & {
67
92
  queryFn: Exclude<UseQueryOptions<QueryData<Response["data"]>, QueryError<Response["error"]>, InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryKey<Paths, Method, Path>>["queryFn"], SkipToken | undefined>;
68
93
  }>;
69
- type UseQueryMethod<Paths extends {}, Media extends MediaType> = <Method extends HttpMethod, Path extends PathsWithMethod<Paths, Method>, Init extends MaybeOptionalInit<Paths[Path], Method>, Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>, Options extends Omit<UseQueryOptions<QueryData<Response["data"]>, QueryError<Response["error"]>, InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryKey<Paths, Method, Path>>, "queryKey" | "queryFn">>(method: Method, url: Path, ...[init, options, queryClient]: InitArguments<Init, [Options?, QueryClient?]>) => UseQueryResult<InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryError<Response["error"]>>;
94
+ type UseQueryMethod<Paths extends {}, Media extends MediaType> = <Method extends HttpMethod, Path extends PathsWithMethod<Paths, Method>, Init extends MaybeOptionalInit<Paths[Path], Method>, Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>, Options extends Omit<UseQueryOptions<QueryData<Response["data"]>, QueryError<Response["error"]>, InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryKey<Paths, Method, Path>>, "queryKey" | "queryFn">>(method: Method, url: Path, ...[init, options, queryClient]: InitArguments<Init, [Options?, QueryClient?]>) => QueryResult<InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryError<Response["error"]>, Options>;
70
95
  /**
71
96
  * The type of the page params: the initial one and the ones `getNextPageParam` and
72
97
  * `getPreviousPageParam` return (upstream #2458). It was `unknown`. It stays `unknown` when a
@@ -121,13 +146,23 @@ type MethodResponse<CreatedClient extends OpenapiQueryClient<any, any>, Method e
121
146
  * ES module builds loaded side by side) is one too. An error body from JSON is never an `Error`.
122
147
  */
123
148
  declare function isResponseError(error: unknown): error is ResponseError;
149
+ /** Options of `createClient`. */
150
+ interface CreateClientOptions {
151
+ /**
152
+ * The name of the API in every query key, in place of the fetch client's `baseUrl`. Give the
153
+ * same name where the server and the browser reach one API by different URLs, so the browser
154
+ * reads the data the server rendered with; give different names to clients of one base URL that
155
+ * fetch different data, such as one per tenant header.
156
+ */
157
+ keyScope?: string;
158
+ }
124
159
  /**
125
160
  * Hooks and query options for a fetch client. A `QueryClient` other than the one from the React
126
161
  * context is passed to each hook as its last argument; `createClient` does not take one.
127
162
  */
128
- declare function createClient<Paths extends {}, Media extends MediaType = MediaType>(client: Client<Paths, Media>): OpenapiQueryClient<Paths, Media>;
163
+ declare function createClient<Paths extends {}, Media extends MediaType = MediaType>(client: Client<Paths, Media>, { keyScope }?: CreateClientOptions): OpenapiQueryClient<Paths, Media>;
129
164
 
130
165
  declare namespace createClient {
131
- export { createClient as default, isResponseError, InfiniteQueryKey, MethodResponse, OpenapiQueryClient, QueryError, QueryKey, QueryKeyWithDataTag, QueryOptionsFunction, ResponseError, UseInfiniteQueryMethod, UseMutationMethod, UseQueryMethod, UseSuspenseQueryMethod };
166
+ export { createClient as default, isResponseError, CreateClientOptions, InfiniteQueryKey, MethodResponse, OpenapiQueryClient, QueryError, QueryKey, QueryKeyWithDataTag, QueryOptionsFunction, ResponseError, UseInfiniteQueryMethod, UseMutationMethod, UseQueryMethod, UseSuspenseQueryMethod };
132
167
  }
133
168
  export = createClient;
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { UseQueryOptions, DefaultError, DataTag, SkipToken, QueryClient, UseQueryResult, UseSuspenseQueryOptions, UseSuspenseQueryResult, UseInfiniteQueryOptions, InfiniteData, UseInfiniteQueryResult, UseMutationOptions, UseMutationResult } from '@tanstack/react-query';
1
+ import { UseQueryOptions, DefaultError, DataTag, SkipToken, QueryClient, DefinedUseQueryResult, UseQueryResult, UseSuspenseQueryOptions, UseSuspenseQueryResult, UseInfiniteQueryOptions, InfiniteData, UseInfiniteQueryResult, UseMutationOptions, UseMutationResult } from '@tanstack/react-query';
2
2
  import { MaybeOptionalInit, FetchResponse, PathOperation, Client } from 'openapi-typesafe-fetch';
3
3
  import { HttpMethod, PathsWithMethod, MediaType, RequiredKeysOf } from 'openapi-typesafe-fetch/helpers';
4
4
 
@@ -54,6 +54,12 @@ type InitWithUnknowns<Init> = Init & {
54
54
  * so `Parameters<typeof $api.queryOptions>` still requires it then (upstream #2178).
55
55
  */
56
56
  type InitArguments<Init, Rest extends unknown[]> = RequiredKeysOf<Init> extends never ? [InitWithUnknowns<Init>?, ...Rest] : [InitWithUnknowns<Init>, ...Rest];
57
+ /**
58
+ * The key of a query: the method, the path and the request. Its init is the init of the call with
59
+ * the headers and the body as plain values, and the client's `keyScope`, or its `baseUrl` when the
60
+ * init has none, so two requests never share a key; it is left out when nothing is left. Read a
61
+ * query's key from `queryOptions(...).queryKey` rather than writing it out.
62
+ */
57
63
  type QueryKey<Paths extends {}, Method extends HttpMethod, Path extends PathsWithMethod<Paths, Method>, Init = MaybeOptionalInit<Paths[Path], Method>> = Init extends undefined ? readonly [Method, Path] : readonly [Method, Path, Init];
58
64
  /**
59
65
  * The last element of an infinite query's key. `useQuery` and `useInfiniteQuery` cache different
@@ -63,10 +69,29 @@ type QueryKey<Paths extends {}, Method extends HttpMethod, Path extends PathsWit
63
69
  */
64
70
  declare const INFINITE_QUERY_KEY_MARKER = "infinite";
65
71
  type InfiniteQueryKey<Paths extends {}, Method extends HttpMethod, Path extends PathsWithMethod<Paths, Method>> = readonly [...QueryKey<Paths, Method, Path>, typeof INFINITE_QUERY_KEY_MARKER];
66
- type QueryOptionsFunction<Paths extends {}, Media extends MediaType> = <Method extends HttpMethod, Path extends PathsWithMethod<Paths, Method>, Init extends MaybeOptionalInit<Paths[Path], Method>, Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>, Options extends Omit<UseQueryOptions<QueryData<Response["data"]>, QueryError<Response["error"]>, InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryKey<Paths, Method, Path>>, "queryKey" | "queryFn">>(method: Method, path: Path, ...[init, options]: InitArguments<Init, [Options?]>) => NoInfer<Omit<UseQueryOptions<QueryData<Response["data"]>, QueryError<Response["error"]>, InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryKey<Paths, Method, Path>>, "queryFn" | "queryKey"> & QueryKeyWithDataTag<QueryKey<Paths, Method, Path>, QueryData<Response["data"]>, QueryError<Response["error"]>> & {
72
+ /**
73
+ * Whether the options give an `initialData` that is never `undefined`: a value, or a function that
74
+ * never returns `undefined`. Then `data` is never `undefined` either, as for TanStack Query's own
75
+ * `useQuery` with `DefinedInitialDataOptions`.
76
+ */
77
+ type HasDefinedInitialData<Options> = Options extends {
78
+ initialData: infer Initial;
79
+ } ? Initial extends (...args: never) => infer Returned ? undefined extends Returned ? false : true : undefined extends Initial ? false : true : false;
80
+ /** The result of `useQuery`: its `data` is defined when the options give defined initial data. */
81
+ type QueryResult<Data, Error, Options> = HasDefinedInitialData<Options> extends true ? DefinedUseQueryResult<Data, Error> : UseQueryResult<Data, Error>;
82
+ /**
83
+ * A defined `initialData` of the options, in the type `queryOptions` returns, so TanStack Query's
84
+ * `useQuery` takes the result as options with defined initial data. It is typed as the query data,
85
+ * as TanStack's `DefinedInitialDataOptions` types it: the type of a literal such as `[{ id: 1 }]`
86
+ * lacks the optional properties of the data, and TanStack's overload rejected it.
87
+ */
88
+ type InitialDataOf<Options, Data> = HasDefinedInitialData<Options> extends true ? {
89
+ initialData: Data | (() => Data);
90
+ } : unknown;
91
+ type QueryOptionsFunction<Paths extends {}, Media extends MediaType> = <Method extends HttpMethod, Path extends PathsWithMethod<Paths, Method>, Init extends MaybeOptionalInit<Paths[Path], Method>, Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>, Options extends Omit<UseQueryOptions<QueryData<Response["data"]>, QueryError<Response["error"]>, InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryKey<Paths, Method, Path>>, "queryKey" | "queryFn">>(method: Method, path: Path, ...[init, options]: InitArguments<Init, [Options?]>) => NoInfer<Omit<UseQueryOptions<QueryData<Response["data"]>, QueryError<Response["error"]>, InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryKey<Paths, Method, Path>>, "queryFn" | "queryKey"> & QueryKeyWithDataTag<QueryKey<Paths, Method, Path>, QueryData<Response["data"]>, QueryError<Response["error"]>> & InitialDataOf<Options, QueryData<Response["data"]>> & {
67
92
  queryFn: Exclude<UseQueryOptions<QueryData<Response["data"]>, QueryError<Response["error"]>, InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryKey<Paths, Method, Path>>["queryFn"], SkipToken | undefined>;
68
93
  }>;
69
- type UseQueryMethod<Paths extends {}, Media extends MediaType> = <Method extends HttpMethod, Path extends PathsWithMethod<Paths, Method>, Init extends MaybeOptionalInit<Paths[Path], Method>, Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>, Options extends Omit<UseQueryOptions<QueryData<Response["data"]>, QueryError<Response["error"]>, InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryKey<Paths, Method, Path>>, "queryKey" | "queryFn">>(method: Method, url: Path, ...[init, options, queryClient]: InitArguments<Init, [Options?, QueryClient?]>) => UseQueryResult<InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryError<Response["error"]>>;
94
+ type UseQueryMethod<Paths extends {}, Media extends MediaType> = <Method extends HttpMethod, Path extends PathsWithMethod<Paths, Method>, Init extends MaybeOptionalInit<Paths[Path], Method>, Response extends Required<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>, Options extends Omit<UseQueryOptions<QueryData<Response["data"]>, QueryError<Response["error"]>, InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryKey<Paths, Method, Path>>, "queryKey" | "queryFn">>(method: Method, url: Path, ...[init, options, queryClient]: InitArguments<Init, [Options?, QueryClient?]>) => QueryResult<InferSelectReturnType<QueryData<Response["data"]>, Options["select"]>, QueryError<Response["error"]>, Options>;
70
95
  /**
71
96
  * The type of the page params: the initial one and the ones `getNextPageParam` and
72
97
  * `getPreviousPageParam` return (upstream #2458). It was `unknown`. It stays `unknown` when a
@@ -121,11 +146,21 @@ type MethodResponse<CreatedClient extends OpenapiQueryClient<any, any>, Method e
121
146
  * ES module builds loaded side by side) is one too. An error body from JSON is never an `Error`.
122
147
  */
123
148
  declare function isResponseError(error: unknown): error is ResponseError;
149
+ /** Options of `createClient`. */
150
+ interface CreateClientOptions {
151
+ /**
152
+ * The name of the API in every query key, in place of the fetch client's `baseUrl`. Give the
153
+ * same name where the server and the browser reach one API by different URLs, so the browser
154
+ * reads the data the server rendered with; give different names to clients of one base URL that
155
+ * fetch different data, such as one per tenant header.
156
+ */
157
+ keyScope?: string;
158
+ }
124
159
  /**
125
160
  * Hooks and query options for a fetch client. A `QueryClient` other than the one from the React
126
161
  * context is passed to each hook as its last argument; `createClient` does not take one.
127
162
  */
128
- declare function createClient<Paths extends {}, Media extends MediaType = MediaType>(client: Client<Paths, Media>): OpenapiQueryClient<Paths, Media>;
163
+ declare function createClient<Paths extends {}, Media extends MediaType = MediaType>(client: Client<Paths, Media>, { keyScope }?: CreateClientOptions): OpenapiQueryClient<Paths, Media>;
129
164
 
130
165
  export { createClient as default, isResponseError };
131
- export type { InfiniteQueryKey, MethodResponse, OpenapiQueryClient, QueryError, QueryKey, QueryKeyWithDataTag, QueryOptionsFunction, ResponseError, UseInfiniteQueryMethod, UseMutationMethod, UseQueryMethod, UseSuspenseQueryMethod };
166
+ export type { CreateClientOptions, InfiniteQueryKey, MethodResponse, OpenapiQueryClient, QueryError, QueryKey, QueryKeyWithDataTag, QueryOptionsFunction, ResponseError, UseInfiniteQueryMethod, UseMutationMethod, UseQueryMethod, UseSuspenseQueryMethod };