@kubb/plugin-fetch 5.13.0-canary.20261105T105941 → 5.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,913 +1,2 @@
1
- import { applyHeaderStyles, defaultBodySerializer, defaultPathSerializer, defaultQuerySerializer, isDefaultJsonBody, serializeCookies } from './serializers.ts'
2
- import type { HeadersInit, PathParamStyle, PathSerializer, RequestBody, Serializers, Styles } from './serializers.ts'
3
- import { ParseError, type StandardSchemaValidator, validateStandardSchema } from './standardSchema.ts'
4
-
5
- /**
6
- * HTTP status codes treated as a success, everything else is an error.
7
- */
8
- export type SuccessStatusCode = '200' | '201' | '202' | '203' | '204' | '205' | '206' | '207' | '208' | '226'
9
-
10
- export type SuccessOf<TResponses> = TResponses[Extract<keyof TResponses, SuccessStatusCode>]
11
-
12
- export type ErrorOf<TResponses> = TResponses[Exclude<keyof TResponses, SuccessStatusCode>]
13
-
14
- /**
15
- * Converts a response record's string status key to its numeric literal, leaving non-numeric keys like `default` as `number`.
16
- */
17
- export type ToStatusNumber<TStatus> = TStatus extends `${infer TNumber extends number}` ? TNumber : number
18
-
19
- /**
20
- * Unwraps content-type variants to keep the bare body on `error`.
21
- */
22
- export type DataOf<T> = T extends { contentType: string; data: infer TData } ? TData : T
23
-
24
- /**
25
- * Keeps `contentType` beside `data` so switching on it narrows the body.
26
- */
27
- export type SuccessVariant<TStatus, TEntry, TRequest, TResponse> = TEntry extends { contentType: string; data: unknown }
28
- ? TEntry extends { contentType: infer TContentType; data: infer TData }
29
- ? { status: ToStatusNumber<TStatus>; data: TData; error: undefined; contentType: TContentType; request: TRequest; response: TResponse }
30
- : never
31
- : { status: ToStatusNumber<TStatus>; data: TEntry; error: undefined; contentType: string | undefined; request: TRequest; response: TResponse }
32
-
33
- /**
34
- * Narrows `data` or `error` when switching on the numeric status.
35
- */
36
- export type ResultByStatus<TResponses, TStatus extends keyof TResponses, TRequest, TResponse> = TStatus extends SuccessStatusCode
37
- ? SuccessVariant<TStatus, TResponses[TStatus], TRequest, TResponse>
38
- : {
39
- status: ToStatusNumber<TStatus>
40
- data: undefined
41
- error: DataOf<TResponses[TStatus]>
42
- contentType: string | undefined
43
- request: TRequest
44
- response: TResponse
45
- }
46
-
47
- export type ResultUnion<TResponses, TRequest, TResponse> = {
48
- [TStatus in keyof TResponses]: ResultByStatus<TResponses, TStatus, TRequest, TResponse>
49
- }[keyof TResponses]
50
-
51
- /**
52
- * Selects success statuses without letting untyped error payloads widen `data`.
53
- */
54
- export type SuccessResultUnion<TResponses, TRequest, TResponse> = {
55
- [TStatus in Extract<keyof TResponses, SuccessStatusCode>]: ResultByStatus<TResponses, TStatus, TRequest, TResponse>
56
- }[Extract<keyof TResponses, SuccessStatusCode>]
57
-
58
- /**
59
- * Narrows `data` and `error` by status. With `throwOnError`, includes only success variants.
60
- */
61
- export type RequestResult<TResponses, ThrowOnError extends boolean = true, TRequest = Request, TResponse = Response> = ThrowOnError extends true
62
- ? [SuccessResultUnion<TResponses, TRequest, TResponse>] extends [never]
63
- ? {
64
- status: number
65
- data: SuccessOf<TResponses>
66
- error: undefined
67
- contentType: string | undefined
68
- request: TRequest
69
- response: TResponse
70
- }
71
- : SuccessResultUnion<TResponses, TRequest, TResponse>
72
- : [ResultUnion<TResponses, TRequest, TResponse>] extends [never]
73
- ? { status: number; data: undefined; error: undefined; contentType: string | undefined; request: TRequest; response: TResponse }
74
- : ResultUnion<TResponses, TRequest, TResponse>
75
-
76
- /**
77
- * A `RequestResult` promise with an extra `unwrap()` method that resolves to the success body.
78
- */
79
- export type Unwrappable<T extends { data: unknown; error: unknown }> = Promise<T> & {
80
- unwrap: () => Promise<Extract<T, { error: undefined }>['data']>
81
- }
82
-
83
- /**
84
- * Attaches `unwrap()` to a result promise, which rejects with `error` when the result carried one.
85
- *
86
- * @example
87
- * ```ts
88
- * const { data, error } = await getPetById({ path: { petId: 1 } })
89
- * ```
90
- *
91
- * @example
92
- * ```ts
93
- * const pet = await getPetById({ path: { petId: 1 } }).unwrap()
94
- * ```
95
- */
96
- export function withUnwrap<T extends { data: unknown; error: unknown }>(promise: Promise<T>): Unwrappable<T> {
97
- const unwrappable = promise as Unwrappable<T>
98
- unwrappable.unwrap = () =>
99
- promise.then((result) => {
100
- if (result.error !== undefined) throw result.error
101
- return result.data as Extract<T, { error: undefined }>['data']
102
- })
103
- return unwrappable
104
- }
105
-
106
- /**
107
- * The shape a generated operation returns with `returnType: 'data'`: the success body when
108
- * `throwOnError` is true, or the full `RequestResult` when it is false.
109
- */
110
- export type UnwrappedResult<TResponses, ThrowOnError extends boolean = true, TRequest = Request, TResponse = Response> = ThrowOnError extends true
111
- ? RequestResult<TResponses, true, TRequest, TResponse>['data']
112
- : RequestResult<TResponses, ThrowOnError, TRequest, TResponse>
113
-
114
- /**
115
- * Returns the success body when `throwOnError` is true, or the full result when it is false.
116
- */
117
- export function unwrapResult<T extends { data: unknown; error: unknown }>(promise: Promise<T>, throwOnError: boolean | undefined): Promise<T | T['data']> {
118
- return promise.then((result) => ((throwOnError ?? true) ? result.data : result))
119
- }
120
-
121
- export type DataShape = { body?: unknown; cookies?: unknown; headers?: unknown; path?: unknown; query?: unknown }
122
-
123
- export type RequestCredentials = 'omit' | 'same-origin' | 'include'
124
- export type ResponseType = 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream'
125
-
126
- /**
127
- * Decodes a response body for a codec's media type.
128
- */
129
- export type Deserializer<T = unknown> = (raw: unknown, contentType: string) => T | Promise<T>
130
-
131
- /**
132
- * Encodes a request body for a codec's media type.
133
- */
134
- export type ContentBodySerializer = (body: unknown, contentType?: string) => RequestBody | undefined
135
-
136
- /**
137
- * Encodes requests or decodes responses for a media type. Either direction can be omitted.
138
- */
139
- export type Codec = {
140
- serialize?: ContentBodySerializer
141
- deserialize?: Deserializer
142
- }
143
-
144
- /**
145
- * A string sets the request content type. The object form can also set `Accept`.
146
- */
147
- export type ContentType = string | { request?: string; response?: string }
148
-
149
- /**
150
- * Validates request bodies and params, success bodies, or non-throwing error bodies with Standard Schema.
151
- */
152
- export type Validator<T = unknown> = StandardSchemaValidator<T>
153
-
154
- /**
155
- * Identifies the value and request that failed validation in `onValidationError`.
156
- */
157
- export type ValidationErrorContext = {
158
- value: unknown
159
- direction: 'request' | 'response' | 'error'
160
- source: 'body' | 'path' | 'query' | 'headers'
161
- method?: string
162
- url?: string
163
- status?: number
164
- }
165
-
166
- /**
167
- * Return `{ value }` to substitute a failed value, including `undefined`. Returning nothing rethrows the `ParseError`.
168
- */
169
- export type ValidationErrorHandler = (error: ParseError, context: ValidationErrorContext) => { value: unknown } | void | Promise<{ value: unknown } | void>
170
-
171
- /**
172
- * Turns generated validation on or off. `false` skips every validator, an object skips only the directions set to `false`:
173
- * `request` is the body, `params` are path, query, and header params, `response` and `error` are the response bodies.
174
- * @default true
175
- */
176
- export type ValidateOption = boolean | { request?: boolean; params?: boolean; response?: boolean; error?: boolean }
177
-
178
- /**
179
- * A resolved security scheme carried on each generated call's `security` array and passed to the `auth` resolver.
180
- */
181
- export type Auth = {
182
- type: 'http' | 'apiKey' | 'oauth2' | 'openIdConnect'
183
- scheme?: 'bearer' | 'basic'
184
- name?: string
185
- in?: 'header' | 'query' | 'cookie'
186
- scopes?: Array<string>
187
- }
188
-
189
- /**
190
- * Return `user:password` for basic auth, or `undefined` to skip a scheme.
191
- */
192
- export type AuthToken = string | undefined
193
-
194
- /**
195
- * Resolves the token for a security scheme, either a static token or a callback called per scheme until one returns a token.
196
- */
197
- export type AuthResolver = AuthToken | ((auth: Auth) => AuthToken | Promise<AuthToken>)
198
-
199
- /**
200
- * Extra `fetch` init the transport spreads onto every `Request`, an escape hatch for fields the runtime does not set itself such as `cache`, `redirect`, and Next.js's `next`.
201
- */
202
- export type FetchOptions = RequestInit & { next?: Record<string, unknown> }
203
-
204
- export type RequestConfig<TBody = unknown, TRequest = Request, TResponse = Response> = {
205
- baseURL?: string
206
- url?: string
207
- method?: 'GET' | 'PUT' | 'PATCH' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'QUERY'
208
- path?: unknown
209
- query?: unknown
210
- params?: unknown
211
- cookies?: unknown
212
- body?: TBody
213
- headers?: unknown
214
- styles?: Styles
215
- signal?: AbortSignal
216
- credentials?: RequestCredentials
217
- options?: FetchOptions
218
- contentType?: ContentType
219
- responseType?: ResponseType
220
- throwOnError?: boolean
221
- client?: ClientInstance<TRequest, TResponse>
222
- transport?: Transport<TRequest, TResponse>
223
- serializer?: Serializers
224
- codecs?: Record<string, Codec>
225
- validator?: { request?: Validator; path?: Validator; query?: Validator; headers?: Validator; response?: Validator; error?: Validator }
226
- onValidationError?: ValidationErrorHandler
227
- validate?: ValidateOption
228
- security?: Array<Auth>
229
- auth?: AuthResolver
230
- }
231
-
232
- /**
233
- * Combines client options with the operation's typed request params and body.
234
- */
235
- export type Options<TData extends DataShape, ThrowOnError extends boolean = true, TRequest = Request, TResponse = Response> = Omit<
236
- RequestConfig<unknown, TRequest, TResponse>,
237
- keyof DataShape | 'url'
238
- > &
239
- TData & {
240
- client?: ClientInstance<TRequest, TResponse>
241
- throwOnError?: ThrowOnError
242
- }
243
-
244
- /**
245
- * Client-level configuration shared by every call an instance makes, overridden by the per-call `RequestConfig`.
246
- */
247
- export type ClientConfig<TRequest = Request, TResponse = Response> = {
248
- baseURL?: string
249
- headers?: HeadersInit
250
- credentials?: RequestCredentials
251
- options?: FetchOptions
252
- throwOnError?: boolean
253
- transport?: Transport<TRequest, TResponse>
254
- serializer?: Serializers
255
- codecs?: Record<string, Codec>
256
- onValidationError?: ValidationErrorHandler
257
- validate?: ValidateOption
258
- auth?: AuthResolver
259
- }
260
-
261
- /**
262
- * The normalized request the transport receives, with all serialization, auth, and header work already done.
263
- */
264
- export type ResolvedRequest = {
265
- url: string
266
- method: string
267
- headers: Record<string, string>
268
- body?: RequestBody
269
- signal?: AbortSignal
270
- credentials?: RequestCredentials
271
- options?: FetchOptions
272
- responseType?: ResponseType
273
- }
274
-
275
- /**
276
- * What a transport returns: the parsed body plus the native request and response objects.
277
- */
278
- export type TransportResult<TData = unknown, TRequest = Request, TResponse = Response> = {
279
- data: TData
280
- status: number
281
- statusText: string
282
- headers: Headers
283
- contentType?: string
284
- request: TRequest
285
- response: TResponse
286
- }
287
-
288
- /**
289
- * The per-plugin send, supplied to `createClientCore` as `defaultTransport`.
290
- */
291
- export type Transport<TRequest = Request, TResponse = Response> = (request: ResolvedRequest) => Promise<TransportResult<unknown, TRequest, TResponse>>
292
-
293
- export type CallResult<TRequest = Request, TResponse = Response> = {
294
- status: number
295
- data: unknown
296
- error: unknown
297
- contentType: string | undefined
298
- request: TRequest
299
- response: TResponse
300
- }
301
-
302
- export type InterceptorFn<T, TContext = never> = (value: T, context?: TContext) => T | Promise<T>
303
-
304
- /**
305
- * A single interceptor channel with a transport-agnostic `use` / `eject` / `update` API.
306
- */
307
- export type InterceptorStack<T, TContext = never> = {
308
- use: (fn: InterceptorFn<T, TContext>) => number
309
- eject: (id: number) => void
310
- update: (id: number, fn: InterceptorFn<T, TContext>) => void
311
- run: (value: T, context?: TContext) => Promise<T>
312
- }
313
-
314
- export type Interceptors<TRequest = Request, TResponse = Response> = {
315
- request: InterceptorStack<ResolvedRequest, RequestConfig<unknown, TRequest, TResponse>>
316
- response: InterceptorStack<TransportResult<unknown, TRequest, TResponse>, RequestConfig<unknown, TRequest, TResponse>>
317
- error: InterceptorStack<ResponseError<unknown, TRequest, TResponse>, RequestConfig<unknown, TRequest, TResponse>>
318
- }
319
-
320
- export type UrlConfig = Pick<RequestConfig, 'baseURL' | 'url' | 'path' | 'query' | 'params' | 'serializer' | 'styles'>
321
-
322
- /**
323
- * A client instance: the callable send plus configuration, interceptors, and an isolated
324
- * `createClient` factory bound to the same transport.
325
- */
326
- export type ClientInstance<TRequest = Request, TResponse = Response> = {
327
- <TBody = unknown>(config: RequestConfig<TBody, TRequest, TResponse>): Promise<CallResult<TRequest, TResponse>>
328
- getConfig: () => ClientConfig<TRequest, TResponse>
329
- setConfig: (config: ClientConfig<TRequest, TResponse>) => ClientConfig<TRequest, TResponse>
330
- getUrl: (config: UrlConfig) => string
331
- interceptors: Interceptors<TRequest, TResponse>
332
- createClient: (config?: ClientConfig<TRequest, TResponse>) => ClientInstance<TRequest, TResponse>
333
- }
334
-
335
- /**
336
- * Thrown for a non-2xx response, so a resolved call always means success.
337
- */
338
- export class ResponseError<TError = unknown, TRequest = Request, TResponse = Response> extends Error {
339
- data: TError
340
- status: number
341
- statusText: string
342
- contentType: string | undefined
343
- request: TRequest
344
- response: TResponse
345
-
346
- constructor(config: {
347
- data: TError
348
- status: number
349
- statusText: string
350
- contentType?: string
351
- request: TRequest
352
- response: TResponse
353
- method?: string
354
- url?: string
355
- }) {
356
- // The query and hash are left out: sensitive query parameters or fragments must not reach logs.
357
- const cleanUrl = config.url?.split(/[?#]/)[0]
358
- const target = [config.method, cleanUrl].filter(Boolean).join(' ')
359
- const statusText = config.statusText?.trim()
360
- super(`${target ? `${target} failed` : 'Request failed'} with status ${config.status}${statusText ? ` ${statusText}` : ''}`)
361
- this.name = 'ResponseError'
362
- this.data = config.data
363
- this.status = config.status
364
- this.statusText = config.statusText
365
- this.contentType = config.contentType
366
- this.request = config.request
367
- this.response = config.response
368
- }
369
-
370
- /**
371
- * Matches on `name`, not `instanceof`: every generated client bundles its own `ResponseError` class.
372
- */
373
- static is(error: unknown): error is ResponseError<unknown, unknown, unknown> {
374
- return error instanceof Error && error.name === 'ResponseError'
375
- }
376
- }
377
-
378
- export type ResponseErrorConfig<TError = unknown> = ResponseError<TError>
379
-
380
- function headerEntries(headers: object): Array<[string, unknown]> {
381
- if (Array.isArray(headers)) return headers
382
- return headers instanceof Headers ? [...headers] : Object.entries(headers)
383
- }
384
-
385
- function serializeHeaders(headers: HeadersInit | undefined): Record<string, string> {
386
- if (!headers) return {}
387
- const entries = headerEntries(headers)
388
- const result: Record<string, string> = {}
389
- for (const [key, value] of entries) {
390
- if (value === undefined || value === null) continue
391
- result[key] = typeof value === 'string' ? value : typeof value === 'object' ? JSON.stringify(value) : String(value)
392
- }
393
- return result
394
- }
395
-
396
- function collectHeadersCaseInsensitive(...sources: Array<unknown>): Record<string, unknown> {
397
- const keys = new Map<string, string>()
398
- const result: Record<string, unknown> = {}
399
- for (const source of sources) {
400
- if (!source) continue
401
- const entries = headerEntries(source)
402
- for (const [key, value] of entries) {
403
- if (value === undefined || value === null) continue
404
- const lowerCase = key.toLowerCase()
405
- const previous = keys.get(lowerCase)
406
- if (previous !== undefined) delete result[previous]
407
- keys.set(lowerCase, key)
408
- result[key] = value
409
- }
410
- }
411
- return result
412
- }
413
-
414
- function getHeader(headers: Record<string, string>, name: string): string | undefined {
415
- const key = Object.keys(headers).find((k) => k.toLowerCase() === name.toLowerCase())
416
- return key ? headers[key] : undefined
417
- }
418
-
419
- function serializeUrl({
420
- parts,
421
- pathParams,
422
- search,
423
- pathSerializer = defaultPathSerializer,
424
- pathStyles,
425
- }: {
426
- parts: Array<string | undefined>
427
- pathParams: Record<string, unknown>
428
- search: string
429
- pathSerializer?: PathSerializer
430
- pathStyles?: Record<string, PathParamStyle>
431
- }): string {
432
- const path = parts
433
- .filter(Boolean)
434
- .join('')
435
- .replace(/\{([^{}]+)\}/g, (_, key: string) => pathSerializer({ name: key, value: pathParams[key], options: pathStyles?.[key] }))
436
- return path + (search ? `?${search}` : '')
437
- }
438
-
439
- /**
440
- * Creates a transport-agnostic interceptor channel that runs interceptors in registration order.
441
- */
442
- export function createInterceptorStack<T, TContext = never>(): InterceptorStack<T, TContext> {
443
- let entries: Array<{ id: number; fn: InterceptorFn<T, TContext> }> = []
444
- let counter = 0
445
- return {
446
- use(fn) {
447
- const id = ++counter
448
- entries.push({ id, fn })
449
- return id
450
- },
451
- eject(id) {
452
- entries = entries.filter((entry) => entry.id !== id)
453
- },
454
- update(id, fn) {
455
- const entry = entries.find((item) => item.id === id)
456
- if (entry) entry.fn = fn
457
- },
458
- async run(value, context) {
459
- let result = value
460
- for (const entry of entries) {
461
- result = await entry.fn(result, context)
462
- }
463
- return result
464
- },
465
- }
466
- }
467
-
468
- /**
469
- * Walks the per-operation security in order and places the first resolved token on the request, mutating `headers` / `query` in place.
470
- */
471
- export async function resolveAuth(params: {
472
- security: Array<Auth> | undefined
473
- auth: AuthResolver | undefined
474
- headers: Record<string, string>
475
- query: Record<string, unknown>
476
- }): Promise<void> {
477
- const { security, auth, headers, query } = params
478
- if (!security?.length || auth === undefined) return
479
-
480
- for (const scheme of security) {
481
- const token = typeof auth === 'function' ? await auth(scheme) : auth
482
- if (token === undefined) continue
483
-
484
- if (scheme.type !== 'apiKey') {
485
- if (getHeader(headers, 'Authorization') === undefined) {
486
- headers['Authorization'] = scheme.scheme === 'basic' ? `Basic ${btoa(String.fromCharCode(...new TextEncoder().encode(token)))}` : `Bearer ${token}`
487
- }
488
- return
489
- }
490
-
491
- const name = scheme.name ?? 'Authorization'
492
- if (scheme.in === 'query') {
493
- if (query[name] === undefined) query[name] = token
494
- return
495
- }
496
- if (scheme.in === 'cookie') {
497
- headers['Cookie'] = [headers['Cookie'], `${name}=${token}`].filter(Boolean).join('; ')
498
- return
499
- }
500
- if (getHeader(headers, name) === undefined) headers[name] = token
501
- return
502
- }
503
- }
504
-
505
- function isValidationEnabled(validate: ValidateOption | undefined, direction: 'request' | 'params' | 'response' | 'error'): boolean {
506
- return typeof validate === 'object' ? validate[direction] !== false : validate !== false
507
- }
508
-
509
- async function runValidator<T>({
510
- validator,
511
- value,
512
- context,
513
- onValidationError,
514
- }: {
515
- validator: Validator<T> | undefined
516
- value: T
517
- context: Omit<ValidationErrorContext, 'value'>
518
- onValidationError: ValidationErrorHandler | undefined
519
- }): Promise<T> {
520
- if (!validator) return value
521
- try {
522
- return await validateStandardSchema(validator, value)
523
- } catch (error) {
524
- if (!onValidationError || !(error instanceof ParseError)) throw error
525
- const handled = await onValidationError(error, { ...context, value })
526
- if (!handled) throw error
527
- return handled.value as T
528
- }
529
- }
530
-
531
- function baseContentType(value: string | null | undefined): string | undefined {
532
- if (!value) return undefined
533
- return value.split(';')[0]!.trim().toLowerCase() || undefined
534
- }
535
-
536
- function getResponseContentType(headers: Headers | Record<string, string> | undefined): string | undefined {
537
- if (!headers) return undefined
538
- const value = headers instanceof Headers ? headers.get('Content-Type') : (headers['Content-Type'] ?? headers['content-type'])
539
- return baseContentType(value)
540
- }
541
-
542
- function resolveSerializers({ config, requestConfig }: { config: { serializer?: Serializers }; requestConfig: { serializer?: Serializers } }) {
543
- return {
544
- querySerializer: requestConfig.serializer?.query ?? config.serializer?.query ?? defaultQuerySerializer,
545
- bodySerializer: requestConfig.serializer?.body ?? config.serializer?.body ?? defaultBodySerializer,
546
- pathSerializer: requestConfig.serializer?.path ?? config.serializer?.path ?? defaultPathSerializer,
547
- }
548
- }
549
-
550
- async function resolveRequest<TBody, TRequest, TResponse>({
551
- config,
552
- requestConfig,
553
- }: {
554
- config: ClientConfig<TRequest, TResponse>
555
- requestConfig: RequestConfig<TBody, TRequest, TResponse>
556
- }): Promise<{ request: ResolvedRequest; codecs: Record<string, Codec>; validate: ValidateOption | undefined }> {
557
- const { querySerializer, bodySerializer, pathSerializer } = resolveSerializers({ config, requestConfig })
558
- const codecs = { ...config.codecs, ...requestConfig.codecs }
559
- const onValidationError = requestConfig.onValidationError ?? config.onValidationError
560
- const validate = requestConfig.validate ?? config.validate
561
- const validationContext = { direction: 'request', method: requestConfig.method, url: requestConfig.url } as const
562
-
563
- // Params are encoded before anything reads them: headers before styling, query before auth adds its values.
564
- const paramValues = {
565
- path: { ...(requestConfig.path as Record<string, unknown> | undefined) },
566
- query: { ...((requestConfig.query ?? requestConfig.params) as Record<string, unknown> | undefined) },
567
- headers: collectHeadersCaseInsensitive(config.headers, requestConfig.headers),
568
- }
569
- const [validatedPath, validatedQuery, validatedHeaders] = await Promise.all(
570
- (['path', 'query', 'headers'] as const).map((source) =>
571
- runValidator({
572
- validator: isValidationEnabled(validate, 'params') ? requestConfig.validator?.[source] : undefined,
573
- value: paramValues[source],
574
- context: { ...validationContext, source },
575
- onValidationError,
576
- }),
577
- ),
578
- )
579
-
580
- const headers = serializeHeaders(applyHeaderStyles(validatedHeaders as HeadersInit | undefined, requestConfig.styles?.header))
581
- const contentType = requestConfig.contentType
582
- const { request: requestContentTypeOption, response: responseContentType } = typeof contentType === 'string' ? { request: contentType } : (contentType ?? {})
583
- const requestContentType = requestContentTypeOption ?? getHeader(headers, 'content-type')
584
- if (responseContentType && getHeader(headers, 'accept') === undefined) {
585
- headers['Accept'] = responseContentType
586
- }
587
-
588
- const query: Record<string, unknown> = { ...(validatedQuery as Record<string, unknown> | undefined) }
589
-
590
- await resolveAuth({
591
- security: requestConfig.security,
592
- auth: requestConfig.auth ?? config.auth,
593
- headers,
594
- query,
595
- })
596
-
597
- if (requestConfig.cookies) {
598
- const cookie = serializeCookies(requestConfig.cookies as Record<string, unknown>, requestConfig.styles?.cookie)
599
- if (cookie) headers['Cookie'] = [headers['Cookie'], cookie].filter(Boolean).join('; ')
600
- }
601
-
602
- const validatedBody = await runValidator({
603
- validator: isValidationEnabled(validate, 'request') ? requestConfig.validator?.request : undefined,
604
- value: requestConfig.body,
605
- context: { ...validationContext, source: 'body' },
606
- onValidationError,
607
- })
608
- const requestContentTypeBase = baseContentType(requestContentType)
609
- const contentCodec = requestContentTypeBase ? codecs[requestContentTypeBase] : undefined
610
- const usesDefaultBodySerializer = !contentCodec?.serialize && bodySerializer === defaultBodySerializer
611
- const body = contentCodec?.serialize
612
- ? contentCodec.serialize(validatedBody, requestContentType)
613
- : bodySerializer({ body: validatedBody, contentType: requestContentType, encoding: requestConfig.styles?.body })
614
- if (requestContentTypeOption) headers['Content-Type'] = requestContentTypeOption
615
- if (usesDefaultBodySerializer && isDefaultJsonBody(validatedBody) && getHeader(headers, 'content-type') === undefined) {
616
- headers['Content-Type'] = 'application/json'
617
- }
618
- // The transport must set the multipart boundary, even when a content type was explicitly provided.
619
- if (body instanceof FormData) {
620
- for (const key of Object.keys(headers)) {
621
- if (key.toLowerCase() === 'content-type') delete headers[key]
622
- }
623
- }
624
-
625
- const url = serializeUrl({
626
- parts: [requestConfig.baseURL ?? config.baseURL, requestConfig.url],
627
- pathParams: (validatedPath ?? {}) as Record<string, unknown>,
628
- search: querySerializer(query, requestConfig.styles?.query),
629
- pathSerializer,
630
- pathStyles: requestConfig.styles?.path,
631
- })
632
-
633
- const options = config.options || requestConfig.options ? { ...config.options, ...requestConfig.options } : undefined
634
-
635
- return {
636
- codecs,
637
- validate,
638
- request: {
639
- url,
640
- method: (requestConfig.method ?? 'GET').toUpperCase(),
641
- headers,
642
- body,
643
- signal: requestConfig.signal,
644
- credentials: requestConfig.credentials ?? config.credentials,
645
- options,
646
- responseType: requestConfig.responseType,
647
- },
648
- }
649
- }
650
-
651
- /**
652
- * Creates an isolated client using the supplied default transport.
653
- */
654
- export function createClientCore<TRequest = Request, TResponse = Response>(
655
- options: { defaultTransport: Transport<TRequest, TResponse> } & ClientConfig<TRequest, TResponse>,
656
- ): ClientInstance<TRequest, TResponse> {
657
- const { defaultTransport, ...initialConfig } = options
658
- let config: ClientConfig<TRequest, TResponse> = { ...initialConfig }
659
-
660
- const interceptors: Interceptors<TRequest, TResponse> = {
661
- request: createInterceptorStack<ResolvedRequest, RequestConfig<unknown, TRequest, TResponse>>(),
662
- response: createInterceptorStack<TransportResult<unknown, TRequest, TResponse>, RequestConfig<unknown, TRequest, TResponse>>(),
663
- error: createInterceptorStack<ResponseError<unknown, TRequest, TResponse>, RequestConfig<unknown, TRequest, TResponse>>(),
664
- }
665
-
666
- const client = (async <TBody = unknown>(requestConfig: RequestConfig<TBody, TRequest, TResponse>): Promise<CallResult<TRequest, TResponse>> => {
667
- const transport = requestConfig.transport ?? config.transport ?? defaultTransport
668
- const { request, codecs, validate } = await resolveRequest({ config, requestConfig })
669
-
670
- const resolvedRequest = await interceptors.request.run(request, requestConfig)
671
- const result = await interceptors.response.run(await transport(resolvedRequest), requestConfig)
672
-
673
- const throwOnError = requestConfig.throwOnError ?? config.throwOnError ?? true
674
- const validator = requestConfig.validator
675
- const onValidationError = requestConfig.onValidationError ?? config.onValidationError
676
- const isSuccess = result.status >= 200 && result.status < 300
677
- const direction = isSuccess ? 'response' : 'error'
678
- const contentType = result.contentType ?? getResponseContentType(result.headers)
679
- const codec = contentType ? codecs[contentType] : undefined
680
- const decoded = contentType && codec?.deserialize ? await codec.deserialize(result.data, contentType) : result.data
681
- const data = await runValidator({
682
- validator: isValidationEnabled(validate, direction) ? validator?.[direction] : undefined,
683
- value: decoded,
684
- context: { direction, source: 'body', method: resolvedRequest.method, url: resolvedRequest.url, status: result.status },
685
- onValidationError,
686
- })
687
- if (!isSuccess && throwOnError) {
688
- const responseError = new ResponseError({
689
- data,
690
- status: result.status,
691
- statusText: result.statusText,
692
- contentType,
693
- request: result.request,
694
- response: result.response,
695
- method: resolvedRequest.method,
696
- url: resolvedRequest.url,
697
- })
698
- await interceptors.error.run(responseError, requestConfig)
699
- throw responseError
700
- }
701
- return {
702
- status: result.status,
703
- data: isSuccess ? data : undefined,
704
- error: isSuccess ? undefined : data,
705
- contentType,
706
- request: result.request,
707
- response: result.response,
708
- }
709
- }) as ClientInstance<TRequest, TResponse>
710
-
711
- client.getConfig = () => config
712
- client.setConfig = (next) => {
713
- config = { ...config, ...next, headers: { ...serializeHeaders(config.headers), ...serializeHeaders(next.headers) } }
714
- return config
715
- }
716
- client.getUrl = (requestConfig) => {
717
- const { querySerializer, pathSerializer } = resolveSerializers({ config, requestConfig })
718
- const query: Record<string, unknown> = { ...((requestConfig.query ?? requestConfig.params) as Record<string, unknown> | undefined) }
719
- return serializeUrl({
720
- parts: [requestConfig.baseURL ?? config.baseURL, requestConfig.url],
721
- pathParams: (requestConfig.path ?? {}) as Record<string, unknown>,
722
- search: querySerializer(query, requestConfig.styles?.query),
723
- pathSerializer,
724
- pathStyles: requestConfig.styles?.path,
725
- })
726
- }
727
- client.interceptors = interceptors
728
- client.createClient = (next) => createClientCore({ defaultTransport, ...config, ...next })
729
-
730
- return client
731
- }
732
-
733
- function detectResponseType(contentType: string | null): ResponseType | undefined {
734
- if (!contentType) return undefined
735
- if (contentType.includes('text/event-stream')) return 'stream'
736
- if (contentType.includes('application/json') || contentType.includes('text/json')) return 'json'
737
- if (contentType.includes('text/')) return 'text'
738
- if (contentType.includes('image/') || contentType.includes('application/octet-stream')) return 'blob'
739
- return undefined
740
- }
741
-
742
- async function parseResponse(response: Response, responseType?: ResponseType): Promise<unknown> {
743
- if (response.status === 204 || response.status === 205 || response.status === 304 || !response.body) {
744
- return undefined
745
- }
746
-
747
- switch (responseType ?? detectResponseType(response.headers.get('Content-Type'))) {
748
- case 'text':
749
- case 'document':
750
- return response.text()
751
- case 'blob':
752
- return response.blob()
753
- case 'arraybuffer':
754
- return response.arrayBuffer()
755
- case 'stream':
756
- return response.body ?? undefined
757
- case 'json': {
758
- // An empty body with a JSON content-type would make response.json() throw, so treat it as no data.
759
- const body = await response.text()
760
- return body ? JSON.parse(body) : undefined
761
- }
762
- }
763
-
764
- const text = await response.text()
765
- if (!text) return undefined
766
- try {
767
- return JSON.parse(text)
768
- } catch {
769
- return text
770
- }
771
- }
772
-
773
- /**
774
- * The default transport that sends the resolved request through `globalThis.fetch` and returns the parsed body with the native request and response.
775
- */
776
- export const defaultTransport: Transport = async (request: ResolvedRequest): Promise<TransportResult> => {
777
- const init: RequestInit = {
778
- ...request.options,
779
- method: request.method,
780
- headers: request.headers,
781
- body: request.body,
782
- signal: request.signal,
783
- }
784
- if (request.credentials) init.credentials = request.credentials
785
-
786
- const nativeRequest = new Request(request.url, init)
787
- const response = await globalThis.fetch(nativeRequest)
788
- const data = await parseResponse(response, request.responseType)
789
-
790
- return {
791
- data,
792
- status: response.status,
793
- statusText: response.statusText,
794
- headers: response.headers,
795
- contentType: getResponseContentType(response.headers),
796
- request: nativeRequest,
797
- response,
798
- }
799
- }
800
-
801
- /**
802
- * One decoded Server-Sent Event, with `data` parsed as JSON when valid and kept as the raw string otherwise.
803
- */
804
- export type ServerSentEvent<TData = unknown> = {
805
- data: TData
806
- event?: string
807
- id?: string
808
- retry?: number
809
- }
810
-
811
- async function* readBytes(stream: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>): AsyncGenerator<Uint8Array> {
812
- if (!('getReader' in stream)) {
813
- yield* stream
814
- return
815
- }
816
-
817
- const reader = stream.getReader()
818
- try {
819
- while (true) {
820
- const { done, value } = await reader.read()
821
- if (done) return
822
- yield value
823
- }
824
- } finally {
825
- await reader.cancel().catch(() => {})
826
- }
827
- }
828
-
829
- function parseEvent<TData>(raw: string): ServerSentEvent<TData> | undefined {
830
- const data: Array<string> = []
831
- const event: ServerSentEvent<TData> = { data: undefined as TData }
832
- let seen = false
833
-
834
- for (const line of raw.split('\n')) {
835
- if (!line || line.startsWith(':')) continue
836
- seen = true
837
- const index = line.indexOf(':')
838
- const field = index === -1 ? line : line.slice(0, index)
839
- const value = index === -1 ? '' : line.slice(index + 1).replace(/^ /, '')
840
- switch (field) {
841
- case 'data':
842
- data.push(value)
843
- break
844
- case 'event':
845
- event.event = value
846
- break
847
- case 'id':
848
- event.id = value
849
- break
850
- case 'retry':
851
- if (Number.isFinite(Number(value))) event.retry = Number(value)
852
- break
853
- }
854
- }
855
-
856
- if (!seen) return undefined
857
-
858
- if (data.length) {
859
- const joined = data.join('\n')
860
- try {
861
- event.data = JSON.parse(joined) as TData
862
- } catch {
863
- event.data = joined as TData
864
- }
865
- }
866
- return event
867
- }
868
-
869
- /**
870
- * Parses a `text/event-stream` body into typed Server-Sent Events, consumed with `for await` and stopped early by breaking the loop.
871
- */
872
- export async function* parseEventStream<TData = unknown>(
873
- stream: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>,
874
- ): AsyncGenerator<ServerSentEvent<TData>> {
875
- const decoder = new TextDecoder()
876
- const normalize = (text: string) => text.replace(/\r\n|\r/g, '\n')
877
- let buffer = ''
878
-
879
- for await (const chunk of readBytes(stream)) {
880
- const blocks = normalize(buffer + decoder.decode(chunk, { stream: true })).split('\n\n')
881
- buffer = blocks.pop() ?? ''
882
- for (const block of blocks) {
883
- const event = parseEvent<TData>(block)
884
- if (event) yield event
885
- }
886
- }
887
-
888
- const event = parseEvent<TData>(normalize(buffer + decoder.decode()))
889
- if (event) yield event
890
- }
891
-
892
- /**
893
- * Returns parsed events alongside the native response.
894
- */
895
- export type EventStreamResult<TData = unknown, TResponse = Response> = {
896
- stream: AsyncGenerator<ServerSentEvent<TData>>
897
- response: TResponse
898
- }
899
-
900
- /**
901
- * Exposes a streaming response body as typed Server-Sent Events.
902
- */
903
- export async function toEventStream<TData = unknown>(result: Promise<{ data: unknown; response: Response }>): Promise<EventStreamResult<TData>> {
904
- const { data, response } = await result
905
- return {
906
- response,
907
- stream: parseEventStream<TData>(data as ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>),
908
- }
909
- }
910
-
911
- export const client = createClientCore({ defaultTransport })
912
-
913
- export const createClient = (config?: Parameters<typeof client.createClient>[0]) => client.createClient(config)
1
+ // The client template was `templates/fetch.ts` before it became `templates/client.ts`; this keeps the old subpath working.
2
+ export * from './client.ts'