@dlenroc/typed-client 0.1.0 → 0.3.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/dist/fetch.d.ts CHANGED
@@ -1,4 +1,16 @@
1
- import { _ as Transport, f as RequestKindMap, m as ResponseKindMap } from "./types-Cq8XAc1z.js";
1
+ import { _ as Transport, f as RequestKindMap, m as ResponseKindMap, n as CommonOptions } from "./types-XCe4DTv4.js";
2
+ interface FetchRequestKinds extends RequestKindMap {
3
+ /**
4
+ * A `Blob` or `File`. Fetch uses its `type`, if not empty, as the default
5
+ * `Content-Type`.
6
+ */
7
+ readonly blob: Blob;
8
+ /**
9
+ * A `ReadableStream` of bytes. Fetch reads the stream once while it sends
10
+ * the body. With `follow: true`, a redirect other than 303 fails.
11
+ */
12
+ readonly stream: ReadableStream<Uint8Array>;
13
+ }
2
14
  interface FetchResponseKinds extends ResponseKindMap {
3
15
  readonly blob: Blob;
4
16
  readonly stream: ReadableStream<Uint8Array>;
@@ -7,14 +19,19 @@ interface FetchMetadata {
7
19
  readonly redirected: boolean;
8
20
  readonly type: ResponseType;
9
21
  }
10
- declare const NATIVE_OPTION_KEYS: readonly ["cache", "credentials", "integrity", "keepalive", "mode", "redirect", "referrer", "referrerPolicy", "signal", "priority", "window"];
11
- type FetchNativeOptions = Pick<RequestInit, (typeof NATIVE_OPTION_KEYS)[number]>;
22
+ type FetchNativeOptions = CommonOptions & {
23
+ /**
24
+ * Passed to `fetch`. `redirect` here overrides `follow`. The client
25
+ * combines `signal` here with `timeout`.
26
+ */
27
+ readonly transport?: Omit<RequestInit, "method" | "headers" | "body">;
28
+ };
12
29
  /**
13
- * Use the browser's Fetch API or Node.js 24+.
30
+ * Send requests with the Fetch API of a browser or Node.js 24+.
14
31
  *
15
32
  * @remarks
16
- * Leave the body absent for GET and HEAD. Pass native options such as
17
- * `signal` in the call object. This adapter also decodes `blob` and
33
+ * Do not send a body with `GET` or `HEAD`. Pass native options such as
34
+ * `signal` under `transport`. This transport also decodes `blob` and
18
35
  * `stream` responses. Consume or cancel returned streams. A stream
19
36
  * schema must release its reader lock before it returns or throws.
20
37
  * If the schema replaces the stream, consume or cancel the original.
@@ -27,7 +44,7 @@ type FetchNativeOptions = Pick<RequestInit, (typeof NATIVE_OPTION_KEYS)[number]>
27
44
  *
28
45
  * const transport = fetchTransport({ baseUrl: "https://api.example.test" });
29
46
  * const health = c.bind(c.endpoint("/health"), transport);
30
- * await health({ status: 204, signal: AbortSignal.timeout(5000) });
47
+ * await health({ status: 204, timeout: 5000 });
31
48
  * ```
32
49
  *
33
50
  * @throws
@@ -38,5 +55,5 @@ export declare function fetchTransport(config?: {
38
55
  readonly baseUrl?: string;
39
56
  /** @defaultValue globalThis.fetch */
40
57
  readonly fetch?: typeof globalThis.fetch;
41
- }): Transport<RequestKindMap, FetchResponseKinds, FetchNativeOptions, FetchMetadata>;
58
+ }): Transport<FetchRequestKinds, FetchResponseKinds, FetchNativeOptions, FetchMetadata>;
42
59
  export {};
package/dist/fetch.js CHANGED
@@ -1,19 +1,6 @@
1
- import { a as TransportFailure, c as asSearchParams, r as RequestPreparationError, s as createUrlResolver } from "./errors-D1bIeOq9.js";
2
- import { a as appendResponseHeader, c as asFormData, i as encodeUtf8, l as binaryView, n as decodeUrlEncoded, o as defaultContentType, s as prepareHeaders, u as encodeJson } from "./codec-BWlr5T5u.js";
1
+ import { a as transportError, c as asSearchParams, s as createUrlResolver } from "./errors-25xWqgvt.js";
2
+ import { a as appendResponseHeader, c as encodeJson, i as encodeUtf8, n as decodeUrlEncoded, o as prepareHeaders, s as asFormData } from "./codec-CaVxvHce.js";
3
3
  // src/transports/fetch.ts
