@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.
@@ -5,8 +5,8 @@ type SchemaResult<Output> = {
5
5
  readonly issues: readonly StandardIssue[];
6
6
  };
7
7
  /**
8
- * Request schemas run before sending. Response schemas receive decoded
9
- * bodies or raw headers. Both may validate asynchronously.
8
+ * Request schemas receive the call inputs. Response schemas receive raw
9
+ * headers or a decoded body. Both can validate asynchronously.
10
10
  *
11
11
  * @see {@link https://standardschema.dev/ | Standard Schema}
12
12
  */
@@ -31,16 +31,22 @@ type FieldScalar = string | number | boolean | bigint | null | undefined;
31
31
  type PairInput<Value> = readonly (readonly [string, Value])[];
32
32
  type Fields<Value> = Readonly<Record<string, Value | readonly Value[]>> | PairInput<Value>;
33
33
  /**
34
- * Strings are already encoded. Repeat pairs or use arrays in records.
35
- * Omit a field with `undefined` or send an empty value with `null`.
34
+ * The client sends a string without encoding it. Repeat pairs or use
35
+ * arrays in records. Omit a field with `undefined` or send an empty value
36
+ * with `null`.
36
37
  */
37
- type QueryInput = string | URLSearchParams | Fields<FieldScalar>;
38
- type HeaderValue = FieldScalar | readonly FieldScalar[];
38
+ type QueryInput = string | Fields<FieldScalar>;
39
39
  /**
40
- * Header names are case-insensitive. `undefined` allows a default,
41
- * `null` suppresses it, and `""` sends an empty value.
40
+ * Request headers by name.
41
+ *
42
+ * @remarks
43
+ * The client sends header names as given. Names that differ only in case
44
+ * are one header, so the client sends the last spelling and the last
45
+ * value. k6, Playwright, and HTTP/2 can change the case. `undefined`
46
+ * allows a default value, `null` suppresses the header and its default,
47
+ * and `""` sends an empty value.
42
48
  */
43
- type HeaderInput = Headers | Readonly<Record<string, HeaderValue>> | PairInput<HeaderValue>;
49
+ type HeaderInput = Readonly<Record<string, FieldScalar>>;
44
50
  /** A view sends only its selected byte range. */
45
51
  type BinaryInput = ArrayBuffer | ArrayBufferView;
