@kubb/plugin-client 5.12.0 → 6.0.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.
Files changed (72) hide show
  1. package/README.md +1 -1
  2. package/dist/client-C-0-puI2.d.ts +554 -0
  3. package/dist/index.cjs +1377 -784
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.cts +117 -78
  6. package/dist/index.d.ts +117 -78
  7. package/dist/index.js +1375 -786
  8. package/dist/index.js.map +1 -1
  9. package/dist/templates/client.d.ts +3 -2
  10. package/dist/templates/core.d.ts +3 -3
  11. package/dist/templates/mediaTypes/formData.d.ts +5 -0
  12. package/dist/templates/mediaTypes/urlencoded.d.ts +5 -0
  13. package/dist/templates/mediaTypes.d.ts +2 -0
  14. package/dist/templates/serializers/cookies.d.ts +5 -0
  15. package/dist/templates/serializers/headers.d.ts +5 -0
  16. package/dist/templates/serializers/path.d.ts +5 -0
  17. package/dist/templates/serializers/pathStyles.d.ts +5 -0
  18. package/dist/templates/serializers/query.d.ts +5 -0
  19. package/dist/templates/serializers/queryStyles.d.ts +14 -0
  20. package/dist/templates/serializers.d.ts +118 -2
  21. package/dist/templates/sse.d.ts +20 -113
  22. package/dist/templates/standardSchema.d.ts +81 -2
  23. package/docs/guides/authentication.md +12 -2
  24. package/docs/guides/calling-operations.md +8 -6
  25. package/docs/guides/migrate-to-v6.md +139 -0
  26. package/docs/guides/validate-requests-and-responses.md +13 -8
  27. package/docs/guides/write-your-client.md +118 -12
  28. package/docs/options.md +5 -3
  29. package/docs/overview.md +3 -1
  30. package/kubb-extension.json +21 -3
  31. package/package.json +6 -5
  32. package/src/builders/callConfig.ts +80 -0
  33. package/src/builders/contentType.ts +35 -0
  34. package/src/builders/generics.ts +29 -0
  35. package/src/builders/operationBody.ts +43 -0
  36. package/src/builders/operationData.ts +64 -0
  37. package/src/builders/returnStatement.ts +103 -0
  38. package/src/builders/security.ts +125 -0
  39. package/src/builders/signature.ts +71 -0
  40. package/src/builders/styles.ts +94 -0
  41. package/src/builders/validator.ts +84 -0
  42. package/src/builders/validatorOptions.ts +53 -0
  43. package/src/clientTypes.ts +195 -0
  44. package/src/components/ClientRuntime.tsx +97 -0
  45. package/src/components/Operation.tsx +72 -0
  46. package/src/components/SdkClient.tsx +100 -0
  47. package/src/components/SdkFacade.tsx +35 -0
  48. package/src/generators/clientGenerator.tsx +91 -6
  49. package/src/generators/sdkGenerator.tsx +208 -0
  50. package/src/index.ts +3 -1
  51. package/src/macros.ts +9 -0
  52. package/src/plugin.ts +7 -8
  53. package/src/resolver.ts +28 -0
  54. package/src/setup.ts +90 -0
  55. package/src/types.ts +4 -2
  56. package/templates/client.ts +2 -1
  57. package/templates/core.ts +735 -286
  58. package/templates/mediaTypes/formData.ts +59 -0
  59. package/templates/mediaTypes/urlencoded.ts +33 -0
  60. package/templates/mediaTypes.ts +147 -0
  61. package/templates/serializers/cookies.ts +58 -0
  62. package/templates/serializers/headers.ts +35 -0
  63. package/templates/serializers/path.ts +19 -0
  64. package/templates/serializers/pathStyles.ts +27 -0
  65. package/templates/serializers/query.ts +21 -0
  66. package/templates/serializers/queryStyles.ts +107 -0
  67. package/templates/serializers.ts +48 -364
  68. package/templates/sse.ts +87 -178
  69. package/templates/standardSchema.ts +16 -37
  70. package/dist/client-BxO6Dygu.d.ts +0 -355
  71. package/dist/serializers-Ds8zZwOO.d.ts +0 -190
  72. package/dist/standardSchema-BShJWz2i.d.ts +0 -104