4
- const NATIVE_OPTION_KEYS = [
5
- "cache",
6
- "credentials",
7
- "integrity",
8
- "keepalive",
9
- "mode",
10
- "redirect",
11
- "referrer",
12
- "referrerPolicy",
13
- "signal",
14
- "priority",
15
- "window"
16
- ];
17
4
  async function decodeFormData(form) {
18
5
  const target = Object.create(null);
19
6
  for (const [name, item] of form) {
@@ -48,8 +35,6 @@ var FetchResponseHandle = class {
48
35
  };
49
36
  const headers = Object.create(null);
50
37
  for (const [name, value] of native.headers) appendResponseHeader(headers, name, value);
51
- const cookies = native.headers.getSetCookie?.();
52
- if (cookies?.length) headers["set-cookie"] = cookies;
53
38
  this.headers = headers;
54
39
  }
55
40
  async read(kind) {
@@ -80,22 +65,21 @@ var FetchResponseHandle = class {
80
65
  this.state = "stream";
81
66
  return stream;
82
67
  }
83
- throw new TypeError(`Unsupported Fetch response body kind: ${String(kind)}`);
68
+ throw new TypeError(`Unsupported response kind: ${String(kind)}`);
84
69
  }
85
70
  async discard() {
86
- if (this.state === "unread") await this.read("none");
87
- else if (this.state === "stream") {
71
+ if (this.state === "stream") {
88
72
  this.state = "read";
89
73
  await this.native.body?.cancel();
90
74
  }
91
75
  }
92
76
  };
93
77
  /**
94
- * Use the browser's Fetch API or Node.js 24+.
78
+ * Send requests with the Fetch API of a browser or Node.js 24+.
95
79
  *
96
80
  * @remarks
97
- * Leave the body absent for GET and HEAD. Pass native options such as
98
- * `signal` in the call object. This adapter also decodes `blob` and
81
+ * Do not send a body with `GET` or `HEAD`. Pass native options such as
82
+ * `signal` under `transport`. This transport also decodes `blob` and
99
83
  * `stream` responses. Consume or cancel returned streams. A stream
100
84
  * schema must release its reader lock before it returns or throws.
101
85
  * If the schema replaces the stream, consume or cancel the original.
@@ -108,7 +92,7 @@ var FetchResponseHandle = class {
108
92
  *
109
93
  * const transport = fetchTransport({ baseUrl: "https://api.example.test" });
110
94
  * const health = c.bind(c.endpoint("/health"), transport);
111
- * await health({ status: 204, signal: AbortSignal.timeout(5000) });
95
+ * await health({ status: 204, timeout: 5000 });
112
96
  * ```
113
97
  *
114
98
  * @throws
@@ -120,79 +104,66 @@ function fetchTransport(config = {}) {
120
104
  if (typeof fetch !== "function") throw new TypeError("Fetch API is unavailable");
121
105
  return async (request) => {
122
106
  const url = resolveUrl(request.url);
107
+ let prepared = false;
123
108
  try {
124
109
  let body;
125
- const options = { method: request.method };
126
- try {
127
- if (request.body !== void 0) switch (request.bodyKind) {
128
- case "none": throw new RequestPreparationError("none request body kind cannot have a body");
129
- case "json":
130
- body = encodeJson(request.body);
131
- break;
132
- case "text":
133
- body = request.body;
134
- break;
135
- case "binary":
136
- body = binaryView(request.body);
137
- break;
138
- case "urlencoded": {
139
- const fields = request.body;
140
- body = typeof fields === "string" ? fields : asSearchParams(fields);
141
- break;
142
- }
143
- case "multipart":
144
- body = asFormData(request.body);
145
- break;
146
- default: throw new RequestPreparationError(`Unsupported Fetch request body kind: ${String(request.bodyKind)}`);
147
- }
148
- const headers = request.headers;
149
- const useMultipartBoundary = request.bodyKind === "multipart" && body !== void 0 && request.input?.unchecked !== true;
150
- if (headers instanceof Headers) {
151
- options.headers = headers;
152
- const contentType = body === void 0 ? void 0 : defaultContentType(request.bodyKind);
153
- if (useMultipartBoundary && headers.has("content-type")) {
154
- const preparedHeaders = new Headers(headers);
155
- preparedHeaders.delete("content-type");
156
- options.headers = preparedHeaders;
157
- } else if (contentType !== void 0 && !headers.has("content-type")) {
158
- const preparedHeaders = new Headers(headers);
159
- preparedHeaders.set("content-type", contentType);
160
- options.headers = preparedHeaders;
161
- }
162
- } else if (headers !== void 0 || body !== void 0) {
163
- let suppressContentType = false;
164
- const rawHeaders = prepareHeaders(headers, request.bodyKind, body !== void 0, (suppressed) => {
165
- suppressContentType = suppressed;
166
- });
167
- if (useMultipartBoundary) delete rawHeaders["content-type"];
168
- if (suppressContentType) {
169
- if (typeof body === "string" || body instanceof URLSearchParams) body = encodeUtf8(body.toString());
170
- else if (body instanceof FormData) try {
171
- body = await new Response(body).arrayBuffer();
172
- } catch (cause) {
173
- throw new RequestPreparationError("Failed to encode multipart body without Content-Type", { cause });
174
- }
175
- }
176
- const preparedHeaders = new Headers();
177
- for (const key in rawHeaders) {
178
- const value = rawHeaders[key];
179
- if (typeof value === "string") preparedHeaders.append(key, value);
180
- else for (const part of value) preparedHeaders.append(key, part);
181
- }
182
- options.headers = preparedHeaders;
110
+ const input = request.input;
111
+ const native = input?.transport;
112
+ const options = {
113
+ ...native,
114
+ method: request.method
115
+ };
116
+ if (native !== void 0) {
117
+ delete options.headers;
118
+ delete options.body;
119
+ }
120
+ if (request.body !== void 0) switch (request.bodyKind) {
121
+ case "none": throw new TypeError("Request body kind none does not allow a body");
122
+ case "json":
123
+ body = encodeJson(request.body);
124
+ break;
125
+ case "text":
126
+ body = request.body;
127
+ break;
128
+ case "binary":
129
+ case "blob":
130
+ body = request.body;
131
+ break;
132
+ case "urlencoded": {
133
+ const fields = request.body;
134
+ body = typeof fields === "string" ? fields : asSearchParams(fields);
135
+ break;
183
136
  }
184
- if (body !== void 0) options.body = body;
185
- for (const key of NATIVE_OPTION_KEYS) {
186
- const value = request.input?.[key];
187
- if (value !== void 0) options[key] = value;
137
+ case "multipart":
138
+ body = asFormData(request.body);
139
+ break;
140
+ case "stream":
141
+ body = request.body;
142
+ options.duplex = "half";
143
+ break;
144
+ default: throw new TypeError(`Unsupported request body kind: ${String(request.bodyKind)}`);
145
+ }
146
+ const headers = request.headers;
147
+ if (headers !== void 0 || body !== void 0) {
148
+ const selected = prepareHeaders(headers, request.bodyKind, body !== void 0, input?.unchecked === true);
149
+ if (selected.contentTypeSuppressed) {
150
+ if (typeof body === "string" || body instanceof URLSearchParams) body = encodeUtf8(body.toString());
151
+ else if (body instanceof FormData) body = await new Response(body).arrayBuffer();
152
+ else if (body instanceof Blob) body = body.slice();
188
153
  }
189
- } catch (cause) {
190
- if (cause instanceof RequestPreparationError) throw cause;
191
- throw new RequestPreparationError("Failed to prepare Fetch request", { cause });
154
+ options.headers = selected.fields;
155
+ }
156
+ if (body !== void 0) options.body = body;
157
+ if (options.redirect === void 0) options.redirect = input?.follow === true ? "follow" : "manual";
158
+ const timeout = input?.timeout;
159
+ if (timeout !== void 0) {
160
+ const limit = AbortSignal.timeout(timeout);
161
+ options.signal = options.signal ? AbortSignal.any([options.signal, limit]) : limit;
192
162
  }
163
+ prepared = true;
193
164
  return new FetchResponseHandle(await fetch(url, options));
194
- } catch (cause) {
195
- throw new TransportFailure(url, cause);
165
+ } catch (failure) {
166
+ throw transportError(prepared, request.method, url, request.meta, failure);
196
167
  }
197
168
  };
198
169
  }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as Transport, a as HeaderInput, c as MultipartFile, d as RequestFields, f as RequestKindMap, g as StandardSchemaV1, h as StandardIssue, l as MultipartInput, m as ResponseKindMap, n as CoreOptions, o as HeaderValue, p as ResponseHeaders, r as FieldScalar, s as JsonValue, t as AnyTransport, u as QueryInput, v as TransportRequest, y as TransportResponse } from "./types-Cq8XAc1z.js";
1
+ import { _ as Transport, c as MultipartFile, d as RequestFields, f as RequestKindMap, g as StandardSchemaV1, h as StandardIssue, i as FieldScalar, l as MultipartInput, m as ResponseKindMap, n as CommonOptions, o as HeaderInput, p as ResponseHeaders, r as CoreOptions, s as JsonValue, t as AnyTransport, u as QueryInput, v as TransportRequest, y as TransportResponse } from "./types-XCe4DTv4.js";
2
2
  declare const hintType: unique symbol;
3
3
  type TypeHint<Value> = {
4
4
  readonly [hintType]: (value: Value) => Value;
@@ -18,9 +18,10 @@ type IsAny<Value> = 0 extends 1 & Value ? true : false;
18
18
  type AllTrue<Results> = Exclude<Results, true> extends never ? true : false;
19
19
  type PairValueValid<Entry, Scalar> = Entry extends readonly [string, infer Value] ? IsFieldValue<Value, Scalar> : false;
20
20
  type IsFieldCollection<Value, Scalar> = Value extends readonly (infer Entry)[] ? PairValueValid<Entry, Scalar> : Value extends object ? AllTrue<{ [Key in keyof Value]-?: IsAny<Value[Key]> extends true ? true : Defined<Value[Key]> extends readonly (infer Item)[] ? IsFieldValue<Item, Scalar> : IsFieldValue<Defined<Value[Key]>, Scalar>; }[keyof Value]> : false;
21
+ type IsHeaderRecord<Value> = Value extends readonly unknown[] ? false : Value extends object ? AllTrue<{ [Key in keyof Value]-?: IsAny<Value[Key]> extends true ? true : IsFieldValue<Value[Key], FieldScalar>; }[keyof Value]> : false;
21
22
  type IsFieldValue<Value, Wire> = [Value] extends [Wire] ? true : false;
22
23
  type SameType<Left, Right> = [Left] extends [Right] ? [Right] extends [Left] ? true : false : false;
23
- type IsWireValue<Value, Wire> = unknown extends Wire ? true : IsAny<Value> extends true ? true : [Defined<Value>] extends [never] ? [Wire] extends [undefined] ? true : false : SameType<Wire, Readonly<Record<string, PathScalar>>> extends true ? IsFieldCollection<Defined<Value>, PathScalar> : SameType<Wire, QueryInput> extends true ? Defined<Value> extends string | URLSearchParams ? true : IsFieldCollection<Defined<Value>, FieldScalar> : SameType<Wire, HeaderInput> extends true ? [Defined<Value>] extends [Headers] ? true : IsFieldCollection<Defined<Value>, HeaderValue> : SameType<Wire, MultipartInput> extends true ? [Defined<Value>] extends [FormData] ? true : IsFieldCollection<Defined<Value>, FieldScalar | MultipartFile> : [Defined<Value>] extends [Wire] ? true : false;
24
+ type IsWireValue<Value, Wire> = unknown extends Wire ? true : IsAny<Value> extends true ? true : [Defined<Value>] extends [never] ? [Wire] extends [undefined] ? true : false : SameType<Wire, Readonly<Record<string, PathScalar>>> extends true ? IsFieldCollection<Defined<Value>, PathScalar> : SameType<Wire, QueryInput> extends true ? Defined<Value> extends string ? true : IsFieldCollection<Defined<Value>, FieldScalar> : SameType<Wire, HeaderInput> extends true ? IsHeaderRecord<Defined<Value>> : SameType<Wire, MultipartInput> extends true ? [Defined<Value>] extends [FormData] ? true : IsFieldCollection<Defined<Value>, FieldScalar | MultipartFile> : [Defined<Value>] extends [Wire] ? true : false;
24
25
  type PossibleBranch<Value, Wire> = Value extends unknown ? IsWireValue<Value, Wire> : never;
25
26
  type AcceptsDecodedValue<Value, Wire> = unknown extends Value ? true : true extends PossibleBranch<Value, Wire> ? true : [Wire] extends [Value] ? true : false;
26
27
  type KindInput<Kind extends string> = Kind extends keyof RequestKindMap ? RequestKindMap[Kind] : unknown;
@@ -43,7 +44,7 @@ interface BodyDescriptor<Kind extends string = string> {
43
44
  type BodySpec<Kind extends string = string> = Kind | SchemaLike | BodyDescriptor<Kind>;
44
45
  interface ResponseDescriptor {
45
46
  readonly body: BodySpec<ResponseKindName>;
46
- /** Receives raw, lowercase header names and may transform them. */
47
+ /** Receives raw, lowercase header names and can transform them. */
47
48
  readonly headers?: SchemaLike;
48
49
  readonly "~standard"?: never;
49
50
  readonly [hintType]?: never;
@@ -55,11 +56,14 @@ type ResponseDefinition = ResponseKindName | SchemaLike | (BodyDescriptor<Respon
55
56
  interface EndpointDefinition {
56
57
  /** @defaultValue "GET" */
57
58
  readonly method?: HttpMethod;
58
- /** Transform call input into the values for `:name` segments. */
59
+ /** Schema for the `path` call field. Its output fills `{name}` parameters. */
59
60
  readonly path?: SchemaLike;
60
- /** Runs before URL encoding. */
61
+ /** Schema for the `query` call field. Runs before URL encoding. */
61
62
  readonly query?: SchemaLike;
62
- /** Runs before the transport applies header defaults. */
63
+ /**
64
+ * Schema for the `headers` call field. Runs before the transport applies
65
+ * header defaults.
66
+ */
63
67
  readonly headers?: SchemaLike;
64
68
  /**
65
69
  * A direct type hint or schema selects JSON.
@@ -71,11 +75,11 @@ interface EndpointDefinition {
71
75
  readonly body?: BodySpec<RequestKindName>;
72
76
  /**
73
77
  * Use `{ body, headers }` to validate headers alongside the body.
74
- * Body schemas receive the decoded value.
75
- * Calls require `status` when this map is empty or omitted.
78
+ * Body schemas receive the decoded value. If there are no declared
79
+ * responses, pass `status` on each call.
76
80
  */
77
81
  readonly responses?: Readonly<Record<number, ResponseDefinition>>;
78
- /** Passed by reference to the transport and included in ClientError. */
82
+ /** Passed by reference to the transport and included in `ClientError`. */
79
83
  readonly meta?: Readonly<Record<string, unknown>>;
80
84
  }
81
85
  interface NormalizedBody {
@@ -178,9 +182,8 @@ type ValidateEndpoint<Url extends string, Declaration extends EndpointDefinition
178
182
  };
179
183
  type StripAfter<Text extends string, Delimiter extends string> = Text extends `${infer Prefix}${Delimiter}${string}` ? Prefix : Text;
180
184
  type PathOnly<Url extends string> = StripAfter<StripAfter<Url, "?">, "#">;
181
- type NameInSegment<Segment extends string> = Segment extends `:${infer Name}` ? Exclude<Name, ""> : never;
182
- type SegmentNames<Path extends string> = Path extends `${infer Head}/${infer Tail}` ? NameInSegment<Head> | SegmentNames<Tail> : NameInSegment<Path>;
183
- type PathNames<Url extends string> = string extends Url ? string : SegmentNames<PathOnly<Url>>;
185
+ type TemplateNames<Path extends string, Names extends string = never> = Path extends `${string}{${infer Name}}${infer Rest}` ? TemplateNames<Rest, Names | Exclude<Name, "">> : Names;
186
+ type PathNames<Url extends string> = string extends Url ? string : TemplateNames<PathOnly<Url>>;
184
187
  type Simplify<Value> = { [Key in keyof Value]: Value[Key]; } & {};
185
188
  type FieldProperty<Key extends string, Value> = undefined extends Value ? { [Property in Key]?: Value; } : { [Property in Key]: Value; };
186
189
  type KeysOfPath<Path extends PathPlan> = Path extends {
@@ -241,12 +244,19 @@ type FinalHeaders<Response> = Response extends {
241
244
  } ? [Defined<Schema>] extends [never] ? ResponseHeaders : SchemaOutput<Defined<Schema>> : ResponseHeaders;
242
245
  type MaybeDiscard<Options, Body> = [OptionValue<Options, "discard">] extends [true] ? undefined : true extends OptionValue<Options, "discard"> ? Body | undefined : Body;
243
246
  type TransportField<Adapter extends AnyTransport> = [TransportMetadata<Adapter>] extends [never] ? {} : {
247
+ /**
248
+ * For example, Fetch `redirected`, Playwright `serverAddr`, or k6
249
+ * `timings`.
250
+ */
244
251
  readonly transport?: TransportMetadata<Adapter>;
245
252
  };
246
253
  type ResponseCase<Status extends number, Response, Adapter extends AnyTransport, Options> = Simplify<{
247
254
  readonly status: Status;
255
+ /** The final response URL, after redirects. */
248
256
  readonly url: string;
257
+ /** Raw headers, or the output of the response headers schema. */
249
258
  readonly headers: FinalHeaders<Response>;
259
+ /** The decoded body, or the output of the response body schema. */
250
260
  readonly body: MaybeDiscard<Options, DecodedBody<Response, Adapter>>;
251
261
  } & TransportField<Adapter>>;
252
262
  type ResponseFor<Spec extends Endpoint, Adapter extends AnyTransport, Status extends number, Options = {}> = number extends Status ? ResponseCase<number, ResponseAt<Spec, DeclaredStatuses<Spec>> | undefined, Adapter, Options> : Status extends number ? ResponseCase<Status, ResponseAt<Spec, Status>, Adapter, Options> : never;
@@ -259,7 +269,8 @@ interface OperationTypes<Spec extends Endpoint = Endpoint, Adapter extends AnyTr
259
269
  };
260
270
  }
261
271
  /**
262
- * Reuse checked call inputs with the bound transport's options.
272
+ * The input type of a checked call to a bound endpoint. Includes the
273
+ * native options of the bound transport.
263
274
  *
264
275
  * @example
265
276
  * ```ts
@@ -272,9 +283,10 @@ type InferInput<Operation extends OperationTypes> = Simplify<CallFields<Operatio
272
283
  readonly unchecked?: false;
273
284
  }>;
274
285
  /**
275
- * Result with the body retained. Pass a status or union of statuses.
276
- * Defaults to all declared statuses. Status-only endpoints need a status.
277
- * Undeclared statuses yield raw headers and an undefined body.
286
+ * The result type of a call to a bound endpoint. Pass a status or union
287
+ * of statuses. Defaults to all declared statuses. If there are no declared
288
+ * responses, pass a status. Accepted undeclared statuses return raw
289
+ * headers and `body: undefined`.
278
290
  *
279
291
  * @example
280
292
  * ```ts
@@ -284,24 +296,28 @@ type InferInput<Operation extends OperationTypes> = Simplify<CallFields<Operatio
284
296
  type InferResponse<Operation extends OperationTypes, Status extends number = DeclaredStatuses<Operation[typeof boundOperation]["spec"]>> = ResponseFor<Operation[typeof boundOperation]["spec"], Operation[typeof boundOperation]["adapter"], Status>;
285
297
  type BoundOperation<Spec extends Endpoint, Adapter extends AnyTransport> = ({} extends CallFields<Spec, Adapter, {}> ? {
286
298
  /**
287
- * Accepts any declared response status.
299
+ * Send the request and return the checked response. Accepts all
300
+ * declared statuses.
288
301
  *
289
302
  * @throws
290
- * A {@link ClientError} if the call fails.
303
+ * A {@link ClientError} if the call fails, including an unexpected
304
+ * status.
291
305
  */
292
306
  (input?: undefined): Promise<ResultFor<Spec, Adapter, {}>>;
293
307
  } : {}) & OperationTypes<Spec, Adapter> & {
294
308
  /**
295
- * Accepts declared statuses by default. Pass `status` to select
296
- * which statuses to accept and narrow the result.
309
+ * Send the request and return the checked response. Accepts all declared
310
+ * statuses by default. Pass `status` to select which statuses to accept
311
+ * and narrow the result.
297
312
  *
298
313
  * @remarks
299
- * Use `unchecked: true` to skip request schemas and override the method,
300
- * path, or body kind. Use `discard: true` to check status and headers
301
- * without decoding or validating the response body.
314
+ * Use `unchecked: true` to skip request schemas and allow `method`,
315
+ * `path`, and `bodyKind` overrides. Use `discard: true` to check status
316
+ * and headers, then discard the body before decoding.
302
317
  *
303
318
  * @throws
304
- * A {@link ClientError} for a failed call, including an unexpected status.
319
+ * A {@link ClientError} if the call fails, including an unexpected
320
+ * status.
305
321
  *
306
322
  * @example
307
323
  * ```ts
@@ -325,11 +341,13 @@ type BoundOperation<Spec extends Endpoint, Adapter extends AnyTransport> = ({} e
325
341
  readonly unchecked: true;
326
342
  } : unknown) & CallRequest<Spec, Adapter, Unchecked> & NoInfer<ValidOptions<Spec, Input>> & CheckCallKeys<Input, CallFields<Spec, Adapter, Input>>): Promise<ResultFor<Spec, Adapter, Input>>;
327
343
  /**
328
- * Accepts declared statuses by default. Pass `status` to select
329
- * which statuses to accept and narrow the result.
344
+ * Send the request and return the checked response. Accepts all declared
345
+ * statuses by default. Pass `status` to select which statuses to accept
346
+ * and narrow the result.
330
347
  *
331
348
  * @throws
332
- * A {@link ClientError} if the call fails.
349
+ * A {@link ClientError} if the call fails, including an unexpected
350
+ * status.
333
351
  */
334
352
  <const Input extends CallOptions<Spec, Adapter> & RequestFields>(input: Input & NoInfer<CallRequest<Spec, Adapter, OptionValue<Input, "unchecked">> & ValidOptions<Spec, Input>> & CheckCallKeys<Input, CallFields<Spec, Adapter, Input>>): Promise<ResultFor<Spec, Adapter, Input>>;
335
353
  };
