@kubb/plugin-fetch 5.9.0-canary.20261024T190549 → 5.9.1

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.
@@ -162,16 +162,19 @@ export type ContentType = string | {
162
162
  * A Standard Schema validator (zod, valibot, arktype) that parses a value before it is sent or after
163
163
  * it is received. `runValidator` runs it through `validateStandardSchema`. Wired through the per-call
164
164
  * `validator.request` / `validator.response` / `validator.error` hooks (`error` runs on the error body when a
165
- * non-2xx call does not throw).
165
+ * non-2xx call does not throw), and `validator.path` / `validator.query` / `validator.headers` for the
166
+ * request params.
166
167
  */
167
168
  export type Validator<T = unknown> = StandardSchemaValidator<T>;
168
169
  /**
169
- * The failing body and the call it came from, handed to `onValidationError` alongside the `ParseError`.
170
- * `direction` says which slot rejected it: the request body, the success body, or the error body.
170
+ * The failing value and the call it came from, handed to `onValidationError` alongside the `ParseError`.
171
+ * `direction` says which side rejected it: the request, the success body, or the error body. `source`
172
+ * says which part of it: the body, or one of the request param groups.
171
173
  */
172
174
  export type ValidationErrorContext = {
173
175
  value: unknown;
174
176
  direction: 'request' | 'response' | 'error';
177
+ source: 'body' | 'path' | 'query' | 'headers';
175
178
  method?: string;
176
179
  url?: string;
177
180
  status?: number;
@@ -236,6 +239,9 @@ export type RequestConfig<TBody = unknown, TRequest = Request, TResponse = Respo
236
239
  codecs?: Record<string, Codec>;
237
240
  validator?: {
238
241
  request?: Validator;
242
+ path?: Validator;
243
+ query?: Validator;
244
+ headers?: Validator;
239
245
  response?: Validator;
240
246
  error?: Validator;
241
247
  };
@@ -324,6 +330,7 @@ export type Interceptors<TRequest = Request, TResponse = Response> = {
324
330
  response: InterceptorStack<TransportResult<unknown, TRequest, TResponse>, RequestConfig<unknown, TRequest, TResponse>>;
325
331
  error: InterceptorStack<ResponseError<unknown, TRequest, TResponse>, RequestConfig<unknown, TRequest, TResponse>>;
326
332
  };
333
+ export type UrlConfig = Pick<RequestConfig, 'baseURL' | 'url' | 'path' | 'query' | 'params' | 'serializer' | 'styles'>;
327
334
  /**
328
335
  * A client instance: the callable send plus configuration, interceptors, and an isolated
329
336
  * `createClient` factory bound to the same transport.
@@ -332,7 +339,7 @@ export type ClientInstance<TRequest = Request, TResponse = Response> = {
332
339
  <TBody = unknown>(config: RequestConfig<TBody, TRequest, TResponse>): Promise<CallResult<TRequest, TResponse>>;
333
340
  getConfig: () => ClientConfig<TRequest, TResponse>;
334
341
  setConfig: (config: ClientConfig<TRequest, TResponse>) => ClientConfig<TRequest, TResponse>;
335
- getUrl: <TBody = unknown>(config: RequestConfig<TBody, TRequest, TResponse>) => string;
342
+ getUrl: (config: UrlConfig) => string;
336
343
  interceptors: Interceptors<TRequest, TResponse>;
337
344
  createClient: (config?: ClientConfig<TRequest, TResponse>) => ClientInstance<TRequest, TResponse>;
338
345
  };
@@ -48,4 +48,18 @@ export declare class ParseError extends Error {
48
48
  * const pet = await validateStandardSchema(PetSchema, rawData)
49
49
  */
50
50
  export declare function validateStandardSchema<TOutput>(schema: StandardSchemaValidator<TOutput>, value: unknown): Promise<TOutput>;
51
+ /**
52
+ * Wraps an object schema so its keys match case-insensitively.
53
+ * Keys the schema does not declare pass through untouched.
54
+ * The declared keys are validated with `schema` under their declared names.
55
+ * Every key, and every issue path, keeps the casing the caller used.
56
+ *
57
+ * @param schema Standard Schema-compatible object schema.
58
+ * @param entries The record of keys the passed object schema validates.
59
+ * @example
60
+ * ```ts
61
+ * validator: { headers: toHeadersStandardSchema(putEventHeadersSchema, putEventHeadersSchema.shape) }
62
+ * ```
63
+ */
64
+ export declare function toHeadersStandardSchema(schema: StandardSchemaValidator, entries: Record<string, unknown>): StandardSchemaValidator;
51
65
  //#endregion
package/docs/options.md CHANGED
@@ -10,7 +10,7 @@ Pass these options to `pluginFetch()`. Shared options link to [Shared plugin opt
10
10
  | [`group`](https://kubb.dev/docs/5.x/reference/plugin-options#group) | Split output by tag or path: `type`, `name`. | None |
11
11
  | [`baseURL`](#baseurl) | Base URL prepended to every request. | None |
12
12
  | [`throwOnErrorDefault`](#throwonerrordefault) | Default error behavior and return type for generated operations. | `true` |
13
- | [`validator`](#validator) | Validate request and response bodies with Zod. | `false` |
13
+ | [`validator`](#validator) | Validate request bodies, params, and responses with Zod. | `false` |
14
14
  | [`sdk`](#sdk) | Generate a class-based SDK instead of functions. | None |
15
15
  | [`returnType`](#returntype) | Shape of the value a generated call resolves to. | `'full'` |
16
16
  | [`include`](https://kubb.dev/docs/5.x/reference/plugin-options#include) | Keep only operations that match. | None |
@@ -48,13 +48,13 @@ if (result.status !== 200) console.error(result.status, result.error)
48
48
 
49
49
  ### validator
50
50
 
51
- Validates request and response bodies with schemas from `@kubb/plugin-zod`, so add `pluginZod()` too. An invalid body makes the generated function throw a `ParseError`.
51
+ Validates request bodies, path, query, and header params, and response bodies with schemas from `@kubb/plugin-zod`, so add `pluginZod()` too. An invalid value makes the generated function throw a `ParseError`.
52
52
 
53
- | | |
54
- | -------- | --------------------------------------------------------- |
55
- | Type | `false \| 'zod' \| { request?: 'zod'; response?: 'zod' }` |
56
- | Required | `false` |
57
- | Default | `false` |
53
+ | | |
54
+ | -------- | ------------------------------------------------------------------------- |
55
+ | Type | `false \| 'zod' \| { request?: 'zod'; params?: 'zod'; response?: 'zod' }` |
56
+ | Required | `false` |
57
+ | Default | `false` |
58
58
 
59
59
  ::field-group
60
60
 
@@ -66,8 +66,8 @@ Default value. Does no validation and returns the response cast to the generated
66
66
  Validates the success response body, and the error body when a non-2xx call does not throw.
67
67
  :::
68
68
 
69
- :::field{name="{ request?: 'zod', response?: 'zod' }"}
70
- Opts in per direction. `request` validates the request body before the call, and `response` validates the response body after it.
69
+ :::field{name="{ request?: 'zod', params?: 'zod', response?: 'zod' }"}
70
+ Opts in per direction. `request` validates the request body and `params` validates the path, query, and header params before the call. `response` validates the response body after it.
71
71
  :::
72
72
 
73
73
  ::
@@ -84,11 +84,17 @@ export default defineConfig({
84
84
  plugins: [
85
85
  pluginTs(),
86
86
  pluginZod(),
87
- pluginFetch({ validator: { request: 'zod', response: 'zod' } }),
87
+ pluginFetch({ validator: { request: 'zod', params: 'zod', response: 'zod' } }),
88
88
  ],
89
89
  })
90
90
  ```
91
91
 
92
+ `params` runs each group through its generated `<operation>PathSchema`, `QuerySchema`, or `HeadersSchema`, and sends what the schema returns. A codec param such as a `Date` goes out in its wire form, and an invalid param fails before the request. Values added by `auth` are not validated.
93
+
94
+ Only the params your OpenAPI spec declares are sent. Path and query keys the spec does not declare are stripped, so a key such as an undocumented filter or a cache-buster never reaches the URL. Declare it in the spec, or leave `params` off. Headers are the exception: client-level `headers` (such as `Authorization` or tracing headers) are merged with the call's headers before validation, so headers the spec does not declare pass through unchanged, and declared header params match in any casing.
95
+
96
+ Pair `request` and `params` with `pluginZod({ inferred: 'codec' })` when the schemas use codecs, so the request types accept the domain values (such as a `Date`) that the validators encode. See [`inferred`](https://kubb.dev/extensions/kubb-labs/plugin-zod/options#inferred).
97
+
92
98
  ### sdk
93
99
 
94
100
  Generates a class-based SDK. Each instance takes its own client config, so environments can use separate clients. Leave `sdk` unset to keep the standalone functions that query plugins call.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubb/plugin-fetch",
3
- "version": "5.9.0-canary.20261024T190549",
3
+ "version": "5.9.1",
4
4
  "description": "Generate a slim, type-safe HTTP client with Kubb based on the native Fetch api.",
5
5
  "keywords": [
6
6
  "api-client",
@@ -80,12 +80,12 @@
80
80
  "registry": "https://registry.npmjs.org/"
81
81
  },
82
82
  "dependencies": {
83
- "@kubb/plugin-ts": "^5.2.0-canary.20261024T190548",
84
- "@kubb/plugin-zod": "^5.7.0-canary.20261024T190548"
83
+ "@kubb/plugin-ts": "^5.1.0",
84
+ "@kubb/plugin-zod": "^5.7.1"
85
85
  },
86
86
  "devDependencies": {
87
- "@internals/client": "0.1.0-canary.20261024T190549",
88
- "@internals/shared": "0.1.0-canary.20261024T190548",
87
+ "@internals/client": "0.0.0",
88
+ "@internals/shared": "0.0.0",
89
89
  "kubb": "^5.13.0",
90
90
  "typescript": "^7.0.2"
91
91
  },
@@ -161,17 +161,20 @@ export type ContentType = string | { request?: string; response?: string }
161
161
  * A Standard Schema validator (zod, valibot, arktype) that parses a value before it is sent or after
162
162
  * it is received. `runValidator` runs it through `validateStandardSchema`. Wired through the per-call
163
163
  * `validator.request` / `validator.response` / `validator.error` hooks (`error` runs on the error body when a
164
- * non-2xx call does not throw).
164
+ * non-2xx call does not throw), and `validator.path` / `validator.query` / `validator.headers` for the
165
+ * request params.
165
166
  */
166
167
  export type Validator<T = unknown> = StandardSchemaValidator<T>
167
168
 
168
169
  /**
169
- * The failing body and the call it came from, handed to `onValidationError` alongside the `ParseError`.
170
- * `direction` says which slot rejected it: the request body, the success body, or the error body.
170
+ * The failing value and the call it came from, handed to `onValidationError` alongside the `ParseError`.
171
+ * `direction` says which side rejected it: the request, the success body, or the error body. `source`
172
+ * says which part of it: the body, or one of the request param groups.
171
173
  */
172
174
  export type ValidationErrorContext = {
173
175
  value: unknown
174
176
  direction: 'request' | 'response' | 'error'
177
+ source: 'body' | 'path' | 'query' | 'headers'
175
178
  method?: string
176
179
  url?: string
177
180
  status?: number
@@ -234,7 +237,7 @@ export type RequestConfig<TBody = unknown, TRequest = Request, TResponse = Respo
234
237
  transport?: Transport<TRequest, TResponse>
235
238
  serializer?: Serializers
236
239
  codecs?: Record<string, Codec>
237
- validator?: { request?: Validator; response?: Validator; error?: Validator }
240
+ validator?: { request?: Validator; path?: Validator; query?: Validator; headers?: Validator; response?: Validator; error?: Validator }
238
241
  onValidationError?: ValidationErrorHandler
239
242
  security?: Array<Auth>
240
243
  auth?: AuthResolver
@@ -334,6 +337,8 @@ export type Interceptors<TRequest = Request, TResponse = Response> = {
334
337
  error: InterceptorStack<ResponseError<unknown, TRequest, TResponse>, RequestConfig<unknown, TRequest, TResponse>>
335
338
  }
336
339
 
340
+ export type UrlConfig = Pick<RequestConfig, 'baseURL' | 'url' | 'path' | 'query' | 'params' | 'serializer' | 'styles'>
341
+
337
342
  /**
338
343
  * A client instance: the callable send plus configuration, interceptors, and an isolated
339
344
  * `createClient` factory bound to the same transport.
@@ -342,7 +347,7 @@ export type ClientInstance<TRequest = Request, TResponse = Response> = {
342
347
  <TBody = unknown>(config: RequestConfig<TBody, TRequest, TResponse>): Promise<CallResult<TRequest, TResponse>>
343
348
  getConfig: () => ClientConfig<TRequest, TResponse>
344
349
  setConfig: (config: ClientConfig<TRequest, TResponse>) => ClientConfig<TRequest, TResponse>
345
- getUrl: <TBody = unknown>(config: RequestConfig<TBody, TRequest, TResponse>) => string
350
+ getUrl: (config: UrlConfig) => string
346
351
  interceptors: Interceptors<TRequest, TResponse>
347
352
  createClient: (config?: ClientConfig<TRequest, TResponse>) => ClientInstance<TRequest, TResponse>
348
353
  }
@@ -392,9 +397,14 @@ export class ResponseError<TError = unknown, TRequest = Request, TResponse = Res
392
397
 
393
398
  export type ResponseErrorConfig<TError = unknown> = ResponseError<TError>
394
399
 
400
+ function headerEntries(headers: object): Array<[string, unknown]> {
401
+ if (Array.isArray(headers)) return headers
402
+ return headers instanceof Headers ? [...headers] : Object.entries(headers)
403
+ }
404
+
395
405
  function serializeHeaders(headers: HeadersInit | undefined): Record<string, string> {
396
406
  if (!headers) return {}
397
- const entries = Array.isArray(headers) ? headers : Object.entries(headers)
407
+ const entries = headerEntries(headers)
398
408
  const result: Record<string, string> = {}
399
409
  for (const [key, value] of entries) {
400
410
  if (value === undefined || value === null) continue
@@ -403,8 +413,22 @@ function serializeHeaders(headers: HeadersInit | undefined): Record<string, stri
403
413
  return result
404
414
  }
405
415
 
406
- function mergeHeaders(...sources: Array<HeadersInit | undefined>): Record<string, string> {
407
- return Object.assign({}, ...sources.map(serializeHeaders))
416
+ function collectHeadersCaseInsensitive(...sources: Array<unknown>): Record<string, unknown> {
417
+ const keys = new Map<string, string>()
418
+ const result: Record<string, unknown> = {}
419
+ for (const source of sources) {
420
+ if (!source) continue
421
+ const entries = headerEntries(source)
422
+ for (const [key, value] of entries) {
423
+ if (value === undefined || value === null) continue
424
+ const lowerCase = key.toLowerCase()
425
+ const previous = keys.get(lowerCase)
426
+ if (previous !== undefined) delete result[previous]
427
+ keys.set(lowerCase, key)
428
+ result[key] = value
429
+ }
430
+ }
431
+ return result
408
432
  }
409
433
 
410
434
  function getHeader(headers: Record<string, string>, name: string): string | undefined {
@@ -573,15 +597,29 @@ async function resolveRequest<TBody, TRequest, TResponse>({
573
597
  }): Promise<{ request: ResolvedRequest; codecs: Record<string, Codec> }> {
574
598
  const { querySerializer, bodySerializer, pathSerializer } = resolveSerializers({ config, requestConfig })
575
599
  const codecs = { ...config.codecs, ...requestConfig.codecs }
600
+ const onValidationError = requestConfig.onValidationError ?? config.onValidationError
601
+ const validationContext = { direction: 'request', method: requestConfig.method, url: requestConfig.url } as const
602
+
603
+ // Params are encoded before anything reads them: headers before styling, query before auth adds its values.
604
+ const paramValues = {
605
+ path: { ...(requestConfig.path as Record<string, unknown> | undefined) },
606
+ query: { ...((requestConfig.query ?? requestConfig.params) as Record<string, unknown> | undefined) },
607
+ headers: collectHeadersCaseInsensitive(config.headers, requestConfig.headers),
608
+ }
609
+ const [validatedPath, validatedQuery, validatedHeaders] = await Promise.all(
610
+ (['path', 'query', 'headers'] as const).map((source) =>
611
+ runValidator({ validator: requestConfig.validator?.[source], value: paramValues[source], context: { ...validationContext, source }, onValidationError }),
612
+ ),
613
+ )
576
614
 
577
- const headers = mergeHeaders(config.headers, applyHeaderStyles(requestConfig.headers as HeadersInit | undefined, requestConfig.styles?.header))
615
+ const headers = serializeHeaders(applyHeaderStyles(validatedHeaders as HeadersInit | undefined, requestConfig.styles?.header))
578
616
  const { request: requestContentTypeOption, response: responseContentType } = resolveContentType(requestConfig.contentType)
579
617
  const requestContentType = requestContentTypeOption ?? getHeader(headers, 'content-type')
580
618
  if (responseContentType && !hasHeader(headers, 'accept')) {
581
619
  headers['Accept'] = responseContentType
582
620
  }
583
621
 
584
- const query: Record<string, unknown> = { ...((requestConfig.query ?? requestConfig.params) as Record<string, unknown> | undefined) }
622
+ const query: Record<string, unknown> = { ...(validatedQuery as Record<string, unknown> | undefined) }
585
623
 
586
624
  await resolveAuth({
587
625
  security: requestConfig.security,
@@ -598,8 +636,8 @@ async function resolveRequest<TBody, TRequest, TResponse>({
598
636
  const validatedBody = await runValidator({
599
637
  validator: requestConfig.validator?.request,
600
638
  value: requestConfig.body,
601
- context: { direction: 'request', method: requestConfig.method, url: requestConfig.url },
602
- onValidationError: requestConfig.onValidationError ?? config.onValidationError,
639
+ context: { ...validationContext, source: 'body' },
640
+ onValidationError,
603
641
  })
604
642
  const requestContentTypeBase = baseContentType(requestContentType)
605
643
  const contentCodec = requestContentTypeBase ? codecs[requestContentTypeBase] : undefined
@@ -620,7 +658,7 @@ async function resolveRequest<TBody, TRequest, TResponse>({
620
658
 
621
659
  const url = serializeUrl({
622
660
  parts: [requestConfig.baseURL ?? config.baseURL, requestConfig.url],
623
- pathParams: (requestConfig.path ?? {}) as Record<string, unknown>,
661
+ pathParams: (validatedPath ?? {}) as Record<string, unknown>,
624
662
  search: querySerializer(query, requestConfig.styles?.query),
625
663
  pathSerializer,
626
664
  pathStyles: requestConfig.styles?.path,
@@ -681,7 +719,7 @@ async function settleResult<TRequest, TResponse>({
681
719
  const data = await runValidator({
682
720
  validator: validator?.response,
683
721
  value: decoded,
684
- context: { direction: 'response', ...validationContext },
722
+ context: { direction: 'response', source: 'body', ...validationContext },
685
723
  onValidationError,
686
724
  })
687
725
  return { status: result.status, data, error: undefined, contentType, request: result.request, response: result.response }
@@ -690,7 +728,7 @@ async function settleResult<TRequest, TResponse>({
690
728
  const error = await runValidator({
691
729
  validator: validator?.error,
692
730
  value: decoded,
693
- context: { direction: 'error', ...validationContext },
731
+ context: { direction: 'error', source: 'body', ...validationContext },
694
732
  onValidationError,
695
733
  })
696
734
  if (throwOnError) {
@@ -52,3 +52,58 @@ export async function validateStandardSchema<TOutput>(schema: StandardSchemaVali
52
52
  }
53
53
  return (result as { value: TOutput }).value
54
54
  }
55
+
56
+ /**
57
+ * Wraps an object schema so its keys match case-insensitively.
58
+ * Keys the schema does not declare pass through untouched.
59
+ * The declared keys are validated with `schema` under their declared names.
60
+ * Every key, and every issue path, keeps the casing the caller used.
61
+ *
62
+ * @param schema Standard Schema-compatible object schema.
63
+ * @param entries The record of keys the passed object schema validates.
64
+ * @example
65
+ * ```ts
66
+ * validator: { headers: toHeadersStandardSchema(putEventHeadersSchema, putEventHeadersSchema.shape) }
67
+ * ```
68
+ */
69
+ export function toHeadersStandardSchema(schema: StandardSchemaValidator, entries: Record<string, unknown>): StandardSchemaValidator {
70
+ const declared = new Map(Object.keys(entries).map((name) => [name.toLowerCase(), name]))
71
+
72
+ function validate(value: unknown): StandardSchemaResult<unknown> | Promise<StandardSchemaResult<unknown>> {
73
+ if (typeof value !== 'object' || value === null) {
74
+ return { issues: [{ message: 'Expected an object' }] }
75
+ }
76
+
77
+ const originalKeys = new Map<string, string>()
78
+ const declaredValues: Record<string, unknown> = {}
79
+ const undeclaredValues: Record<string, unknown> = {}
80
+ for (const [key, entry] of Object.entries(value)) {
81
+ const name = declared.get(key.toLowerCase())
82
+ if (name === undefined) {
83
+ undeclaredValues[key] = entry
84
+ continue
85
+ }
86
+ originalKeys.set(name, key)
87
+ declaredValues[name] = entry
88
+ }
89
+
90
+ const toOriginal = (key: string) => originalKeys.get(key) ?? key
91
+ const settle = (result: StandardSchemaResult<unknown>): StandardSchemaResult<unknown> => {
92
+ if (result.issues) {
93
+ return {
94
+ issues: result.issues.map((issue): StandardSchemaIssue => ({
95
+ ...issue,
96
+ path: issue.path?.map((segment, index) => (index === 0 && typeof segment === 'string' ? toOriginal(segment) : segment)),
97
+ })),
98
+ }
99
+ }
100
+ const validated = Object.entries((result.value ?? {}) as Record<string, unknown>).map(([key, entry]) => [toOriginal(key), entry])
101
+ return { value: { ...undeclaredValues, ...Object.fromEntries(validated) } }
102
+ }
103
+
104
+ const result = schema['~standard'].validate(declaredValues)
105
+ return result instanceof Promise ? result.then(settle) : settle(result)
106
+ }
107
+
108
+ return { '~standard': { validate } }
109
+ }