@@ -1,2 +1,3 @@
1
- import { A as SuccessOf, S as RequestResult, n as NativeResponse, p as DataShape, t as NativeRequest, y as Options } from "../client-BxO6Dygu.js";
2
- export { type DataShape, NativeRequest, NativeResponse, type Options, type RequestResult, type SuccessOf };
1
+ import { $ as createClientCore, A as ResultByStatus, B as SuccessVariant, C as RequestResult, D as ResponseErrorConfig, E as ResponseError, F as StreamResult, G as Unwrappable, H as Transport, I as StreamResultWithHeaders, J as UnwrappedResultWithHeaders, K as Unwrapped, L as SuccessOf, M as SecurityRequirement, N as ServerSentEvent, O as ResponseErrorOf, P as StreamOptions, Q as Validator, R as SuccessResultUnion, S as RequestCredentials, T as ResolvedRequest, U as TransportResult, V as ToStatusNumber, W as TypedEvent, X as UnwrappedStreamResultWithHeaders, Y as UnwrappedStreamResult, Z as UrlConfig, _ as InterceptorStack, a as AuthResolver, at as resolveThrowOnError, b as ParseAs, c as ClientInstance, ct as withUnwrap, d as DataShape, dt as MediaTypes, et as createInterceptorStack, f as DecodedResponse, ft as defaultMediaTypes, g as InterceptorFn, h as EventStreamOptions, ht as resolveMediaType, i as Auth, it as resolveAuth, j as ResultUnion, k as ResponseHeaders, l as ContentType, lt as MediaType, m as ErrorOf, mt as parseJson, n as NativeRequest, nt as getHeader, o as AuthToken, ot as toRequestInit, p as EmptyErrorBody, pt as isEncodedBody, q as UnwrappedResult, r as NativeResponse, rt as isResponseError, s as ClientConfig, st as unwrapResult, t as NativeOptions, tt as createLazyClient, u as DataOf, ut as MediaTypeContext, v as Interceptors, w as RequestResultWithHeaders, x as RequestConfig, y as Options, z as SuccessStatusCode } from "../client-C-0-puI2.js";
2
+ import { ValidateOption, ValidationErrorContext, ValidationErrorHandler } from "./standardSchema.js";
3
+ export { type Auth, type AuthResolver, type AuthToken, type ClientConfig, type ClientInstance, type ContentType, type DataOf, type DataShape, type DecodedResponse, type EmptyErrorBody, type ErrorOf, type EventStreamOptions, type InterceptorFn, type InterceptorStack, type Interceptors, type MediaType, type MediaTypeContext, type MediaTypes, NativeOptions, NativeRequest, NativeResponse, type Options, type ParseAs, type RequestConfig, type RequestCredentials, type RequestResult, type RequestResultWithHeaders, type ResolvedRequest, type ResponseError, type ResponseErrorConfig, type ResponseErrorOf, type ResponseHeaders, type ResultByStatus, type ResultUnion, type SecurityRequirement, type ServerSentEvent, type StreamOptions, type StreamResult, type StreamResultWithHeaders, type SuccessOf, type SuccessResultUnion, type SuccessStatusCode, type SuccessVariant, type ToStatusNumber, type Transport, type TransportResult, type TypedEvent, type Unwrappable, type Unwrapped, type UnwrappedResult, type UnwrappedResultWithHeaders, type UnwrappedStreamResult, type UnwrappedStreamResultWithHeaders, type UrlConfig, type ValidateOption, type ValidationErrorContext, type ValidationErrorHandler, type Validator, type createClientCore, type createInterceptorStack, type createLazyClient, type defaultMediaTypes, type getHeader, type isEncodedBody, type isResponseError, type parseJson, type resolveAuth, type resolveMediaType, type resolveThrowOnError, type toRequestInit, type unwrapResult, type withUnwrap };
@@ -1,3 +1,3 @@
1
- import { a as ValidateOption, o as ValidationErrorContext, s as ValidationErrorHandler } from "../standardSchema-BShJWz2i.js";
2
- import { A as SuccessOf, B as Validator, C as ResolvedRequest, D as ResponseTypeMap, E as ResponseType, F as Transport, G as resolveAuth, H as createInterceptorStack, I as TransportResult, J as withUnwrap, K as resolveResponseType, L as Unwrappable, M as SuccessStatusCode, N as SuccessVariant, O as ResultByStatus, P as ToStatusNumber, R as UnwrappedResult, S as RequestResult, T as ResponseErrorConfig, U as getResponseContentType, V as createClientCore, W as isStreamed, _ as InterceptorStack, a as AuthToken, b as RequestConfig, c as ClientInstance, d as ContentType, f as DataOf, g as InterceptorFn, h as ErrorOf, i as AuthResolver, j as SuccessResultUnion, k as ResultUnion, l as Codec, m as Deserializer, o as CallResult, p as DataShape, q as unwrapResult, r as Auth, s as ClientConfig, u as ContentBodySerializer, v as Interceptors, w as ResponseError, x as RequestCredentials, y as Options, z as UrlConfig } from "../client-BxO6Dygu.js";
3
- export { Auth, AuthResolver, AuthToken, CallResult, ClientConfig, ClientInstance, Codec, ContentBodySerializer, ContentType, DataOf, DataShape, Deserializer, ErrorOf, InterceptorFn, InterceptorStack, Interceptors, Options, RequestConfig, RequestCredentials, RequestResult, ResolvedRequest, ResponseError, ResponseErrorConfig, ResponseType, ResponseTypeMap, ResultByStatus, ResultUnion, SuccessOf, SuccessResultUnion, SuccessStatusCode, SuccessVariant, ToStatusNumber, Transport, TransportResult, Unwrappable, UnwrappedResult, UrlConfig, type ValidateOption, type ValidationErrorContext, type ValidationErrorHandler, Validator, createClientCore, createInterceptorStack, getResponseContentType, isStreamed, resolveAuth, resolveResponseType, unwrapResult, withUnwrap };
1
+ import { $ as createClientCore, A as ResultByStatus, B as SuccessVariant, C as RequestResult, D as ResponseErrorConfig, E as ResponseError, F as StreamResult, G as Unwrappable, H as Transport, I as StreamResultWithHeaders, J as UnwrappedResultWithHeaders, K as Unwrapped, L as SuccessOf, M as SecurityRequirement, N as ServerSentEvent, O as ResponseErrorOf, P as StreamOptions, Q as Validator, R as SuccessResultUnion, S as RequestCredentials, T as ResolvedRequest, U as TransportResult, V as ToStatusNumber, W as TypedEvent, X as UnwrappedStreamResultWithHeaders, Y as UnwrappedStreamResult, Z as UrlConfig, _ as InterceptorStack, a as AuthResolver, at as resolveThrowOnError, b as ParseAs, c as ClientInstance, ct as withUnwrap, d as DataShape, dt as MediaTypes, et as createInterceptorStack, f as DecodedResponse, ft as defaultMediaTypes, g as InterceptorFn, h as EventStreamOptions, ht as resolveMediaType, i as Auth, it as resolveAuth, j as ResultUnion, k as ResponseHeaders, l as ContentType, lt as MediaType, m as ErrorOf, mt as parseJson, nt as getHeader, o as AuthToken, ot as toRequestInit, p as EmptyErrorBody, pt as isEncodedBody, q as UnwrappedResult, rt as isResponseError, s as ClientConfig, st as unwrapResult, tt as createLazyClient, u as DataOf, ut as MediaTypeContext, v as Interceptors, w as RequestResultWithHeaders, x as RequestConfig, y as Options, z as SuccessStatusCode } from "../client-C-0-puI2.js";
2
+ import { ValidateOption, ValidationErrorContext, ValidationErrorHandler } from "./standardSchema.js";
3
+ export { Auth, AuthResolver, AuthToken, ClientConfig, ClientInstance, ContentType, DataOf, DataShape, DecodedResponse, EmptyErrorBody, ErrorOf, EventStreamOptions, InterceptorFn, InterceptorStack, Interceptors, MediaType, MediaTypeContext, MediaTypes, Options, ParseAs, RequestConfig, RequestCredentials, RequestResult, RequestResultWithHeaders, ResolvedRequest, ResponseError, ResponseErrorConfig, ResponseErrorOf, ResponseHeaders, ResultByStatus, ResultUnion, SecurityRequirement, ServerSentEvent, StreamOptions, StreamResult, StreamResultWithHeaders, SuccessOf, SuccessResultUnion, SuccessStatusCode, SuccessVariant, ToStatusNumber, Transport, TransportResult, TypedEvent, Unwrappable, Unwrapped, UnwrappedResult, UnwrappedResultWithHeaders, UnwrappedStreamResult, UnwrappedStreamResultWithHeaders, UrlConfig, type ValidateOption, type ValidationErrorContext, type ValidationErrorHandler, Validator, createClientCore, createInterceptorStack, createLazyClient, defaultMediaTypes, getHeader, isEncodedBody, isResponseError, parseJson, resolveAuth, resolveMediaType, resolveThrowOnError, toRequestInit, unwrapResult, withUnwrap };
@@ -0,0 +1,5 @@
1
+ import { lt as MediaType } from "../../client-C-0-puI2.js";
2
+ /**
3
+ * The `multipart/form-data` handler, which follows `config.styles.body`.
4
+ */
5
+ export declare const multipartFormData: MediaType;
@@ -0,0 +1,5 @@
1
+ import { lt as MediaType } from "../../client-C-0-puI2.js";
2
+ /**
3
+ * The `application/x-www-form-urlencoded` handler, which follows `config.styles.body`.
4
+ */
5
+ export declare const urlencoded: MediaType;
@@ -0,0 +1,2 @@
1
+ import { dt as MediaTypes, ft as defaultMediaTypes, ht as resolveMediaType, lt as MediaType, mt as parseJson, pt as isEncodedBody, ut as MediaTypeContext } from "../client-C-0-puI2.js";
2
+ export { MediaType, MediaTypeContext, MediaTypes, defaultMediaTypes, isEncodedBody, parseJson, resolveMediaType };
@@ -0,0 +1,5 @@
1
+ import { CookieSerializer } from "../serializers.js";
2
+ /**
3
+ * Joins cookie parameters into a `Cookie` header value with the OpenAPI `form` style, or the `cookie` style when a parameter sets it.
4
+ */
5
+ export declare const serializeCookies: CookieSerializer;
@@ -0,0 +1,5 @@
1
+ import { HeaderSerializer } from "../serializers.js";
2
+ /**
3
+ * Serializes array and object headers with the OpenAPI `simple` style.
4
+ */
5
+ export declare const serializeHeaders: HeaderSerializer;
@@ -0,0 +1,5 @@
1
+ import { PathSerializer } from "../serializers.js";
2
+ /**
3
+ * The path serializer for the `simple` style, which `serializeStyledPath` also uses.
4
+ */
5
+ export declare const serializePath: PathSerializer;
@@ -0,0 +1,5 @@
1
+ import { PathSerializer } from "../serializers.js";
2
+ /**
3
+ * The path serializer for the OpenAPI `label` and `matrix` styles. A `simple` parameter uses `serializePath`.
4
+ */
5
+ export declare const serializeStyledPath: PathSerializer;
@@ -0,0 +1,5 @@
1
+ import { QuerySerializer } from "../serializers.js";
2
+ /**
3
+ * The query serializer for a spec without styled query parameters: arrays repeat their key, objects use `form` with explode.
4
+ */
5
+ export declare const serializeQuery: QuerySerializer;
@@ -0,0 +1,14 @@
1
+ import { QueryParamStyle, QuerySerializer } from "../serializers.js";
2
+ /**
3
+ * One query parameter or form field with its OpenAPI style, as encoded pairs.
4
+ */
5
+ export declare function serializeStyledQueryParam({ key, value, options }: {
6
+ key: string;
7
+ value: unknown;
8
+ options: QueryParamStyle;
9
+ }): Array<string>;
10
+ /**
11
+ * The query serializer for a spec with styled query parameters: an OpenAPI style, `allowReserved` or a JSON content
12
+ * type. Without a style entry, arrays repeat their key and objects use `form` with explode.
13
+ */
14
+ export declare const serializeStyledQuery: QuerySerializer;
@@ -1,2 +1,118 @@
1
- import { C as defaultQuerySerializer, E as serializeCookies, S as defaultPathSerializer, T as isJsonMediaType, _ as Serializers, a as HeaderValue, b as baseContentType, c as ParamContentType, d as PathStyle, f as QueryParamStyle, g as SerializationStyle, h as RequestBody, i as HeaderParamStyle, l as PathParamStyle, m as QueryStyle, n as BodySerializer, o as HeadersInit, p as QuerySerializer, r as CookieParamStyle, s as HttpMethod, t as BodyEncoding, u as PathSerializer, v as Styles, w as isDefaultJsonBody, x as defaultBodySerializer, y as applyHeaderStyles } from "../serializers-Ds8zZwOO.js";
2
- export { BodyEncoding, BodySerializer, CookieParamStyle, HeaderParamStyle, HeaderValue, HeadersInit, HttpMethod, ParamContentType, PathParamStyle, PathSerializer, PathStyle, QueryParamStyle, QuerySerializer, QueryStyle, RequestBody, SerializationStyle, Serializers, Styles, applyHeaderStyles, baseContentType, defaultBodySerializer, defaultPathSerializer, defaultQuerySerializer, isDefaultJsonBody, isJsonMediaType, serializeCookies };
1
+ export type HeaderValue = string | number | boolean | null | undefined | object;
2
+ export type HeadersInit = Array<[string, HeaderValue]> | Record<string, HeaderValue>;
3
+ /**
4
+ * A body `fetch` accepts, read from `RequestInit` so a project without the `dom` lib still has it.
5
+ */
6
+ export type RequestBody = NonNullable<RequestInit['body']>;
7
+ export type HttpMethod = 'GET' | 'PUT' | 'PATCH' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'QUERY' | 'TRACE' | (string & {});
8
+ /**
9
+ * The OpenAPI query style. `form` is the default.
10
+ */
11
+ export type QueryStyle = 'form' | 'spaceDelimited' | 'pipeDelimited' | 'deepObject';
12
+ export type SerializationStyle<TStyle = string> = {
13
+ style?: TStyle;
14
+ explode?: boolean;
15
+ allowReserved?: boolean;
16
+ };
17
+ /**
18
+ * The media type of a parameter described with `content`. JSON sends one JSON-encoded value.
19
+ */
20
+ export type ParamContentType = {
21
+ contentType?: string;
22
+ };
23
+ /**
24
+ * `querystring` marks an OpenAPI 3.2 `in: querystring` parameter, sent as the whole query string.
25
+ */
26
+ export type QueryParamStyle = SerializationStyle<QueryStyle> & ParamContentType & {
27
+ querystring?: boolean;
28
+ };
29
+ /**
30
+ * Turns the query object into a search string, following each parameter's OpenAPI style when given.
31
+ */
32
+ export type QuerySerializer = (params: Record<string, unknown>, options?: Record<string, QueryParamStyle>) => string;
33
+ /**
34
+ * `cookie` is the OpenAPI 3.2 style that sends values as they are, without percent-encoding (RFC 6265). `form` is the default.
35
+ */
36
+ export type CookieParamStyle = ParamContentType & {
37
+ style?: 'form' | 'cookie';
38
+ explode?: boolean;
39
+ };
40
+ export type HeaderParamStyle = ParamContentType & {
41
+ explode?: boolean;
42
+ };
43
+ /**
44
+ * The OpenAPI `encoding` of one form body property. `contentType` sets a multipart part's media type.
45
+ */
46
+ export type BodyEncoding = SerializationStyle<QueryStyle> & {
47
+ contentType?: string;
48
+ };
49
+ /**
50
+ * The OpenAPI path style. `simple` is the default.
51
+ */
52
+ export type PathStyle = 'simple' | 'label' | 'matrix';
53
+ export type PathParamStyle = SerializationStyle<PathStyle>;
54
+ /**
55
+ * Joins the cookie parameters of a call into a `Cookie` header value.
56
+ */
57
+ export type CookieSerializer = (cookies: Record<string, unknown>, styles?: Record<string, CookieParamStyle>) => string;
58
+ /**
59
+ * Serializes the header parameters of a call that are arrays or objects.
60
+ */
61
+ export type HeaderSerializer = (headers: HeadersInit | undefined, styles?: Record<string, HeaderParamStyle>) => HeadersInit | undefined;
62
+ /**
63
+ * Turns one path parameter into its URL segment.
64
+ */
65
+ export type PathSerializer = (args: {
66
+ name: string;
67
+ value: unknown;
68
+ options?: PathParamStyle | undefined;
69
+ }) => string;
70
+ /**
71
+ * Parameter serializers, set per client or per call. `.kubb/client.ts` registers the ones the spec needs. Bodies are
72
+ * encoded by `mediaTypes`.
73
+ */
74
+ export type Serializers = {
75
+ query?: QuerySerializer;
76
+ path?: PathSerializer;
77
+ /**
78
+ * Turns array and object header values into strings. Without one, such a value is sent as JSON.
79
+ */
80
+ header?: HeaderSerializer;
81
+ /**
82
+ * Sends the `cookies` of a call. Kubb registers `serializeCookies` when the spec has a cookie parameter.
83
+ */
84
+ cookie?: CookieSerializer;
85
+ };
86
+ /**
87
+ * The OpenAPI styles of a generated call's parameters, by location and name. `body` holds the form `encoding`.
88
+ */
89
+ export type Styles = {
90
+ path?: Record<string, PathParamStyle>;
91
+ query?: Record<string, QueryParamStyle>;
92
+ header?: Record<string, HeaderParamStyle>;
93
+ cookie?: Record<string, CookieParamStyle>;
94
+ body?: Record<string, BodyEncoding>;
95
+ };
96
+ /**
97
+ * Sends a `bigint` as a JSON number, and throws past the safe-integer range instead of losing precision.
98
+ */
99
+ export declare function jsonReplacer(_key: string, value: unknown): unknown;
100
+ /**
101
+ * A `Content-Type` without its parameters, in lower case.
102
+ */
103
+ export declare function baseContentType(value: string | null | undefined): string | undefined;
104
+ /**
105
+ * Whether a media type is JSON, such as `application/json` or `application/problem+json`.
106
+ */
107
+ export declare function isJsonMediaType(contentType: string | null | undefined): boolean;
108
+ export declare function notNullish(value: unknown): boolean;
109
+ /**
110
+ * Renders a parameter value as a string. A `Date` becomes ISO-8601, so it does not depend on the locale.
111
+ */
112
+ export declare function toValue(value: unknown): string;
113
+ export declare function encodeComponent(value: unknown): string;
114
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
115
+ /**
116
+ * One parameter as form pairs, with an array repeating its key and an object as `key[prop]`.
117
+ */
118
+ export declare function serializeDefaultQueryParam(key: string, value: unknown): Array<string>;
@@ -1,124 +1,31 @@
1
- import { a as ValidateOption, i as StandardSchemaValidator, s as ValidationErrorHandler } from "../standardSchema-BShJWz2i.js";
2
- import { A as SuccessOf, S as RequestResult, n as NativeResponse, p as DataShape, t as NativeRequest, y as Options } from "../client-BxO6Dygu.js";
1
+ import { N as ServerSentEvent, dt as MediaTypes, h as EventStreamOptions, lt as MediaType } from "../client-C-0-puI2.js";
2
+ type Cursor = {
3
+ lastEventId: string;
4
+ };
5
+ type EventStreamInput = ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>;
3
6
  /**
4
- * One decoded Server-Sent Event. `data` is parsed as JSON when valid and kept as the raw string otherwise,
5
- * `event` is `message` when the server sent no `event` field, and `id` is the last event ID the stream has set.
7
+ * Parses a `text/event-stream` body into events, as the WHATWG spec does. Break the loop to cancel the stream.
6
8
  */