@@ -345,100 +363,98 @@ declare function type<Value>(): TypeHint<Value>;
345
363
  declare function endpoint<const Url extends string>(url: Url): PreparedEndpoint<Url, {}>;
346
364
  declare function endpoint<const Url extends string, const Declaration extends EndpointDefinition>(url: Url, definition: Declaration & ValidateEndpoint<Url, Declaration>): PreparedEndpoint<Url, Declaration>;
347
365
  declare function bind<const Contract extends EndpointTree, Adapter extends AnyTransport>(contract: Contract & ValidateBinding<Contract, Adapter>, transport: Adapter): BoundContract<Contract, Adapter>;
348
- interface ErrorContext {
349
- readonly method: string;
350
- readonly url?: string | undefined;
351
- readonly meta?: Readonly<Record<string, unknown>> | undefined;
352
- }
353
- type SchemaFailure = {
354
- readonly reason: "issues";
355
- readonly issues: readonly StandardIssue[];
356
- } | {
357
- readonly reason: "exception";
358
- };
359
- type ResponseDiagnostics = {
360
- readonly status: number;
361
- readonly headers: ResponseHeaders;
362
- };
366
+ type Meta = Readonly<Record<string, unknown>>;
367
+ type SchemaPart = "path" | "query" | "headers" | "body";
363
368
  /**
364
- * `request-input` covers an empty status list. `request-url` and
365
- * `request-prepare` cover URL construction and request preparation.
366
- * `transport` means the adapter failed to return a response.
367
- *
368
- * Schema failures identify the `field` and whether validation reported
369
- * `issues` or threw an exception. Response failures include the status
370
- * and raw headers. `status` adds the accepted statuses, `response-decode`
371
- * adds the body kind, and `response-cleanup` means only cleanup failed.
372
- */
373
- type Failure = {
374
- readonly code: "request-input";
375
- } | {
376
- readonly code: "request-url";
377
- } | {
378
- readonly code: "request-prepare";
379
- } | ({
380
- readonly code: "request-schema";
381
- readonly field: "path" | "query" | "headers" | "body";
382
- } & SchemaFailure) | {
383
- readonly code: "transport";
384
- } | (ResponseDiagnostics & ({
385
- readonly code: "status";
386
- readonly expectedStatuses: readonly number[];
387
- } | {
388
- readonly code: "response-decode";
389
- readonly kind: string;
390
- } | ({
391
- readonly code: "response-schema";
392
- readonly field: "headers" | "body";
393
- } & SchemaFailure) | {
394
- readonly code: "response-cleanup";
395
- }));
396
- export type ClientError = Error & {
397
- readonly method: string;
398
- /** Resolved request or response URL, when available. */
399
- readonly url: string | undefined;
400
- /** Shares the endpoint metadata object and defaults to an empty object. */
401
- readonly meta: Readonly<Record<string, unknown>>;
402
- /** Cleanup failure retained without replacing the primary error. */
403
- cleanupError?: unknown;
404
- } & Failure;
405
- type ClientErrorOptions = ErrorContext & Failure & {
406
- readonly cause?: unknown;
407
- };
408
- /**
409
- * Narrow by `code` to read failure-specific fields.
369
+ * The error that a bound call throws. Narrow by `code` to read its fields.
410
370
  *
411
371
  * @remarks
412
- * `cause` holds the underlying failure and `cleanupError` holds a
413
- * secondary cleanup failure. Diagnostic fields such as `code` and
414
- * `meta` are enumerable. Read `message` and `cause` explicitly for JSON.
372
+ * - `request`: Nothing was sent because the call input, URL, preparation,
373
+ * or a schema failed.
374
+ * - `transport`: The transport failed to deliver or release a response.
375
+ * - `status`: The status falls outside the accepted set.
376
+ * - `response`: The body cannot be decoded, or a response schema rejects
377
+ * the response.
378
+ *
379
+ * `schema` names the schema that failed. It reported `issues` or threw
380
+ * `cause`.
415
381
  *
416
382
  * @example
417
383
  * ```ts
418
384
  * if (error instanceof ClientError && error.code === "status") {
419
- * console.log(error.status, error.expectedStatuses);
385
+ * console.log(error.meta.operationId, error.status);
420
386
  * }
421
387
  * ```
422
- *
423
- * @example
424
- * ```ts
425
- * throw new ClientError({
426
- * code: "transport", method: "GET", cause,
427
- * });
428
- * ```
429
388
  */
