openapi-typesafe-fetch 1.0.0-rc.0 → 1.0.0-rc.2

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/src/index.d.ts CHANGED
@@ -28,28 +28,59 @@ export interface ClientOptions extends Omit<RequestInit, "headers"> {
28
28
  /** global pathSerializer */
29
29
  pathSerializer?: PathSerializer;
30
30
  headers?: HeadersOptions;
31
- /** RequestInit extension object to pass as 2nd argument to fetch when supported (defaults to undefined) */
31
+ /**
32
+ * RequestInit extension object to pass as 2nd argument to fetch when supported (defaults to
33
+ * undefined)
34
+ */
32
35
  requestInitExt?: Record<string, unknown>;
33
36
  }
34
37
 
38
+ /**
39
+ * `ClientOptions` for a Fetch API implementation with its own types, such as the `undici` package
40
+ * (upstream #2562). TypeScript cannot relate its `Request` and `Response` to the DOM lib's
41
+ * (`duplex`, `RequestDestination`, `BodyInit` differ), so only what the client needs is checked: a
42
+ * `fetch` that returns a promise and a `Request` class that takes a URL. Pass the `fetch` and the
43
+ * `Request` of the same implementation; middleware and results still use the DOM types. The
44
+ * `createClient` overload with `ClientOptions` comes first, so an inline `fetch` gets a typed
45
+ * `Request` input.
46
+ */
47
+ export interface CustomFetchClientOptions extends Omit<ClientOptions, "fetch" | "Request"> {
48
+ /** `fetch` of another implementation (for example `fetch` from `undici`) */
49
+ fetch?: (input: never, init?: never) => PromiseLike<object>;
50
+ /** `Request` of the same implementation (for example `Request` from `undici`) */
51
+ Request?: new (
52
+ input: string,
53
+ init: never,
54
+ ) => object;
55
+ }
56
+
35
57
  export type HeadersOptions =
36
58
  | Required<RequestInit>["headers"]
37
59
  | Record<string, string | number | boolean | (string | number | boolean)[] | null | undefined>;
38
60
 
39
61
  export type QuerySerializer<T> = (
40
- query: T extends { parameters: any } ? NonNullable<T["parameters"]["query"]> : Record<string, unknown>,
62
+ // biome-ignore lint/suspicious/noExplicitAny: T["parameters"]["query"] needs an any constraint
63
+ query: T extends { parameters: any }
64
+ ? NonNullable<T["parameters"]["query"]>
65
+ : Record<string, unknown>,
41
66
  ) => string;
42
67
 
43
68
  /** @see https://swagger.io/docs/specification/serialization/#query */