7
- export type ServerSentEvent<TData = unknown> = {
8
- data: TData;
9
- event: string;
10
- id?: string;
11
- retry?: number;
12
- };
13
- /** An event the document types by name: the member's own `event` and `data`, plus the `id` and `retry` any event may carry. */
14
- export type TypedEvent<TEvent> = TEvent & Pick<ServerSentEvent, 'id' | 'retry'>;
15
- /** Per-call options of a streamed operation, passed next to its request params. */
16
- export type EventStreamOptions = {
17
- /**
18
- * The largest number of characters, line breaks included, one event may hold before the blank line that ends it.
19
- * A larger event throws a `RangeError` and cancels the stream. Set `Infinity` to turn the limit off.
20
- * @default 16777216
21
- */
22
- maxEventSize?: number;
23
- /**
24
- * Ends the stream when an event's raw `data` equals this value, such as `[DONE]`.
25
- */
26
- terminator?: string;
27
- /**
28
- * Maps each event before validation.
29
- */
30
- transform?: (event: ServerSentEvent) => ServerSentEvent;
31
- };
32
- /** The options of a streamed operation: the call's `Options` with the per-call stream options, as `Options` is for a regular call. */
33
- export type StreamOptions<TData extends DataShape, ThrowOnError extends boolean = true> = Options<TData, ThrowOnError> & EventStreamOptions;
9
+ export declare function parseEventStream<TData = unknown>(input: EventStreamInput | (Pick<EventStreamOptions, 'maxEventSize' | 'terminator' | 'rawData'> & {
10
+ stream: EventStreamInput;
11
+ cursor?: Cursor | undefined;
12
+ })): AsyncGenerator<ServerSentEvent<TData>>;
34
13
  /**
35
- * The validation settings a call or its client may set.
14
+ * Parses a JSON Lines body into one value per line. Break the loop to cancel the stream.
36
15
  */