389
+ export type ClientError = Error & {
390
+ readonly method: string;
391
+ /** Resolved request or response URL, when available. */
392
+ readonly url: string | undefined;
393
+ /** The endpoint's metadata object, passed by reference. */
394
+ readonly meta: Meta;
395
+ readonly cause: unknown;
396
+ /** Present only when cleanup failed as well as the primary failure. */
397
+ cleanupError?: unknown;
398
+ } & ({
399
+ /**
400
+ * Nothing was sent because the call input, URL, preparation, or a
401
+ * schema failed.
402
+ */
403
+ readonly code: "request";
404
+ readonly status: undefined;
405
+ readonly schema: SchemaPart | undefined;
406
+ readonly issues: readonly StandardIssue[] | undefined;
407
+ } | {
408
+ /** The transport failed to deliver or release a response. */
409
+ readonly code: "transport";
410
+ /** Set when a response arrived but could not be released. */
411
+ readonly status: number | undefined;
412
+ readonly schema: undefined;
413
+ readonly issues: undefined;
414
+ } | {
415
+ /** The status falls outside the accepted set. */
416
+ readonly code: "status";
417
+ readonly status: number;
418
+ readonly schema: undefined;
419
+ readonly issues: undefined;
420
+ } | {
421
+ /**
422
+ * The body cannot be decoded, or a response schema rejects the
423
+ * response.
424
+ */
425
+ readonly code: "response";
426
+ readonly status: number;
427
+ /** `undefined` when the body could not be decoded. */
428
+ readonly schema: "headers" | "body" | undefined;
429
+ readonly issues: readonly StandardIssue[] | undefined;
430
+ });
431
+ declare class ClientErrorInstance extends Error {
432
+ readonly code: string;
433
+ readonly method: string;
434
+ readonly url: string | undefined;
435
+ readonly meta: Meta;
436
+ readonly status: number | undefined;
437
+ readonly schema: string | undefined;
438
+ readonly issues: readonly StandardIssue[] | undefined;
439
+ cleanupError?: unknown;
440
+ constructor(code: ClientError["code"], summary: string, method: string, url: string | undefined, meta: Meta, status: number | undefined, schema: SchemaPart | undefined, issues: readonly StandardIssue[] | undefined, cause: unknown);
441
+ }
430
442
  export declare const ClientError: {
431
- new (options: ClientErrorOptions): ClientError;
443
+ /** @internal */
444
+ new (...args: ConstructorParameters<typeof ClientErrorInstance>): ClientError;
432
445
  };