44
69
  export type QuerySerializerOptions = {
45
- /** Set serialization for arrays. @see https://swagger.io/docs/specification/serialization/#query */
70
+ /**
71
+ * Set serialization for arrays.
72
+ * @see https://swagger.io/docs/specification/serialization/#query
73
+ */
46
74
  array?: {
47
75
  /** default: "form" */
48
76
  style: "form" | "spaceDelimited" | "pipeDelimited";
49
77
  /** default: true */
50
78
  explode: boolean;
51
79
  };
52
- /** Set serialization for objects. @see https://swagger.io/docs/specification/serialization/#query */
80
+ /**
81
+ * Set serialization for objects.
82
+ * @see https://swagger.io/docs/specification/serialization/#query
83
+ */
53
84
  object?: {
54
85
  /** default: "deepObject" */
55
86
  style: "form" | "deepObject";
@@ -66,6 +97,8 @@ export type QuerySerializerOptions = {
66
97
  allowReserved?: boolean;
67
98
  };
68
99
 
100
+ // The result is the fetch body; openapi-fetch types it as `any` (ADR-030).
101
+ // biome-ignore lint/suspicious/noExplicitAny: openapi-fetch's type, kept for parity
69
102
  export type BodySerializer<T> = (body: OperationRequestBodyContent<T>) => any;
70
103
 
71
104
  export type PathSerializer = (pathname: string, pathParams: Record<string, unknown>) => string;
@@ -91,25 +124,38 @@ export interface DefaultParamsOption {
91
124
  }
92
125
 
93
126
  export type ParamsOption<T> = T extends {
94
- parameters: any;
127
+ parameters: unknown;
95
128
  }
96
129
  ? RequiredKeysOf<T["parameters"]> extends never
97
130
  ? { params?: T["parameters"] }
98
131
  : { params: T["parameters"] }
99
132
  : DefaultParamsOption;
100
133
 
101
- // Writable<T> strips $Read markers (readOnly properties excluded from request body)
134
+ /** `true` for `any`: the operation of `createClient<any>()`, which says nothing about its body. */
135
+ type IsAny<T> = 0 extends 1 & T ? true : false;
136
+
137
+ // Writable<T> strips $Read markers (readOnly properties excluded from request body).
138
+ // An `any` operation is checked first: a conditional type on `any` takes both branches, which
139
+ // gave `{ body?: never } | { body: any }` and so a required init (upstream #2526).
102
140
  export type RequestBodyOption<T> =
103
- Writable<OperationRequestBodyContent<T>> extends never
104
- ? { body?: never }
105
- : IsOperationRequestBodyOptional<T> extends true
106
- ? { body?: Writable<OperationRequestBodyContent<T>> }
107
- : { body: Writable<OperationRequestBodyContent<T>> };
141
+ IsAny<T> extends true
142
+ ? // biome-ignore lint/suspicious/noExplicitAny: an any schema takes any body (upstream #2526)
143
+ { body?: any }
144
+ : Writable<OperationRequestBodyContent<T>> extends never
145
+ ? { body?: never }
146
+ : IsOperationRequestBodyOptional<T> extends true
147
+ ? { body?: Writable<OperationRequestBodyContent<T>> }
148
+ : { body: Writable<OperationRequestBodyContent<T>> };
108
149
 
109
150
  export type FetchOptions<T> = RequestOptions<T> & Omit<RequestInit, "body" | "headers">;
110
151
 
111
152
  // Readable<T> strips $Write markers (writeOnly properties excluded from response)
112
- export type FetchResponse<T extends Record<string | number, any>, Options, Media extends MediaType> =
153
+ export type FetchResponse<
154
+ // biome-ignore lint/suspicious/noExplicitAny: unknown rejects the generated interfaces
155
+ T extends Record<string | number, any>,
156
+ Options,
157
+ Media extends MediaType,
158
+ > =
113
159
  | {
114
160
  data: ParseAsResponse<Readable<SuccessResponse<ResponseObjectMap<T>, Media>>, Options>;
115
161
  error?: never;
@@ -158,7 +204,7 @@ export interface MiddlewareCallbackParams {
158
204
  readonly params: MiddlewareRequestParams;
159
205
  /** Unique ID for this request */
160
206
  readonly id: string;
161
- /** createClient options (read-only) */
207
+ /** The options of this request after merging the client and request options (read-only) */
162
208
  readonly options: MergedOptions;
163
209
  }
164
210
 
@@ -189,29 +235,79 @@ export type Middleware =
189
235
  onError: MiddlewareOnError;
190
236
  };
191
237
 
192
- /** This type helper makes the 2nd function param required if params/requestBody are required; otherwise, optional */
193
- export type MaybeOptionalInit<Params, Location extends keyof Params> =
194
- RequiredKeysOf<FetchOptions<FilterKeys<Params, Location>>> extends never
195
- ? FetchOptions<FilterKeys<Params, Location>> | undefined
196
- : FetchOptions<FilterKeys<Params, Location>>;
238
+ /**
239
+ * This type helper makes the 2nd function param required if params/requestBody are required;
240
+ * otherwise, optional. `Location` is any key: with `Paths extends {}` a method is not known to be a
241
+ * key of `Paths[Path]` (upstream #2267). For a union of operations, the union of their inits: one
242
+ * deep type of every init gave TS2589 on hundreds of paths (upstream #1882).
243
+ */
244
+ export type MaybeOptionalInit<Params, Location extends PropertyKey> = OperationInits<
245
+ FilterKeys<Params, Location>
246
+ >;
247
+
248
+ /**
249
+ * The inits of the operations, and `undefined` only when none of them requires anything. One
250
+ * operation's init is `undefined` too when nothing in it is required, as in openapi-fetch. For a
251
+ * union of operations (a union of paths, or `Parameters<typeof client.request>`), `undefined`
252
+ * would make the whole init optional, although a call to one of the paths sends the init it gets,
253
+ * and a path parameter left out stays `{id}` in the URL.
254
+ * One conditional type, as openapi-fetch's, not a union with a conditional `undefined`: while the
255
+ * operation is generic, a union made `FetchResponse` distribute over its members, so the `data` of
256
+ * a generic wrapper's call no longer related to `FetchResponse<Paths[Path][Method], Init, Media>`.
257
+ */
258
+ type OperationInits<Operation> =
259
+ RequiredKeysOf<OperationFetchOptions<Operation>> extends never
260
+ ? OperationFetchOptions<Operation> | undefined
261
+ : OperationFetchOptions<Operation>;
262
+
263
+ /**
264
+ * Each operation's init. A distributive alias, not `extends infer Operation`: while the path is
265
+ * not known, TypeScript reads an `infer` type as `unknown`, so the init lost its type as the
266
+ * contextual type of an argument and a literal such as `"available"` widened to `string`
267
+ * (swr-openapi's `Exact<Init>` checks).
268
+ */
269
+ type OperationFetchOptions<Operation> = Operation extends unknown ? FetchOptions<Operation> : never;
197
270
 
198
271
  // The final init param to accept.
199
272
  // - Determines if the param is optional or not.
200
273
  // - Performs arbitrary [key: string] addition.
201
- // Note: the addition MUST happen after all the inference happens (otherwise TS can’t infer if init is required or not).
274
+ // Note: the addition MUST happen after all the inference happens (otherwise TS can’t infer if
275
+ // init is required or not).
276
+ // - The condition is openapi-fetch's. TypeScript relates two conditional types only when their
277
+ // `extends` types are the same and their check types relate, so a client type written against
278
+ // openapi-fetch's `InitParam` (a wrapper, a cast) accepted this client only with this condition.
279
+ // A union of inits is required through `MaybeOptionalInit`, which then leaves out `undefined`.
280
+ // - The addition is a named alias: written out in both branches, TypeScript gave `never` for
281
+ // `Parameters` of the methods.
202
282
  type InitParam<Init> =
203
- RequiredKeysOf<Init> extends never ? [(Init & { [key: string]: unknown })?] : [Init & { [key: string]: unknown }];
283
+ RequiredKeysOf<Init> extends never ? [WithAnyKeys<Init>?] : [WithAnyKeys<Init>];
204
284
 
205
- export type ClientMethod<
206
- Paths extends Record<string, Record<HttpMethod, {}>>,
207
- Method extends HttpMethod,
208
- Media extends MediaType,
209
- > = <Path extends PathsWithMethod<Paths, Method>, Init extends MaybeOptionalInit<Paths[Path], Method>>(
285
+ /** The init with any other key (`[key: string]: unknown`), added after inference. */
286
+ type WithAnyKeys<Init> = Init & { [key: string]: unknown };
287
+
288
+ /**
289
+ * @internal Exported for openapi-typesafe-react-query only; not part of the API (ADR-034).
290
+ * The operation of `Method` on `Path`. Not `Paths[Path][Method]`: `Paths` is only `{}`, because
291
+ * the generated `interface paths` has no index signature and failed a `Record<string, …>`
292
+ * constraint with TS2344 (upstream #2267), so TypeScript does not know `Method` is a key. For a
293
+ * union of paths or methods, the union of their operations; a method a path lacks (`put?: never`)
294
+ * adds none.
295
+ */
296
+ export type PathOperation<Paths, Path, Method> = Extract<
297
+ FilterKeys<Paths[Path & keyof Paths], Method>,
298
+ // biome-ignore lint/suspicious/noExplicitAny: unknown rejects the generated interfaces
299
+ Record<string | number, any>
300
+ >;
301
+
302
+ export type ClientMethod<Paths extends {}, Method extends HttpMethod, Media extends MediaType> = <
303
+ Path extends PathsWithMethod<Paths, Method>,
304
+ Init extends MaybeOptionalInit<Paths[Path], Method>,
305
+ >(
210
306
  url: Path,
211
307
  ...init: InitParam<Init>
212
- ) => Promise<FetchResponse<Paths[Path][Method], Init, Media>>;
308
+ ) => Promise<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>;
213
309
 
214
- export type ClientRequestMethod<Paths extends Record<string, Record<HttpMethod, {}>>, Media extends MediaType> = <
310
+ export type ClientRequestMethod<Paths extends {}, Media extends MediaType> = <
215
311
  Method extends HttpMethod,
216
312
  Path extends PathsWithMethod<Paths, Method>,
217
313
  Init extends MaybeOptionalInit<Paths[Path], Method>,
@@ -219,11 +315,21 @@ export type ClientRequestMethod<Paths extends Record<string, Record<HttpMethod,
219
315
  method: Method,
220
316
  url: Path,
221
317
  ...init: InitParam<Init>
222
- ) => Promise<FetchResponse<Paths[Path][Method], Init, Media>>;
318
+ ) => Promise<FetchResponse<PathOperation<Paths, Path, Method>, Init, Media>>;
223
319
 