37
- type ValidationSettings = {
38
- validate?: ValidateOption;
39
- onValidationError?: ValidationErrorHandler;
40
- };
16
+ export declare function parseJsonLines<TData = unknown>({ stream, maxEventSize, terminator }: Pick<EventStreamOptions, 'maxEventSize' | 'terminator'> & {
17
+ stream: EventStreamInput;
18
+ }): AsyncGenerator<TData>;
41
19
  /**
42
- * What the client resolves a streamed call to: the body as a stream or a decoded value, its content type, and the native response.
20
+ * The `text/event-stream` handler. A whole body, such as an error, is read as text.
43
21
  */
44
- export type EventStreamCall<TResponse> = {
45
- data: unknown;
46
- error?: unknown;
47
- status?: number;
48
- contentType?: string;
49
- request?: NativeRequest;
50
- response: TResponse;
51
- };
52
- /** The payload wrapped in `ServerSentEvent`, or the item itself when the document types it as a whole event. */
53
- type StreamEvent<TData> = TData extends {
54
- event: string;
55
- } ? TData : ServerSentEvent<TData>;
56
- /** Parsed events with the fields a `RequestResult` carries. `TData` is the payload, or the typed event. Iterating the result reads `stream`. */
57
- export type EventStreamResult<TData = unknown, TResponse = NativeResponse> = AsyncIterable<StreamEvent<TData>> & {
58
- stream: AsyncGenerator<StreamEvent<TData>>;
59
- /** The same events as `stream` on a 2xx response, so `.unwrap()` and `returnType: 'data'` return them. */
60
- data: AsyncGenerator<StreamEvent<TData>> | undefined;
61
- status: number | undefined;
62
- /** The error body of a failed call with `throwOnError: false`, whose `stream` then yields nothing. */
63
- error: unknown;
64
- contentType: string | undefined;
65
- request: NativeRequest | undefined;
66
- response: TResponse;
67
- /**
68
- * The last event ID the server sent, to resume from with a `Last-Event-ID` header on a new call. Empty until the server sends `id`.
69
- */
70
- readonly lastEventId: string;
71
- };
72
- type StreamParts<TData> = AsyncIterable<StreamEvent<TData>> & {
73
- stream: AsyncGenerator<StreamEvent<TData>>;
74
- readonly lastEventId: string;
75
- };
76
- type WithEvents<TResult, TData> = TResult extends {
77
- error: undefined;
78
- } ? Omit<TResult, 'data'> & {
79
- data: AsyncGenerator<StreamEvent<TData>>;
80
- } : TResult;
81
- /** A stream call's result, as `RequestResult` is a regular call's: `status` narrows `error`, and the events are its `data`. Branching on `ThrowOnError` lets a generated call cast to it. */
82
- export type StreamResult<TResponses, ThrowOnError extends boolean = true, TData = SuccessOf<TResponses>> = ThrowOnError extends true ? WithEvents<RequestResult<TResponses, true>, TData> & StreamParts<TData> : WithEvents<RequestResult<TResponses, false>, TData> & StreamParts<TData>;
83
- /** What a stream operation returns with `returnType: 'data'`, as `UnwrappedResult` is for a regular call. */
84
- export type UnwrappedStreamResult<TResponses, ThrowOnError extends boolean = true, TData = SuccessOf<TResponses>> = ThrowOnError extends true ? AsyncGenerator<StreamEvent<TData>> : StreamResult<TResponses, false, TData>;
85
- /** The last event ID, shared with the result so it can be read after the loop. */
86
- type Cursor = {
87
- lastEventId: string;
88
- };
22
+ export declare const eventStream: MediaType;
89
23
  /**
90
- * Parses a `text/event-stream` body as the WHATWG event stream specification does: an event is dispatched at its blank line
91
- * when it holds `data`, `event` defaults to `message`, `id` carries across events until an empty `id` resets it, `retry` needs
92
- * all digits, and an unfinished event at the end is dropped. `data` is parsed as JSON when it is valid and kept as text
93
- * otherwise. Consume with `for await`, and break the loop to cancel the stream.
24
+ * The JSON Lines handler. A whole body, such as an error, is read as text.
94
25
  */
