@kubb/plugin-fetch 5.14.0-canary.20261109T134631 → 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.
package/docs/options.md CHANGED
@@ -23,7 +23,7 @@ Pass these options to `pluginFetch()`. Shared options link to [Shared plugin opt
23
23
 
24
24
  ### baseURL
25
25
 
26
- Base URL prepended to every request. When omitted, each request uses the operation's relative path from the spec. A value with a `${...}` interpolation is emitted as a template literal in the generated client config, so `baseURL: '${process.env.API_URL}'` reads the environment variable at runtime.
26
+ Base URL prepended to every request. When omitted, each request uses the operation's relative path from the spec. A path or operation that declares its own `servers` uses that URL instead. See [Set the base URL](https://kubb.dev/extensions/kubb-labs/plugin-fetch/guides/base-url). A value with a `${...}` interpolation is emitted as a template literal in the generated client config, so `baseURL: '${process.env.API_URL}'` reads the environment variable at runtime.
27
27
 
28
28
  | | |
29
29
  | -------- | -------- |
@@ -32,7 +32,7 @@ Base URL prepended to every request. When omitted, each request uses the operati
32
32
 
33
33
  ### throwOnErrorDefault
34
34
 
35
- Set `throwOnErrorDefault: false` to return documented error responses as values by default. It sets the fallback on each generated request and the default `ThrowOnError` type parameter on functions and SDK methods. It applies to the whole plugin, so `override` cannot set it. A call that passes `throwOnError` still wins. With `throwOnError: true`, a non-2xx response throws and the return type narrows to successful responses. Query hooks always pass `throwOnError: true`.
35
+ Set `throwOnErrorDefault: false` to return documented error responses as values by default. The option sets the fallback on each generated request and the default `ThrowOnError` type parameter on functions and SDK methods. The option applies to the whole plugin, so `override` cannot set it. A call that passes `throwOnError` still wins. With `throwOnError: true`, a non-2xx response throws and the return type narrows to successful responses. Query hooks always pass `throwOnError: true`.
36
36
 
37
37
  | | |
38
38
  | -------- | --------- |
@@ -46,9 +46,11 @@ const result = await getPetById({ path: { petId: 1 } })
46
46
  if (result.status !== 200) console.error(result.status, result.error)
47
47
  ```
48
48
 
49
+ 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`.
50
+
49
51
  ### validator
50
52
 
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`.
53
+ Validates request bodies, the path, query, header, and cookie 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
54
 
53
55
  | | |
54
56
  | -------- | ------------------------------------------------------------------------- |
@@ -63,11 +65,11 @@ Default value. Does no validation and returns the response cast to the generated
63
65
  :::
64
66
 
65
67
  :::field{name="'zod'"}
66
- Validates the success response body, and the error body when a non-2xx call does not throw.
68
+ Validates the success response body, and the error body against the schema of its status.
67
69
  :::
68
70
 
69
71
  :::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.
72
+ Opts in per direction. `request` validates the request body and `params` validates the path, query, header, and cookie params before the call. `response` validates the response body after it.
71
73
  :::
72
74
 
73
75
  ::
@@ -89,9 +91,9 @@ export default defineConfig({
89
91
  })
90
92
  ```
91
93
 
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.
94
+ `params` runs each group through its generated `<operation>PathSchema`, `QuerySchema`, `HeadersSchema`, or `CookiesSchema`, 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
95
 
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.
96
+ 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. Headers the spec does not declare pass through unchanged, and declared header params match in any casing.
95
97
 
96
98
  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
99
 
@@ -107,7 +109,7 @@ Generates a class-based SDK. Each instance takes its own client config, so envir
107
109
  ::field-group
108
110
 
109
111
  :::field{name="'tag'"}
110
- Default value for `sdk.mode`. Generates one class per tag, such as `PetClient`. Set `sdk.name` to also get a root class that shares one config, used as `new PetStore(config).pet.getPetById(...)`.
112
+ Default value for `sdk.mode`. Generates one class per tag, such as `PetClient`. Set `sdk.name` to also get a root class that shares one client with every tag, used as `new PetStore(config).pet.getPetById(...)`.
111
113
  :::
112
114
 
113
115
  :::field{name="'flat'"}
@@ -125,6 +127,16 @@ const pet = new PetClient({ baseURL: 'https://petstore.swagger.io/v2' })
125
127
  const { data } = await pet.getPetById({ path: { petId: 1 } })
126
128
  ```
127
129
 
130
+ Each SDK class exposes its client as the read-only `client` field. Interceptors on the root class's `client` apply to every tag:
131
+
132
+ ```typescript
133
+ const api = new PetStore({ baseURL: 'https://petstore.swagger.io/v2' })
134
+ api.client.interceptors.request.use((request) => request)
135
+ await api.pet.getPetById({ path: { petId: 1 } })
136
+ ```
137
+
138
+ A tag class also accepts an existing client, as in `new PetClient(api.client)`.
139
+
128
140
  ### returnType
129
141
 
130
142
  Shape of the value a generated call resolves to.
@@ -138,7 +150,7 @@ Shape of the value a generated call resolves to.
138
150
  ::field-group
139
151
 
140
152
  :::field{name="'full'"}
141
- Default value. Returns `{ status, data, error, contentType, request, response }`.
153
+ Default value. Returns `{ status, data, error, contentType, headers, request, response }`. `headers` is the response's `Headers`. For an operation whose responses declare `headers`, its `get` suggests those names once `status` is narrowed, and the values stay strings.
142
154
  :::
143
155
 
144
156
  :::field{name="'data'"}
@@ -153,7 +165,7 @@ pluginFetch({ returnType: 'data' })
153
165
  const pet = await getPetById({ path: { petId: 1 } }) // Pet, not { status, data, ... }
154
166
  ```
155
167
 
156
- It applies to the functions and the SDK. The query plugins and `@kubb/plugin-mcp` read it too, including a per-operation value set through [`override`](https://kubb.dev/docs/5.x/reference/plugin-options#override). To read headers such as `ETag` under `'data'`, pass `throwOnError: false` and call `result.response.headers.get('etag')`.
168
+ `returnType` applies to the functions and the SDK. The query plugins and `@kubb/plugin-mcp` read it too, including a per-operation value set through [`override`](https://kubb.dev/docs/5.x/reference/plugin-options#override). To read headers such as `ETag` under `'data'`, pass `throwOnError: false` and call `result.response.headers.get('etag')`.
157
169
 
158
170
  ### resolver
159
171
 
package/docs/overview.md CHANGED
@@ -2,17 +2,17 @@
2
2
 
3
3
  The Fetch plugin turns each operation in your OpenAPI spec into a typed async function that sends the request with the native Fetch API. Each function takes grouped `path`, `query`, `headers`, and `body` parameters and returns a result keyed by status code.
4
4
 
5
- The query plugins (`@kubb/plugin-react-query`, `@kubb/plugin-vue-query`, and `@kubb/plugin-swr`) and `@kubb/plugin-mcp` call these functions. The plugin also copies its runtime files (`client.ts`, `serializers.ts`, and `standardSchema.ts`) to `.kubb/` in the root output folder.
5
+ The query plugins (`@kubb/plugin-react-query`, `@kubb/plugin-vue-query`, and `@kubb/plugin-swr`) and `@kubb/plugin-mcp` call these functions. The plugin also copies its runtime files to `.kubb/` in the root output folder. Import the client from `.kubb/client.ts`.
6
6
 
7
7
  ## Setup
8
8
 
9
9
  - Add `@kubb/plugin-ts` for the operation types, or `@kubb/plugin-zod` with `inferred: true`.
10
- - Add `@kubb/plugin-zod` when you set `validator`, and install `zod` v4. Without the plugin, `validator` does nothing.
10
+ - Add `@kubb/plugin-zod` when you set `validator`, and install `zod` v4. Generation fails without the plugin.
11
11
  - No HTTP client package is needed. The generated code calls the global `fetch`.
12
12
 
13
13
  ## Options worth knowing
14
14
 
15
- - `baseURL` is prepended to every request. The spec's `servers` URL is not used, so without `baseURL` you set one at runtime with `client.setConfig({ baseURL })`.
15
+ - `baseURL` is prepended to every request. The spec's top-level `servers` URL is not used, so without `baseURL` you set one at runtime with `client.setConfig({ baseURL })`. Operations with their own `servers`, on the path or the operation, call that URL instead.
16
16
  - `validator: 'zod'` validates response bodies with the schemas from `@kubb/plugin-zod`. Use `{ request: 'zod', response: 'zod' }` to also validate request bodies.
17
17
  - `throwOnErrorDefault: false` returns non-2xx responses as values instead of throwing. A single call can still pass `throwOnError`.
18
18
  - `returnType: 'data'` makes a call resolve to the success body instead of the full result. With `throwOnError: false`, the call still returns the full result.
@@ -26,12 +26,14 @@ The config below generates a Fetch client that sends every request to the Petsto
26
26
 
27
27
  ```typescript [kubb.config.ts]
28
28
  import { defineConfig } from 'kubb/config'
29
+ import { adapterOas } from '@kubb/adapter-oas'
29
30
  import { pluginTs } from '@kubb/plugin-ts'
30
31
  import { pluginFetch } from '@kubb/plugin-fetch'
31
32
 
32
33
  export default defineConfig({
33
34
  input: './petStore.yaml',
34
35
  output: { path: './src/gen' },
36
+ adapter: adapterOas({ integerType: 'number' }),
35
37
  plugins: [
36
38
  pluginTs(),
37
39
  pluginFetch({ baseURL: 'https://petstore.swagger.io/v2' }),
@@ -17,10 +17,9 @@
17
17
  "github": "stijnvanhulle"
18
18
  }
19
19
  ],
20
- "dependencies": ["plugin-ts"],
21
- "optionalDependencies": ["plugin-zod"],
20
+ "optionalDependencies": ["plugin-ts", "plugin-zod"],
22
21
  "compatibility": {
23
- "kubb": ">=5.16.0",
22
+ "kubb": ">=5.18.4",
24
23
  "node": ">=22.22"
25
24
  },
26
25
  "role": "client",
@@ -199,7 +198,7 @@
199
198
  "key": "returnType",
200
199
  "path": ["returnType"],
201
200
  "label": "Return Type",
202
- "description": "What a generated function resolves to. full is the whole result with status and error, data is only the success body when it throws, and plain is the client's own promise",
201
+ "description": "What a generated function resolves to. full is the whole result with status and error, and data is only the success body when it throws",
203
202
  "type": "select",
204
203
  "default": "full",
205
204
  "choices": [
@@ -208,9 +207,6 @@
208
207
  },
209
208
  {
210
209
  "value": "data"
211
- },
212
- {
213
- "value": "plain"
214
210
  }
215
211
  ]
216
212
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubb/plugin-fetch",
3
- "version": "5.14.0-canary.20261109T134631",
3
+ "version": "6.0.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",
@@ -39,6 +39,10 @@
39
39
  "src",
40
40
  "dist",
41
41
  "templates",
42
+ "!templates/config.ts",
43
+ "!templates/core.ts",
44
+ "!templates/serializers.ts",
45
+ "!templates/standardSchema.ts",
42
46
  "kubb-extension.json",
43
47
  "docs",
44
48
  "!/**/**.test.**",
@@ -67,8 +71,7 @@
67
71
  "./package.json": "./package.json",
68
72
  "./kubb-extension.json": "./kubb-extension.json",
69
73
  "./templates/*.ts": {
70
- "types": "./dist/templates/*.d.ts",
71
- "default": "./templates/*.ts"
74
+ "types": "./dist/templates/*.d.ts"
72
75
  },
73
76
  "./templates/*.js": {
74
77
  "types": "./dist/templates/*.d.ts"
@@ -80,15 +83,10 @@
80
83
  "registry": "https://registry.npmjs.org/"
81
84
  },
82
85
  "dependencies": {
83
- "@kubb/kit": "^5.16.0",
84
- "@kubb/plugin-client": "^5.12.0-canary.20261109T134631",
85
- "@kubb/plugin-ts": "^5.5.0-canary.20261109T134631",
86
- "@kubb/plugin-zod": "^5.9.0-canary.20261109T134631",
87
- "@kubb/renderer-jsx": "^5.16.0"
86
+ "@kubb/kit": "^5.18.8",
87
+ "@kubb/plugin-client": "^6.0.1"
88
88
  },
89
89
  "devDependencies": {
90
- "@internals/client": "0.1.0-canary.20261109T134631",
91
- "@internals/shared": "0.1.0-canary.20261109T134631",
92
90
  "typescript": "^7.0.2"
93
91
  },
94
92
  "peerDependencies": {},
package/src/index.ts CHANGED
@@ -1,3 +1,2 @@
1
- export { clientGenerator } from './generators/clientGenerator.tsx'
2
1
  export { default, pluginFetch, pluginFetchName } from './plugin.ts'
3
2
  export type { Options, PluginFetch, ResolvedOptions, ResolverClient } from './types.ts'
package/src/plugin.ts CHANGED
@@ -1,14 +1,9 @@
1
- import path from 'node:path'
2
- import { createSdkGenerator, defaultMacros, isValidatorEnabled, resolverClient } from '@internals/client'
3
- import { createGroupConfig } from '@internals/shared'
4
- import { addGenerator, defineExtension, injectFile, Resolver, setMacros, setResolver, useConfig } from '@kubb/kit'
1
+ import { fileURLToPath } from 'node:url'
2
+ import { defineExtension } from '@kubb/kit'
3
+ import { clientDependencies, resolveClientOptions, setupClient } from '@kubb/plugin-client'
5
4
  import { compatibility } from '../kubb-extension.json'
6
5
  import { version } from '../package.json'
7
- import { pluginTsName } from '@kubb/plugin-ts'
8
- import { pluginZodName } from '@kubb/plugin-zod'
9
- import { clientGenerator } from './generators/clientGenerator.tsx'
10
- import { fetchClientTemplatePath, coreTemplatePath, serializersTemplatePath, sseTemplatePath, standardSchemaTemplatePath } from './templates.ts'
11
- import type { PluginFetch, ResolvedOptions, ResolverClient } from './types.ts'
6
+ import type { PluginFetch } from './types.ts'
12
7
 
13
8
  /**
14
9
  * Canonical plugin name for `@kubb/plugin-fetch`. Used for driver lookups and cross-plugin
@@ -41,72 +36,10 @@ export const pluginFetchName = 'plugin-fetch' satisfies PluginFetch['name']
41
36
  export const pluginFetch = defineExtension<PluginFetch>({
42
37
  kind: 'plugin',
43
38
  meta: { name: pluginFetchName, version, compatibility },
44
- // `plugin-ts` supplies the operation types unless it is absent, in which case `pluginZod({ inferred: true })`
45
- // does. `plugin-zod` is required once `validator` enables a direction, so a missing one fails setup instead of codegen.
46
- dependencies: (options) => ({ [pluginTsName]: { optional: true }, [pluginZodName]: { optional: !isValidatorEnabled(options.validator) } }),
39
+ dependencies: clientDependencies,
47
40
  setup(options) {
48
- const config = useConfig()
49
- const {
50
- output = { path: 'clients', barrel: { type: 'named' } },
51
- exclude = [],
52
- include,
53
- override = [],
54
- baseURL,
55
- throwOnErrorDefault = true,
56
- validator = false,
57
- returnType = 'full',
58
- group,
59
- sdk,
60
- resolver: userResolver,
61
- } = options
62
-
63
- const resolved: ResolvedOptions = {
64
- output,
65
- exclude,
66
- include,
67
- override,
68
- group: createGroupConfig(group),
69
- baseURL,
70
- throwOnErrorDefault,
71
- validator,
72
- returnType,
73
- sdk: sdk ? { mode: sdk.mode ?? 'tag', name: sdk.name } : undefined,
74
- resolver: userResolver ? Resolver.merge<ResolverClient>(resolverClient, userResolver) : resolverClient,
75
- }
76
-
77
- setResolver(resolved.resolver)
78
- setMacros([...defaultMacros, ...(options.macros ?? [])])
79
-
80
- // `sdk` swaps the per-operation functions for the class-based SDK; left unset, the standalone
81
- // functions (which query plugins consume) stay.
82
- addGenerator(resolved.sdk ? createSdkGenerator<PluginFetch>({ sse: sseTemplatePath }) : clientGenerator)
83
-
84
- const root = path.resolve(config.root, config.output.path)
85
-
86
- injectFile({
87
- baseName: 'serializers.ts',
88
- path: path.resolve(root, '.kubb/serializers.ts'),
89
- copy: serializersTemplatePath,
90
- })
91
-
92
- injectFile({
93
- baseName: 'core.ts',
94
- path: path.resolve(root, '.kubb/core.ts'),
95
- copy: coreTemplatePath,
96
- })
97
-
98
- injectFile({
99
- baseName: 'client.ts',
100
- path: path.resolve(root, '.kubb/client.ts'),
101
- copy: fetchClientTemplatePath,
102
- })
103
-
104
- injectFile({
105
- baseName: 'standardSchema.ts',
106
- path: path.resolve(root, '.kubb/standardSchema.ts'),
107
- copy: standardSchemaTemplatePath,
108
- })
109
-
41
+ const resolved = resolveClientOptions(options)
42
+ setupClient({ name: 'fetch', resolved, macros: options.macros, client: fileURLToPath(new URL('../templates/client.ts', import.meta.url)) })
110
43
  return resolved
111
44
  },
112
45
  })
package/src/types.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  import type { PluginType } from '@kubb/kit'
2
- import type { Options, ResolvedOptions, ResolverClient } from '@internals/client'
2
+ import type { ClientOptions, ClientResolvedOptions as ResolvedOptions, ResolverClient } from '@kubb/plugin-client'
3
3
 
4
- export type { Options, ResolvedOptions, ResolverClient } from '@internals/client'
4
+ export type { ClientResolvedOptions as ResolvedOptions, ResolverClient } from '@kubb/plugin-client'
5
+
6
+ /** The shared client options, without `returnType: 'plain'`, which only fits a client module `@kubb/plugin-client` calls. */
7
+ export type Options = ClientOptions & { returnType?: 'full' | 'data' }
5
8
 
6
9
  /**
7
10
  * The plugin factory type for `@kubb/plugin-fetch`. Shares the options surface, resolver, and
@@ -1,39 +1,21 @@
1
- import {
2
- createClientCore,
3
- getResponseContentType,
4
- resolveResponseType,
5
- type ResponseType,
6
- type ResponseTypeMap,
7
- type Transport,
8
- type TransportResult,
9
- } from './core.ts'
10
- import { isJsonMediaType } from './serializers.ts'
1
+ import { createClientCore, createLazyClient, toRequestInit } from './core.ts'
2
+ import { defaultConfig } from './config.ts'
11
3
  import * as core from './core.ts'
12
4
 
13
5
  export * from './core.ts'
14
6
 
15
- /** The request and response objects of this transport, carried on every result and error. */
7
+ /**
8
+ * The native request and response that every result and error carries.
9
+ */
16
10
  export type NativeRequest = Request
17
11
  export type NativeResponse = Response
18
12
 
19
13
  /**
20
- * 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`.
14
+ * Extra `fetch` init for a call or client, such as `cache`, `redirect`, or Next.js's `next`.
21
15
  */
22
- export type FetchOptions = RequestInit & { next?: Record<string, unknown> }
16
+ export type NativeOptions = RequestInit & { next?: Record<string, unknown> }
23
17
 
24
- export type RequestConfig<TBody = unknown, TRequest = NativeRequest, TResponse = NativeResponse> = core.RequestConfig<TBody, TRequest, TResponse> & {
25
- options?: FetchOptions
26
- }
27
- export type Options<TData extends core.DataShape, ThrowOnError extends boolean = true, TRequest = NativeRequest, TResponse = NativeResponse> = core.Options<
28
- TData,
29
- ThrowOnError,
30
- TRequest,
31
- TResponse
32
- > & { options?: FetchOptions }
33
- export type ClientConfig<TRequest = NativeRequest, TResponse = NativeResponse> = core.ClientConfig<TRequest, TResponse> & { options?: FetchOptions }
34
- export type ResolvedRequest = core.ResolvedRequest & { options?: FetchOptions }
35
18
  export type ResponseError<TError = unknown, TRequest = NativeRequest, TResponse = NativeResponse> = core.ResponseError<TError, TRequest, TResponse>
36
- /** The core's `ResponseError` class, typed with this transport's request and response. `instanceof` and `ResponseError.is` both match what the client throws. */
37
19
  export const ResponseError = core.ResponseError as {
38
20
  new <TError = unknown, TRequest = NativeRequest, TResponse = NativeResponse>(
39
21
  config: ConstructorParameters<typeof core.ResponseError<TError, TRequest, TResponse>>[0],
@@ -43,69 +25,68 @@ export const ResponseError = core.ResponseError as {
43
25
  prototype: core.ResponseError<unknown, NativeRequest, NativeResponse>
44
26
  }
45
27
 
46
- async function parseResponse(response: Response, responseType?: ResponseType | ResponseTypeMap): Promise<unknown> {
47
- if (response.status === 204 || response.status === 205 || response.status === 304 || !response.body) {
48
- return undefined
49
- }
28
+ export type RequestConfig<TBody = unknown, TRequest = NativeRequest, TResponse = NativeResponse> = core.RequestConfig<TBody, TRequest, TResponse> & {
29
+ options?: NativeOptions
30
+ }
31
+ export type Options<TData extends core.DataShape, ThrowOnError extends boolean = true, TRequest = NativeRequest, TResponse = NativeResponse> = core.Options<
32
+ TData,
33
+ ThrowOnError,
34
+ TRequest,
35
+ TResponse
36
+ > & { options?: NativeOptions }
37
+ export type ClientConfig<TRequest = NativeRequest, TResponse = NativeResponse> = core.ClientConfig<TRequest, TResponse> & { options?: NativeOptions }
38
+ export type ResolvedRequest = core.ResolvedRequest & { options?: NativeOptions }
39
+ export type RequestResult<
40
+ TResponses,
41
+ ThrowOnError extends boolean = true,
42
+ TRequest = NativeRequest,
43
+ TResponse = NativeResponse,
44
+ THeaders = unknown,
45
+ > = core.RequestResult<TResponses, ThrowOnError, TRequest, TResponse, THeaders>
46
+ export type UnwrappedResult<
47
+ TResponses,
48
+ ThrowOnError extends boolean = true,
49
+ TRequest = NativeRequest,
50
+ TResponse = NativeResponse,
51
+ THeaders = unknown,
52
+ > = core.UnwrappedResult<TResponses, ThrowOnError, TRequest, TResponse, THeaders>
53
+ export type ResponseErrorConfig<TError = unknown> = core.ResponseError<TError, NativeRequest, NativeResponse>
54
+ export type TransportResult<TRequest = NativeRequest, TResponse = NativeResponse> = core.TransportResult<TRequest, TResponse>
55
+ export type DecodedResponse<TData = unknown, TRequest = NativeRequest, TResponse = NativeResponse> = core.DecodedResponse<TData, TRequest, TResponse>
56
+ export type Transport<TRequest = NativeRequest, TResponse = NativeResponse> = core.Transport<TRequest, TResponse>
57
+ export type Interceptors<TRequest = NativeRequest, TResponse = NativeResponse> = core.Interceptors<TRequest, TResponse>
58
+ export type ClientInstance<TRequest = NativeRequest, TResponse = NativeResponse> = core.ClientInstance<TRequest, TResponse>
59
+ export type StreamResult<
60
+ TResponses,
61
+ ThrowOnError extends boolean = true,
62
+ TEvent = core.ServerSentEvent<core.SuccessOf<TResponses>>,
63
+ TRequest = NativeRequest,
64
+ TResponse = NativeResponse,
65
+ THeaders = unknown,
66
+ > = core.StreamResult<TResponses, ThrowOnError, TEvent, TRequest, TResponse, THeaders>
67
+ export type ResponseErrorOf<TResponses, TRequest = NativeRequest, TResponse = NativeResponse, THeaders = unknown> = core.ResponseErrorOf<
68
+ TResponses,
69
+ TRequest,
70
+ TResponse,
71
+ THeaders
72
+ >
73
+ export const isResponseError = core.isResponseError as <TResponses = unknown, TRequest = NativeRequest, TResponse = NativeResponse, THeaders = unknown>(
74
+ error: unknown,
75
+ ) => error is ResponseErrorOf<TResponses, TRequest, TResponse, THeaders>
50
76
 
51
- const contentType = response.headers.get('Content-Type')
52
- // A server may answer a streamed operation with JSON, or with an error body: both are decoded by their content type. Any other streamed success body stays a stream.
53
- const resolved = resolveResponseType(responseType, contentType)
54
- const detected = resolved === 'stream' && (!response.ok || isJsonMediaType(contentType)) ? resolveResponseType(undefined, contentType) : resolved
55
- switch (detected) {
56
- case 'text':
57
- case 'document':
58
- return response.text()
59
- case 'blob':
60
- return response.blob()
61
- case 'arraybuffer':
62
- return response.arrayBuffer()
63
- case 'stream':
64
- return response.body ?? undefined
65
- case 'json': {
66
- // An empty body with a JSON content-type would make response.json() throw, so treat it as no data.
67
- const body = await response.text()
68
- return body ? JSON.parse(body) : undefined
69
- }
70
- }
77
+ export const defaultTransport = async (request: core.ResolvedRequest): Promise<TransportResult> => {
78
+ const nativeRequest = new Request(request.url, toRequestInit(request))
79
+ // `Request` drops the non-standard `next` field, so Next.js reads it from the init.
80
+ const nextInit: NativeOptions | undefined = request.options?.next ? { next: request.options.next } : undefined
81
+ const response = await globalThis.fetch(nativeRequest, nextInit)
71
82
 
72
- const text = await response.text()
73
- if (!text) return undefined
74
- try {
75
- return JSON.parse(text)
76
- } catch {
77
- return text
78
- }
83
+ return { webResponse: response, request: nativeRequest, response }
79
84
  }
80
85
 
81
86
  /**
82
- * The default transport that sends the resolved request through `globalThis.fetch` and returns the parsed body with the native request and response.
87
+ * The client every generated operation uses unless a call passes its own. It is created on first use.
83
88
  */
84
- export const defaultTransport: Transport = async (request: ResolvedRequest): Promise<TransportResult> => {
85
- const init: RequestInit = {
86
- ...request.options,
87
- method: request.method,
88
- headers: request.headers,
89
- body: request.body,
90
- signal: request.signal,
91
- }
92
- if (request.credentials) init.credentials = request.credentials
93
-
94
- const nativeRequest = new Request(request.url, init)
95
- const response = await globalThis.fetch(nativeRequest)
96
- const data = await parseResponse(response, request.responseType)
97
-
98
- return {
99
- data,
100
- status: response.status,
101
- statusText: response.statusText,
102
- headers: response.headers,
103
- contentType: getResponseContentType(response.headers),
104
- request: nativeRequest,
105
- response,
106
- }
107
- }
108
-
109
- export const client = createClientCore({ defaultTransport })
89
+ export const client: ClientInstance = createLazyClient((config) => createClientCore({ defaultTransport, ...config }))
90
+ client.setConfig(defaultConfig)
110
91
 
111
- export const createClient = (config?: Parameters<typeof client.createClient>[0]) => client.createClient(config)
92
+ export const createClient: ClientInstance['createClient'] = client.createClient
@@ -1,39 +0,0 @@
1
- import { n as __exportAll, r as __reExport, t as core_d_exports } from "./core-D6FAGTsL.js";
2
- declare namespace client_d_exports {
3
- export { ClientConfig, FetchOptions, NativeRequest, NativeResponse, Options, RequestConfig, ResolvedRequest, ResponseError, client, createClient, defaultTransport };
4
- }
5
- /** The request and response objects of this transport, carried on every result and error. */
6
- type NativeRequest = Request;
7
- type NativeResponse = Response;
8
- /**
9
- * 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`.
10
- */
11
- type FetchOptions = RequestInit & {
12
- next?: Record<string, unknown>;
13
- };
14
- type RequestConfig<TBody = unknown, TRequest = NativeRequest, TResponse = NativeResponse> = core_d_exports.RequestConfig<TBody, TRequest, TResponse> & {
15
- options?: FetchOptions;
16
- };
17
- type Options<TData extends core_d_exports.DataShape, ThrowOnError extends boolean = true, TRequest = NativeRequest, TResponse = NativeResponse> = core_d_exports.Options<TData, ThrowOnError, TRequest, TResponse> & {
18
- options?: FetchOptions;
19
- };
20
- type ClientConfig<TRequest = NativeRequest, TResponse = NativeResponse> = core_d_exports.ClientConfig<TRequest, TResponse> & {
21
- options?: FetchOptions;
22
- };
23
- type ResolvedRequest = core_d_exports.ResolvedRequest & {
24
- options?: FetchOptions;
25
- };
26
- type ResponseError<TError = unknown, TRequest = NativeRequest, TResponse = NativeResponse> = core_d_exports.ResponseError<TError, TRequest, TResponse>;
27
- /** The core's `ResponseError` class, typed with this transport's request and response. `instanceof` and `ResponseError.is` both match what the client throws. */
28
- declare const ResponseError: {
29
- new <TError = unknown, TRequest = NativeRequest, TResponse = NativeResponse>(config: ConstructorParameters<typeof core_d_exports.ResponseError<TError, TRequest, TResponse>>[0]): core_d_exports.ResponseError<TError, TRequest, TResponse>;
30
- is: typeof core_d_exports.ResponseError.is;
31
- prototype: core_d_exports.ResponseError<unknown, NativeRequest, NativeResponse>;
32
- };
33
- /**
34
- * The default transport that sends the resolved request through `globalThis.fetch` and returns the parsed body with the native request and response.
35
- */
36
- declare const defaultTransport: core_d_exports.Transport;
37
- declare const client: core_d_exports.ClientInstance<unknown, unknown>;
38
- declare const createClient: (config?: Parameters<typeof client.createClient>[0]) => core_d_exports.ClientInstance<unknown, unknown>;
39
- export { Options as a, ResponseError as c, createClient as d, defaultTransport as f, NativeResponse as i, client as l, FetchOptions as n, RequestConfig as o, NativeRequest as r, ResolvedRequest as s, ClientConfig as t, client_d_exports as u };
@@ -1,2 +0,0 @@
1
- import * as import__kubb_plugin_client_templates_core_ts from "@kubb/plugin-client/templates/core.ts";
2
- export { __exportAll as n, __reExport as r, core_d_exports as t };
@@ -1,2 +0,0 @@
1
- import "../core-D6FAGTsL.js";
2
- export * from "@kubb/plugin-client/templates/core.ts";
@@ -1,6 +0,0 @@
1
- import { a as Options, c as ResponseError, d as createClient, f as defaultTransport, i as NativeResponse, l as client, n as FetchOptions, o as RequestConfig, r as NativeRequest, s as ResolvedRequest, t as ClientConfig, u as client_d_exports } from "../client-Dn80AjdR.js";
2
- export * from "@kubb/plugin-client/templates/core.ts";
3
- declare namespace fetch_d_exports {
4
- export { ClientConfig, FetchOptions, NativeRequest, NativeResponse, Options, RequestConfig, ResolvedRequest, ResponseError, client, createClient, defaultTransport };
5
- }
6
- export { ClientConfig, FetchOptions, NativeRequest, NativeResponse, Options, RequestConfig, ResolvedRequest, ResponseError, client, createClient, defaultTransport };
@@ -1 +0,0 @@
1
- export * from "@kubb/plugin-client/templates/serializers.ts";
@@ -1 +0,0 @@
1
- export * from "@kubb/plugin-client/templates/standardSchema.ts";
@@ -1,10 +0,0 @@
1
- import { createClientGenerator } from '@internals/client'
2
- import { sseTemplatePath } from '../templates.ts'
3
- import type { PluginFetch } from '../types.ts'
4
-
5
- /**
6
- * Built-in operation generator for `@kubb/plugin-fetch`. Emits one async function per OpenAPI
7
- * operation using the shared `Operation` component: a grouped `<Name>Request` type and a function
8
- * that forwards a single `options` object to the bundled `client` and returns the `RequestResult`.
9
- */
10
- export const clientGenerator = createClientGenerator<PluginFetch>('fetch', { sse: sseTemplatePath })
package/src/templates.ts DELETED
@@ -1,16 +0,0 @@
1
- import { createRequire } from 'node:module'
2
- import { fileURLToPath } from 'node:url'
3
-
4
- const require = createRequire(import.meta.url)
5
-
6
- /** Absolute path to the fetch client template, copied into `.kubb/client.ts`. */
7
- export const fetchClientTemplatePath = fileURLToPath(new URL('../templates/client.ts', import.meta.url))
8
-
9
- /**
10
- * Absolute paths to the runtime templates `@kubb/plugin-client` ships for every client plugin, copied into `.kubb/core.ts`,
11
- * `.kubb/serializers.ts`, `.kubb/standardSchema.ts`, and `.kubb/sse.ts`.
12
- */
13
- export const coreTemplatePath = require.resolve('@kubb/plugin-client/templates/core.ts')
14
- export const serializersTemplatePath = require.resolve('@kubb/plugin-client/templates/serializers.ts')
15
- export const standardSchemaTemplatePath = require.resolve('@kubb/plugin-client/templates/standardSchema.ts')
16
- export const sseTemplatePath = require.resolve('@kubb/plugin-client/templates/sse.ts')
package/templates/core.ts DELETED
@@ -1,2 +0,0 @@
1
- // Resolves `./core.ts` for the client template next to it. The generator copies the file from `@kubb/plugin-client` into `.kubb/core.ts`.
2
- export * from '@kubb/plugin-client/templates/core.ts'
@@ -1,2 +0,0 @@
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'
@@ -1,2 +0,0 @@
1
- // Resolves `./serializers.ts` for the client template next to it. The generator copies the file from `@kubb/plugin-client` into `.kubb/serializers.ts`.
2
- export * from '@kubb/plugin-client/templates/serializers.ts'
@@ -1,2 +0,0 @@
1
- // Resolves `./standardSchema.ts` for the client template next to it. The generator copies the file from `@kubb/plugin-client` into `.kubb/standardSchema.ts`.
2
- export * from '@kubb/plugin-client/templates/standardSchema.ts'