224
320
  // Only HTTP method keys become calls: `parameters` and `additionalOperations` are not methods.
225
- export type ClientForPath<PathInfo extends Record<string | number, any>, Media extends MediaType> = {
226
- [Method in keyof PathInfo as Method extends HttpMethod ? Uppercase<Method> : never]: <
321
+ // They are left out by `Pick`, which keeps the `?` of a method, not by the key remapping: that is
322
+ // openapi-fetch's, and TypeScript relates two generic mapped types only when their key remappings
323
+ // are the same, so a path-based client type written like openapi-fetch's failed a cast (TS2352).
324
+ export type ClientForPath<
325
+ // biome-ignore lint/suspicious/noExplicitAny: unknown rejects the generated interfaces
326
+ PathInfo extends Record<string | number, any>,
327
+ Media extends MediaType,
328
+ > = PathMethodCalls<Pick<PathInfo, HttpMethod & keyof PathInfo>, Media>;
329
+
330
+ // biome-ignore lint/suspicious/noExplicitAny: unknown rejects the generated interfaces
331
+ type PathMethodCalls<PathInfo extends Record<string | number, any>, Media extends MediaType> = {
332
+ [Method in keyof PathInfo as Uppercase<string & Method>]: <
227
333
  Init extends MaybeOptionalInit<PathInfo, Method>,
228
334
  >(
229
335
  ...init: InitParam<Init>
@@ -256,34 +362,56 @@ export interface Client<Paths extends {}, Media extends MediaType = MediaType> {
256
362
  eject(...middleware: Middleware[]): void;
257
363
  }
258
364
 
259
- export type ClientPathsWithMethod<CreatedClient extends Client<any, any>, Method extends HttpMethod> =
365
+ export type ClientPathsWithMethod<
366
+ // biome-ignore lint/suspicious/noExplicitAny: matches a client of any paths, as in openapi-fetch
367
+ CreatedClient extends Client<any, any>,
368
+ Method extends HttpMethod,
369
+ > =
260
370
  CreatedClient extends Client<infer Paths, infer _Media> ? PathsWithMethod<Paths, Method> : never;
261
371
 
262
372
  export type MethodResponse<
373
+ // biome-ignore lint/suspicious/noExplicitAny: matches a client of any paths, as in openapi-fetch
263
374
  CreatedClient extends Client<any, any>,
264
375
  Method extends HttpMethod,
265
376
  Path extends ClientPathsWithMethod<CreatedClient, Method>,
266
377
  Options = {},
267
378
  > =
268
- CreatedClient extends Client<infer Paths extends { [key: string]: any }, infer Media extends MediaType>
379
+ CreatedClient extends Client<
380
+ // biome-ignore lint/suspicious/noExplicitAny: unknown rejects the generated interfaces
381
+ infer Paths extends { [key: string]: any },
382
+ infer Media extends MediaType
383
+ >
269
384
  ? NonNullable<FetchResponse<Paths[Path][Method], Options, Media>["data"]>
270
385
  : never;
271
386
 
272
387
  export default function createClient<Paths extends {}, Media extends MediaType = MediaType>(
273
388
  clientOptions?: ClientOptions,
274
389
  ): Client<Paths, Media>;
390
+ export default function createClient<Paths extends {}, Media extends MediaType = MediaType>(
391
+ clientOptions?: CustomFetchClientOptions,
392
+ ): Client<Paths, Media>;
275
393
 
276
- export type PathBasedClient<Paths extends Record<string | number, any>, Media extends MediaType = MediaType> = {
394
+ export type PathBasedClient<
395
+ // biome-ignore lint/suspicious/noExplicitAny: unknown rejects the generated interfaces
396
+ Paths extends Record<string | number, any>,
397
+ Media extends MediaType = MediaType,
398
+ > = {
277
399
  [Path in keyof Paths]: ClientForPath<Paths[Path], Media>;
278
400
  };
279
401
 
280
- export declare function wrapAsPathBasedClient<Paths extends {}, Media extends MediaType = MediaType>(
281
- client: Client<Paths, Media>,
282
- ): PathBasedClient<Paths, Media>;
402
+ export declare function wrapAsPathBasedClient<
403
+ Paths extends {},
404
+ Media extends MediaType = MediaType,
405
+ >(client: Client<Paths, Media>): PathBasedClient<Paths, Media>;
283
406
 
284
- export declare function createPathBasedClient<Paths extends {}, Media extends MediaType = MediaType>(
285
- clientOptions?: ClientOptions,
286
- ): PathBasedClient<Paths, Media>;
407
+ export declare function createPathBasedClient<
408
+ Paths extends {},
409
+ Media extends MediaType = MediaType,
410
+ >(clientOptions?: ClientOptions): PathBasedClient<Paths, Media>;
411
+ export declare function createPathBasedClient<
412
+ Paths extends {},
413
+ Media extends MediaType = MediaType,
414
+ >(clientOptions?: CustomFetchClientOptions): PathBasedClient<Paths, Media>;
287
415
 
288
416
  /** Serialize primitive params to string */
289
417
  export declare function serializePrimitiveParam(
@@ -324,12 +452,85 @@ export declare function createQuerySerializer<T = unknown>(
324
452
  * @type {import("./index.js").defaultPathSerializer}
325
453
  * @see https://swagger.io/docs/specification/serialization/#path
326
454
  */
327
- export declare function defaultPathSerializer(pathname: string, pathParams: Record<string, unknown>): string;
455
+ export declare function defaultPathSerializer(
456
+ pathname: string,
457
+ pathParams: Record<string, unknown>,
458
+ ): string;
459
+
460
+ /** Bodies that `fetch` sends as they are, so `defaultBodySerializer` returns them unchanged. */
461
+ type RawRequestBody = FormData | Blob | URLSearchParams | ArrayBuffer | ArrayBufferView;
462
+
463
+ /**
464
+ * The result of `defaultBodySerializer` for a body of type `Body`: the body itself when it is raw,
465
+ * `undefined` for `undefined` (`JSON.stringify` gives it back), `ObjectResult` for an object, and a
466
+ * string otherwise. `unknown` (and `any`) may be any of these.
467
+ */
468
+ type SerializedBody<Body, ObjectResult> = unknown extends Body
469
+ ? RawRequestBody | string | FormData | undefined
470
+ : Body extends RawRequestBody
471
+ ? Body
472
+ : Body extends undefined
473
+ ? undefined
474
+ : Body extends object
475
+ ? ObjectResult
476
+ : string;
477
+
478
+ /** The `Content-Type` values that make `defaultBodySerializer` turn an object into `FormData`. */
479
+ type MultipartMediaType = "multipart/form-data" | `multipart/form-data;${string}`;
480
+
481
+ /** `Headers` drops the spaces and tabs in front of a value before the media type is read. */
482
+ type TrimmedStart<Text extends string> = Text extends ` ${infer Rest}` | `\t${infer Rest}`
483
+ ? TrimmedStart<Rest>
484
+ : Text;
485
+
486
+ /**
487
+ * The `Content-Type` of headers written as a record, in any letter case of the name: `never` when
488
+ * the record has none, `unknown` when the type does not tell (`Headers`, pairs, a string record).
489
+ */
490
+ type ContentTypeOf<GivenHeaders> = GivenHeaders extends undefined
491
+ ? never
492
+ : GivenHeaders extends readonly unknown[] | { get(name: string): unknown }
493
+ ? unknown
494
+ : string extends keyof GivenHeaders
495
+ ? unknown
496
+ : ContentTypeEntries<GivenHeaders>[keyof GivenHeaders];
497
+
498
+ /** For each entry of a header record: its value when it is the `Content-Type`, else `never`. */
499
+ type ContentTypeEntries<Record> = { [Name in keyof Record]: ContentTypeEntry<Name, Record[Name]> };
500
+
501
+ /** The value of a header record entry when its name is `Content-Type` in any letter case. */
502
+ type ContentTypeEntry<Name, Value> =
503
+ Lowercase<Name & string> extends "content-type" ? Value : never;
504
+
505
+ /**
506
+ * What an object becomes with a `Content-Type` of type `ContentType`: `FormData` for a multipart
507
+ * one, a string for any other one or for none, and either when the type is not a literal.
508
+ */
509
+ type ObjectBodyResult<ContentType> = [ContentType] extends [never]
510
+ ? string
511
+ : ContentType extends null | undefined
512
+ ? string
513
+ : ContentType extends string
514
+ ? string extends ContentType
515
+ ? string | FormData
516
+ : Lowercase<TrimmedStart<ContentType>> extends MultipartMediaType
517
+ ? FormData
518
+ : string
519
+ : string | FormData;
328
520
 
329
521
  /**
330
- * Serialize body object to string; with a form content type in `headers`, as URL-encoded form data.
522
+ * Serialize a request body. A raw body (`FormData`, `Blob`, `URLSearchParams`, `ArrayBuffer`, a
523
+ * typed array) is returned as it is. With `headers`: a form `Content-Type` gives URL-encoded form
524
+ * data, a `multipart/form-data` one turns an object into `FormData`, and another non-JSON one keeps
525
+ * a string as it is. Anything else is JSON. Without `headers` an object can only become JSON.
526
+ * Headers written as a record literal tell the result type of an object body: `FormData` for a
527
+ * multipart `Content-Type`, `string` for another one or none. Other headers: `string | FormData`.
331
528
  */
332
- export declare function defaultBodySerializer<T>(body: T, headers?: HeadersOptions): string;
529
+ export declare function defaultBodySerializer<T>(body: T): SerializedBody<T, string>;
530
+ export declare function defaultBodySerializer<
531
+ T,
532
+ const GivenHeaders extends HeadersOptions | undefined,
533
+ >(body: T, headers: GivenHeaders): SerializedBody<T, ObjectBodyResult<ContentTypeOf<GivenHeaders>>>;
333
534
 
334
535
  /** Construct URL string from baseUrl and handle path and query params */
335
536
  export declare function createFinalURL<O>(