95
- type EventStreamInput = ReadableStream<Uint8Array> | AsyncIterable<Uint8Array>;
96
- export declare function parseEventStream<TData = unknown>(input: EventStreamInput | (Pick<EventStreamOptions, 'maxEventSize' | 'terminator'> & {
97
- stream: EventStreamInput;
98
- cursor?: Cursor;
99
- })): AsyncGenerator<ServerSentEvent<TData>>;
26
+ export declare const jsonLines: MediaType;
100
27
  /**
101
- * Reads a call as typed Server-Sent Events, transformed and validated one by one, until the terminator or the end of the
102
- * stream. A successful call whose body is not a stream, such as a decoded JSON answer, throws a `TypeError` with the body
103
- * as its `cause`. A dropped connection ends the loop with the transport's error; `lastEventId` on the result is the ID
104
- * to resume from.
28
+ * The Server-Sent Events and JSON Lines handlers, registered when the document streams.
105
29
  */
106
- export declare function toEventStream<TData = unknown, TResponse = NativeResponse>(call: Promise<EventStreamCall<TResponse>>, { client, config: options, ...meta }?: {
107
- /**
108
- * The client the call went through, for the validation settings a call does not set itself.
109
- */
110
- client?: {
111
- getConfig: () => ValidationSettings;
112
- };
113
- config?: EventStreamOptions & ValidationSettings;
114
- /**
115
- * `event` when the document types each event with its own `event` and `data`, or `data` when it types only the payload.
116
- * @default 'data'
117
- */
118
- shape?: 'event' | 'data';
119
- /**
120
- * Validates each event (`shape: 'event'`) or its `data` (`shape: 'data'`), after `transform`.
121
- */
122
- validator?: StandardSchemaValidator;
123
- }): Promise<EventStreamResult<TData, TResponse>>;
30
+ export declare const streamMediaTypes: MediaTypes;
124
31
  export {};