433
446
  export declare const c: {
434
447
  /**
435
- * Use a full `:name` segment for a required path parameter.
448
+ * Declare an HTTP endpoint with its request and response types.
436
449
  *
437
450
  * @defaultValue GET with an optional JSON body.
438
451
  *
439
452
  * @remarks
440
- * Path values are URL-escaped.
441
- * With an empty or omitted response map, pass `status` on each call.
453
+ * Each `{name}` before `?` or `#` is a required path parameter. A
454
+ * parameter can be part of a segment, for example `/files/{name}.json`
455
+ * or `/jobs/{id}:cancel`. `{}` is literal text. The client escapes path
456
+ * values with `encodeURIComponent`. If there are no declared responses,
457
+ * pass `status` on each call.
442
458
  *
443
459
  * @example
444
460
  * ```ts
@@ -453,7 +469,8 @@ export declare const c: {
453
469
  */
454
470
  endpoint: typeof endpoint;
455
471
  /**
456
- * Supply a type without runtime validation. A bare body hint uses JSON.
472
+ * Supply a type without runtime validation. As a body declaration, it
473
+ * selects JSON.
457
474
  *
458
475
  * @see {@link https://standardschema.dev/ | Standard Schema} for validation.
459
476
  */
@@ -462,7 +479,7 @@ export declare const c: {
462
479
  * Bind an endpoint to get a callable function. Groups keep their keys.
463
480
  *
464
481
  * @remarks
465
- * Import an adapter from `/fetch`, `/playwright`, or `/k6`.
482
+ * Import a transport from `/fetch`, `/playwright`, or `/k6`.
466
483
  * See {@link Transport} to implement or wrap one.
467
484
  *
468
485
  * @example
@@ -476,4 +493,4 @@ export declare const c: {
476
493
  */
477
494
  bind: typeof bind;
478
495
  };
479
- export type { InferInput, InferResponse, RequestKindMap, ResponseHeaders, ResponseKindMap, Transport, TransportRequest, TransportResponse };
496
+ export type { CommonOptions, InferInput, InferResponse, RequestKindMap, ResponseHeaders, ResponseKindMap, Transport, TransportRequest, TransportResponse };