46
52
  interface MultipartFile<Data = BinaryInput> {
@@ -51,8 +57,8 @@ interface MultipartFile<Data = BinaryInput> {
51
57
  readonly mediaType?: string;
52
58
  }
53
59
  /**
54
- * For repeated fields, use arrays in a record or repeat name-value pairs.
55
- * Omit fields with `undefined` or send empty values with `null`.
60
+ * Repeat pairs or use arrays in records. Omit a field with `undefined` or
61
+ * send an empty value with `null`.
56
62
  */
57
63
  type MultipartInput = Fields<FieldScalar | MultipartFile> | FormData;
58
64
  type JsonValue = null | boolean | number | string | readonly JsonValue[] | {
@@ -61,19 +67,25 @@ type JsonValue = null | boolean | number | string | readonly JsonValue[] | {
61
67
  type UrlEncodedResponse = Readonly<Record<string, string | readonly string[] | undefined>>;
62
68
  type MultipartResponseValue = string | MultipartFile<Uint8Array>;
63
69
  type MultipartResponse = Readonly<Record<string, MultipartResponseValue | readonly MultipartResponseValue[] | undefined>>;
64
- /** Lowercase names. Repeated values may be combined by the native API. */
70
+ /**
71
+ * Raw response headers with lowercase names. The native API can combine
72
+ * repeated values.
73
+ */
65
74
  type ResponseHeaders = { readonly [Name in string]: string | readonly string[] | undefined; };
66
75
  /** Extend or pick from these request kinds when defining a transport. */
67
76
  interface RequestKindMap {
68
77
  readonly none: undefined;
69
- /** Serialized with `JSON.stringify`. Failures raise `request-prepare`. */
78
+ /**
79
+ * Serialized with `JSON.stringify`. If serialization fails, the call
80
+ * throws a `request` error.
81
+ */
70
82
  readonly json: unknown;
71
83
  readonly text: string;
72
84
  readonly binary: BinaryInput;
73
85
  readonly urlencoded: QueryInput;
74
86
  /**
75
- * Checked calls use the encoder's Content-Type boundary. With
76
- * `unchecked: true`, a supplied Content-Type is sent as provided.
87
+ * Checked calls use the encoder's boundary. With `unchecked: true`, the
88
+ * client sends a supplied `Content-Type` unchanged.
77
89
  */
78
90
  readonly multipart: MultipartInput;
79
91
  }
@@ -89,14 +101,14 @@ interface ResponseKindMap {
89
101
  interface CoreOptions<Status extends number = number> {
90
102
  /**
91
103
  * A status array must be nonempty. Accepted undeclared statuses return
92
- * an `undefined` body and raw headers.
104
+ * raw headers and `body: undefined`.
93
105
  *
94
106
  * @defaultValue All declared response statuses
95
107
  */
96
108
  readonly status?: Status | readonly Status[];
97
109
  /**
98
- * Skip request schemas. Override `method`, `path`, or `bodyKind`.
99
- * Declared responses still use their schemas.
110
+ * Skip request schemas and allow `method`, `path`, and `bodyKind`
111
+ * overrides. Declared responses still use their schemas.
100
112
  *
101
113
  * @defaultValue false
102
114
  */
@@ -108,6 +120,21 @@ interface CoreOptions<Status extends number = number> {
108
120
  */
109
121
  readonly discard?: boolean;
110
122
  }
123
+ /** Options a transport supports by adding this type to its own. */
124
+ interface CommonOptions {
125
+ /**
126
+ * Milliseconds to wait for the response.
127
+ *
128
+ * @defaultValue k6: 60 s, Playwright: 30 s
129
+ */
130
+ readonly timeout?: number;
131
+ /**
132
+ * Follow redirects and return the final response.
133
+ *
134
+ * @defaultValue false
135
+ */
136
+ readonly follow?: boolean;
137
+ }
111
138
  interface RequestFields {
112
139
  readonly path?: unknown;
113
140
  readonly query?: unknown;
@@ -115,16 +142,17 @@ interface RequestFields {
115
142
  readonly body?: unknown;
116
143
  }
117
144
  /**
118
- * Use the prepared fields to send the request. Treat nested inputs as
119
- * read-only.
145
+ * The request that the client prepares for a transport. Treat nested
146
+ * inputs as read-only.
120
147
  */
121
148
  interface TransportRequest<Requests extends object = RequestKindMap, Responses extends object = ResponseKindMap, Options = unknown> {
122
149
  method: string;
123
150
  /** URL before the transport applies its base URL. */
124
151
  url: string;
152
+ /** See {@link HeaderInput} for `undefined` and `null` values. */
125
153
  headers?: HeaderInput | undefined;
126
154
  bodyKind: keyof Requests & string;
127
- /** `undefined` omits the body. JSON `null` is sent as a value. */
155
+ /** `undefined` omits the body. Send JSON `null` as a value. */
128
156
  body?: Requests[keyof Requests] | undefined;
129
157
  /** Use these possible decoded kinds to choose the native capture mode. */
130
158
  responseKinds: readonly (keyof Responses & string)[];
@@ -132,7 +160,7 @@ interface TransportRequest<Requests extends object = RequestKindMap, Responses e
132
160
  readonly meta: Readonly<Record<string, unknown>>;
133
161
  /**
134
162
  * The original call object by reference. Includes raw request fields,
135
- * call controls, and transport options.
163
+ * call options, and native options.
136
164
  */
137
165
  readonly input?: (CoreOptions & RequestFields & Readonly<Options> & {
138
166
  readonly method?: string;
@@ -140,8 +168,8 @@ interface TransportRequest<Requests extends object = RequestKindMap, Responses e
140
168
  }) | undefined;
141
169
  }
142
170
  /**
143
- * The client calls `read` at most once. The caller owns live resources
144
- * returned by a successful endpoint call.
171
+ * The response that a transport returns. The client calls `read` at most
172
+ * once. The caller owns live resources returned by a successful call.
145
173
  */
146
174
  interface TransportResponse<Responses extends object = ResponseKindMap, Metadata extends object = never> {
147
175
  readonly status: number;
@@ -158,21 +186,23 @@ interface TransportResponse<Responses extends object = ResponseKindMap, Metadata
158
186
  readonly none: undefined;
159
187
  })[Kind]>;
160
188
  /**
161
- * Release resources when status or schema checks reject the response.
162
- * May run before or after `read`. Without this method, the client uses
163
- * `read("none")` for unread responses.
189
+ * Release a live value that `read` returned, for example a stream. The
190
+ * client calls it when a schema rejects that value.
164
191
  */
165
192
  discard?(): Promise<void>;
166
193
  }
167
194
  /**
168
- * See {@link TransportRequest} for the prepared input and
169
- * {@link TransportResponse} for response ownership.
195
+ * A function that sends a prepared request and returns a
196
+ * {@link TransportResponse}.
170
197
  *
171
198
  * @remarks
172
- * Read transport options from `request.input` and expose metadata through
173
- * the handle's `transport` field. Before retrying a request, release the
174
- * previous response with `discard()` or `read("none")`. Release the
175
- * native response if handle creation fails.
199
+ * See {@link TransportRequest} for the prepared input and
200
+ * {@link TransportResponse} for response ownership.
201
+ * Read native options from `request.input` and expose metadata through
202
+ * the response's `transport` field. To support `timeout` and `follow`, add
203
+ * {@link CommonOptions} to the options. Before retrying a request,
204
+ * release the previous response with `read("none")`. If
205
+ * creating the `TransportResponse` fails, release the native response.
176
206
  *
177
207
  * @example
178
208
  * ```ts
@@ -193,4 +223,4 @@ interface TransportResponse<Responses extends object = ResponseKindMap, Metadata
193
223
  */
194
224
  type Transport<Requests extends object = RequestKindMap, Responses extends object = ResponseKindMap, Options = object, Metadata extends object = never> = (request: TransportRequest<Requests, Responses, Options>) => Promise<TransportResponse<Responses, Metadata>>;
195
225
  type AnyTransport = Transport<any, {}, any, any>;
196
- export { Transport as _, HeaderInput as a, MultipartFile as c, RequestFields as d, RequestKindMap as f, StandardSchemaV1 as g, StandardIssue as h, Fields as i, MultipartInput as l, ResponseKindMap as m, CoreOptions as n, HeaderValue as o, ResponseHeaders as p, FieldScalar as r, JsonValue as s, AnyTransport as t, QueryInput as u, TransportRequest as v, TransportResponse as y };
226
+ export { Transport as _, Fields as a, MultipartFile as c, RequestFields as d, RequestKindMap as f, StandardSchemaV1 as g, StandardIssue as h, FieldScalar as i, MultipartInput as l, ResponseKindMap as m, CommonOptions as n, HeaderInput as o, ResponseHeaders as p, CoreOptions as r, JsonValue as s, AnyTransport as t, QueryInput as u, TransportRequest as v, TransportResponse as y };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dlenroc/typed-client",
3
- "version": "0.1.0",
3
+ "version": "0.3.1",
4
4
  "description": "Contract-first typed HTTP client for Fetch, Playwright and k6",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -1,138 +0,0 @@
1
- // src/shared/fields.ts
2
- function forEachField(fields, emit) {
3
- if (Array.isArray(fields)) {
4
- for (let i = 0; i < fields.length; i++) {
5
- const pair = fields[i];
6
- emit(pair[0], pair[1]);
7
- }
8
- return;
9
- }
10
- for (const name in fields) {
11
- const value = fields[name];
12
- if (Array.isArray(value)) for (let i = 0; i < value.length; i++) emit(name, value[i]);
13
- else emit(name, value);
14
- }
15
- }
16
- const formEscapes = /[!'()~]/g;
17
- function escapeFormCharacter(char) {
18
- return "%" + char.charCodeAt(0).toString(16).toUpperCase();
19
- }
20
- function encodeFormValue(value) {
21
- return encodeURIComponent(value).replace(formEscapes, escapeFormCharacter).replaceAll("%20", "+");
22
- }
23
- function asSearchParams(fields) {
24
- if (fields instanceof URLSearchParams) return fields;
25
- const params = new URLSearchParams();
26
- forEachField(fields, (name, value) => {
27
- if (value !== void 0) params.append(name, value === null ? "" : String(value));
28
- });
29
- return params;
30
- }
31
- function encodeFields(fields) {
32
- if (typeof fields === "string") return fields;
33
- if (typeof URLSearchParams !== "undefined") return asSearchParams(fields).toString();
34
- const items = [];
35
- forEachField(fields, (name, value) => {
36
- if (value !== void 0) items.push(`${encodeFormValue(name)}=${encodeFormValue(value === null ? "" : String(value))}`);
37
- });
38
- return items.join("&");
39
- }
40
- // src/shared/url.ts
41
- function appendQuery(url, query) {
42
- if (query === void 0) return url;
43
- const queryString = encodeFields(query);
44
- if (queryString === "") return url;
45
- const fragmentIndex = url.indexOf("#");
46
- const prefix = fragmentIndex < 0 ? url : url.slice(0, fragmentIndex);
47
- const fragment = fragmentIndex < 0 ? "" : url.slice(fragmentIndex);
48
- return prefix + (!prefix.includes("?") ? "?" : prefix.endsWith("?") || prefix.endsWith("&") ? "" : "&") + queryString + fragment;
49
- }
50
- function createUrlResolver(baseUrl) {
51
- if (baseUrl === void 0) return (path) => path;
52
- const prefix = baseUrl.replace(/\/+$/, "");
53
- return (path) => {
54
- if (path.charCodeAt(0) === 47) return path.charCodeAt(1) === 47 ? path : prefix + path;
55
- return /^[A-Za-z][A-Za-z0-9+.-]*:\/\//.test(path) ? path : prefix + "/" + path;
56
- };
57
- }
58
- // src/core/errors.ts
59
- function errorMessage(failure) {
60
- switch (failure.code) {
61
- case "request-input": return "Invalid call input";
62
- case "request-url": return "Request URL construction failed";
63
- case "request-prepare": return "Request preparation failed";
64
- case "transport": return "Transport failed to return a response";
65
- case "response-cleanup": return `Response cleanup failed (status ${failure.status})`;
66
- case "status": return `Unexpected status ${failure.status}; expected ${failure.expectedStatuses.join(", ")}`;
67
- case "response-decode": return `Cannot decode ${failure.kind} response (status ${failure.status})`;
68
- case "request-schema":
69
- case "response-schema": {
70
- const origin = failure.code === "request-schema" ? "Request" : "Response";
71
- const reason = failure.reason === "issues" ? `reported ${failure.issues.length} issue${failure.issues.length === 1 ? "" : "s"}` : "threw";
72
- const status = failure.code === "response-schema" ? ` (status ${failure.status})` : "";
73
- return `${origin} ${failure.field} schema ${reason}${status}`;
74
- }
75
- }
76
- }
77
- var ClientErrorInstance = class extends Error {
78
- url;
79
- meta;
80
- constructor(options) {
81
- super(errorMessage(options), options.cause === void 0 ? void 0 : { cause: options.cause });
82
- Object.assign(this, options);
83
- this.name = "ClientError";
84
- this.url = options.url;
85
- this.meta = options.meta ?? {};
86
- }
87
- };
88
- /**
89
- * Narrow by `code` to read failure-specific fields.
90
- *
91
- * @remarks
92
- * `cause` holds the underlying failure and `cleanupError` holds a
93
- * secondary cleanup failure. Diagnostic fields such as `code` and
94
- * `meta` are enumerable. Read `message` and `cause` explicitly for JSON.
95
- *
96
- * @example
97
- * ```ts
98
- * if (error instanceof ClientError && error.code === "status") {
99
- * console.log(error.status, error.expectedStatuses);
100
- * }
101
- * ```
102
- *
103
- * @example
104
- * ```ts
105
- * throw new ClientError({
106
- * code: "transport", method: "GET", cause,
107
- * });
108
- * ```
109
- */
110
- const ClientError = ClientErrorInstance;
111
- var RequestPreparationError = class extends Error {
112
- constructor(message, options) {
113
- super(message, options);
114
- this.name = "RequestPreparationError";
115
- }
116
- };
117
- var ResponseCleanupError = class extends Error {
118
- constructor(cause) {
119
- super("Failed to release transport response resources", { cause });
120
- this.name = "ResponseCleanupError";
121
- }
122
- };
123
- var FailureWithCleanupError = class extends Error {
124
- cleanupError;
125
- constructor(cause, cleanupError) {
126
- super("Operation and response cleanup failed", { cause });
127
- this.cleanupError = cleanupError;
128
- this.name = "FailureWithCleanupError";
129
- }
130
- };
131
- var TransportFailure = class extends Error {
132
- url;
133
- constructor(url, cause) {
134
- super("Transport request failed", { cause });
135
- this.url = url;
136
- }
137
- };
138
- export { TransportFailure as a, asSearchParams as c, ResponseCleanupError as i, encodeFields as l, FailureWithCleanupError as n, appendQuery as o, RequestPreparationError as r, createUrlResolver as s, ClientError as t, forEachField as u };