@@ -1,2 +1,81 @@
1
- import { a as ValidateOption, c as isValidationEnabled, d as validateStandardSchema, i as StandardSchemaValidator, l as runValidator, n as StandardSchemaIssue, o as ValidationErrorContext, r as StandardSchemaResult, s as ValidationErrorHandler, t as ParseError, u as toHeadersStandardSchema } from "../standardSchema-BShJWz2i.js";
2
- export { ParseError, StandardSchemaIssue, StandardSchemaResult, StandardSchemaValidator, ValidateOption, ValidationErrorContext, ValidationErrorHandler, isValidationEnabled, runValidator, toHeadersStandardSchema, validateStandardSchema };
1
+ /**
2
+ * A Standard Schema validator, such as a Zod, Valibot, or ArkType schema.
3
+ */
4
+ export type StandardSchemaValidator<TOutput = unknown> = {
5
+ readonly '~standard': {
6
+ validate(value: unknown): StandardSchemaResult<TOutput> | Promise<StandardSchemaResult<TOutput>>;
7
+ };
8
+ };
9
+ export type StandardSchemaResult<TOutput> = {
10
+ readonly value: TOutput;
11
+ readonly issues?: undefined;
12
+ } | {
13
+ readonly issues: ReadonlyArray<StandardSchemaIssue>;
14
+ };
15
+ export type StandardSchemaIssue = {
16
+ readonly message?: string;
17
+ readonly path?: ReadonlyArray<PropertyKey | {
18
+ readonly key: PropertyKey;
19
+ }> | undefined;
20
+ };
21
+ /**
22
+ * Thrown when validation fails, with the schema's `issues`.
23
+ */
24
+ export declare class ParseError extends Error {
25
+ readonly issues: ReadonlyArray<StandardSchemaIssue>;
26
+ readonly cause?: unknown;
27
+ constructor({ issues, message, cause }: {
28
+ issues: ReadonlyArray<StandardSchemaIssue>;
29
+ message?: string;
30
+ cause?: unknown;
31
+ });
32
+ }
33
+ /**
34
+ * Returns the parsed value, or throws a `ParseError` with the schema's `issues`.
35
+ */
36
+ export declare function validateStandardSchema<TOutput>(schema: StandardSchemaValidator<TOutput>, value: unknown): Promise<TOutput>;
37
+ /**
38
+ * Wraps an object schema so its keys match in any letter case. `entries` are the keys the schema declares.
39
+ *
40
+ * @example
41
+ * ```ts
42
+ * validator: { headers: toHeadersStandardSchema(putEventHeadersSchema, putEventHeadersSchema.shape) }
43
+ * ```
44
+ */
45
+ export declare function toHeadersStandardSchema(schema: StandardSchemaValidator, entries: Record<string, unknown>): StandardSchemaValidator;
46
+ /**
47
+ * Which value and request failed validation.
48
+ */
49
+ export type ValidationErrorContext = {
50
+ value: unknown;
51
+ direction: 'request' | 'response' | 'error';
52
+ source: 'body' | 'path' | 'query' | 'headers' | 'cookies';
53
+ method?: string | undefined;
54
+ url?: string | undefined;
55
+ status?: number | undefined;
56
+ };
57
+ /**
58
+ * Return `{ value }` to use instead of a failed value. Return nothing to rethrow the `ParseError`.
59
+ */
60
+ export type ValidationErrorHandler = (error: ParseError, context: ValidationErrorContext) => {
61
+ value: unknown;
62
+ } | void | Promise<{
63
+ value: unknown;
64
+ } | void>;
65
+ /**
66
+ * Turns generated validation on or off, for every direction or per direction.
67
+ * @default true
68
+ */
69
+ export type ValidateOption = boolean | {
70
+ request?: boolean;
71
+ params?: boolean;
72
+ response?: boolean;
73
+ error?: boolean;
74
+ };
75
+ export declare function isValidationEnabled(validate: ValidateOption | undefined, direction: 'request' | 'params' | 'response' | 'error'): boolean;
76
+ export declare function runValidator<T>({ validator, value, context, onValidationError }: {
77
+ validator: StandardSchemaValidator<T> | undefined;
78
+ value: T;
79
+ context: Omit<ValidationErrorContext, 'value'>;
80
+ onValidationError: ValidationErrorHandler | undefined;
81
+ }): Promise<T>;
@@ -7,7 +7,7 @@ Auth lives in your `client`. The plugin does not send credentials itself. It tel
7
7
  Each generated function passes the operation's security schemes from the spec as `security`:
8
8
 
9
9
  ```typescript
10
- request({
10
+ apiClient<GetPetByIdResponses, ThrowOnError>({
11
11
  method: 'GET',
12
12
  url: '/pet/{petId}',
13
13
  security: [{ type: 'apiKey', name: 'api_key', in: 'header' }, { type: 'oauth2' }],
@@ -15,8 +15,16 @@ request({
15
15
  })
16
16
  ```
17
17
 
18
+ Each entry is one security requirement, and meeting one is enough. A requirement that needs several schemes together, such as an API key and a session cookie, is an array, and your client sends all of them: `security: [[{ type: 'apiKey', name: 'api_key', in: 'header' }, { type: 'apiKey', name: 'sid', in: 'cookie' }]]`.
19
+
18
20
  An operation without security requirements passes no `security` field. Use that to skip auth on public endpoints.
19
21
 
22
+ An `oauth2` entry carries its `flows` with their URLs, and its `metadataUrl` when the spec sets `oauth2MetadataUrl`. An `openIdConnect` entry carries its discovery `url`. Your client can use them to run the flow, such as the OpenAPI 3.2 `deviceAuthorization` flow, and then send the token as a bearer token:
23
+
24
+ ```typescript
25
+ security: [{ type: 'oauth2', flows: { deviceAuthorization: { deviceAuthorizationUrl: 'https://auth.example.com/device', tokenUrl: 'https://auth.example.com/token' } }, scopes: ['read'] }]
26
+ ```
27
+
20
28
  ## Add a bearer token from an async source
21
29
 
22
30
  The client can `await` anything before it sends the request. The client below awaits a token function you register with `setAuth`, so the token can come from a secrets store or a refresh call:
@@ -54,7 +62,7 @@ setAuth(async () => readTokenFromSecretsStore())
54
62
 
55
63
  ## Sign requests or use several auth methods
56
64
 
57
- Read `config.security` and pick per operation, or pass a different `client` on a call. This works for request signing, such as AWS SigV4, and for services that use different credentials:
65
+ Read `config.security` and pick per operation, or pass a different `client` on a call. Both ways work for request signing, such as AWS SigV4, and for services that use different credentials:
58
66
 
59
67
  ```typescript
60
68
  import { createSignedClient } from './clients/iam'
@@ -62,4 +70,6 @@ import { createSignedClient } from './clients/iam'
62
70
  await getPetById({ path: { petId: 1 }, client: createSignedClient() })
63
71
  ```
64
72
 
73
+ The examples set [`integerType: 'number'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#integertype) on the adapter, so an `int64` id such as `petId` is a `number`. With the default it is a `bigint` and the call takes `1n`.
74
+
65
75
  A client passed on a call replaces the default for that call only.
@@ -8,20 +8,22 @@ import { addPet, getPetById } from './gen/clients'
8
8
  const created = await addPet({ body: { name: 'Odie', photoUrls: [] } })
9
9
  console.log(created.data, created.response.status)
10
10
 
11
- const pet = await getPetById({ path: { petId: 1n } })
11
+ const pet = await getPetById({ path: { petId: 1 } })
12
12
  ```
13
13
 
14
- The keys are `path`, `query`, `headers`, and `body`. Kubb types each from the spec, so a wrong key or value fails at compile time.
14
+ The examples set [`integerType: 'number'`](https://kubb.dev/extensions/kubb-labs/adapter-oas/options#integertype) on the adapter, so an `int64` id such as `petId` is a `number`. With the default it is a `bigint` and the call takes `1n`.
15
+
16
+ The keys are `path`, `query`, `headers`, `cookies`, and `body`. Kubb types each from the spec, so a wrong key or value fails at compile time.
15
17
 
16
18
  ## Errors
17
19
 
18
- `throwOnError` defaults to `true` (see [`throwOnErrorDefault`](https://kubb.dev/extensions/kubb-labs/plugin-client/options#throwonerrordefault)). What that means is up to your client. With the example client, a non-2xx status throws, and `throwOnError: false` returns the error as a value:
20
+ `throwOnError` defaults to `true` (see [`throwOnErrorDefault`](https://kubb.dev/extensions/kubb-labs/plugin-client/options#throwonerrordefault)). What that means is up to your client. With the [minimal client](https://kubb.dev/extensions/kubb-labs/plugin-client/guides/write-your-client#a-minimal-client), a non-2xx status throws, and `throwOnError: false` returns the error as a value:
19
21
 
20
22
  ```typescript
21
- const result = await getPetById({ path: { petId: 1n }, throwOnError: false })
23
+ const result = await getPetById({ path: { petId: 1 }, throwOnError: false })
22
24
 
23
25
  if (result.error === undefined) {
24
- console.log('pet', result.data.name)
26
+ console.log('pet', result.data)
25
27
  }
26
28
  if (result.error !== undefined) {
27
29
  console.log('failed', result.response.status)
@@ -33,5 +35,5 @@ if (result.error !== undefined) {
33
35
  Pass `client` to send one call through another function:
34
36
 
35
37
  ```typescript
36
- await getPetById({ path: { petId: 2n }, client: tenantClient })
38
+ await getPetById({ path: { petId: 2 }, client: tenantClient })
37
39
  ```