@dlenroc/typed-client 0.1.0 → 0.3.0

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.
@@ -1,19 +1,30 @@
1
- import { _ as Transport, f as RequestKindMap, m as ResponseKindMap } from "./types-Cq8XAc1z.js";
2
- import { APIRequestContext } from "playwright-core";
1
+ import { _ as Transport, f as RequestKindMap, m as ResponseKindMap, n as CommonOptions } from "./types-XCe4DTv4.js";
2
+ import { APIRequestContext, APIResponse } from "playwright-core";
3
3
  interface PlaywrightMetadata {
4
- readonly statusText: string;
4
+ readonly timing: ReturnType<APIResponse["timing"]>;
5
+ /**
6
+ * The server IP address and port, or `null` if Playwright does not know
7
+ * them.
8
+ */
9
+ readonly serverAddr: Awaited<ReturnType<APIResponse["serverAddr"]>>;
10
+ /**
11
+ * The TLS certificate and protocol, or `null` for a response that is not
12
+ * HTTPS.
13
+ */
14
+ readonly securityDetails: Awaited<ReturnType<APIResponse["securityDetails"]>>;
5
15
  }
6
16
  type PlaywrightContext = Pick<APIRequestContext, "fetch">;
7
17
  type PlaywrightFetchOptions = NonNullable<Parameters<APIRequestContext["fetch"]>[1]>;
8
- declare const NATIVE_OPTION_KEYS: readonly ["timeout", "maxRedirects", "maxRetries", "ignoreHTTPSErrors", "signal"];
9
- type PlaywrightNativeOptions = Pick<PlaywrightFetchOptions, (typeof NATIVE_OPTION_KEYS)[number]>;
18
+ type PlaywrightNativeOptions = CommonOptions & {
19
+ /** Passed to `fetch`. `maxRedirects` here overrides `follow`. */
20
+ readonly transport?: Pick<PlaywrightFetchOptions, "maxRedirects" | "maxRetries" | "ignoreHTTPSErrors" | "signal">;
21
+ };
10
22
  /**
11
- * Disposes each response after reading or discarding it.
23
+ * Send requests with Playwright and dispose each response after use.
12
24
  *
13
25
  * @remarks
14
- * Use Playwright 1.62 or later. Pass the test's `request` fixture or
15
- * create one with `request.newContext()`. Use a single value per
16
- * request header and keep Content-Type enabled when sending a body.
26
+ * Use Playwright 1.62 or later. Do not set `content-type: null` on a
27
+ * request with a body.
17
28
  *
18
29
  * @example
19
30
  * ```ts
@@ -37,7 +48,10 @@ type PlaywrightNativeOptions = Pick<PlaywrightFetchOptions, (typeof NATIVE_OPTIO
37
48
  * @see {@link https://playwright.dev/docs/api-testing | API testing}
38
49
  */
39
50
  export declare function playwrightTransport(config: {
40
- /** Dispose contexts you create. */
51
+ /**
52
+ * The `request` fixture or a context from `request.newContext()`.
53
+ * Dispose contexts you create.
54
+ */
41
55
  readonly context: PlaywrightContext;
42
56
  /** Relative endpoints append to this URL's path. */
43
57
  readonly baseUrl?: string;
@@ -1,14 +1,7 @@
1
- import { a as TransportFailure, i as ResponseCleanupError, l as encodeFields, n as FailureWithCleanupError, r as RequestPreparationError, s as createUrlResolver } from "./errors-D1bIeOq9.js";
2
- import { a as appendResponseHeader, c as asFormData, n as decodeUrlEncoded, s as prepareHeaders, t as decodeMultipart, u as encodeJson } from "./codec-BWlr5T5u.js";
1
+ import { a as transportError, l as encodeFields, n as FailureWithCleanupError, r as ResponseCleanupError, s as createUrlResolver } from "./errors-Dcje8BxZ.js";
2
+ import { a as appendResponseHeader, c as encodeJson, n as decodeUrlEncoded, o as prepareHeaders, s as asFormData, t as decodeMultipart } from "./codec-DpNVlh9j.js";
3
3
  import { Buffer } from "node:buffer";
4
4
  // src/transports/playwright.ts
5
- const NATIVE_OPTION_KEYS = [
6
- "timeout",
7
- "maxRedirects",
8
- "maxRetries",
9
- "ignoreHTTPSErrors",
10
- "signal"
11
- ];
12
5
  async function disposeAfterFailure(response, cause) {
13
6
  try {
14
7
  await response.dispose();
@@ -24,18 +17,27 @@ var PlaywrightResponseHandle = class PlaywrightResponseHandle {
24
17
  headers;
25
18
  transport;
26
19
  consumed = false;
27
- constructor(native, headers) {
20
+ constructor(native, headers, transport) {
28
21
  this.native = native;
29
22
  this.headers = headers;
30
23
  this.status = native.status();
31
24
  this.url = native.url();
32
- this.transport = { statusText: native.statusText() };
25
+ this.transport = transport;
33
26
  }
34
27
  static async create(native) {
35
28
  try {
36
29
  const headers = Object.create(null);
37
- for (const { name, value } of native.headersArray()) appendResponseHeader(headers, name, value);
38
- return new PlaywrightResponseHandle(native, headers);
30
+ const entries = native.headersArray();
31
+ for (let i = 0; i < entries.length; i++) {
32
+ const entry = entries[i];
33
+ appendResponseHeader(headers, entry.name, entry.value);
34
+ }
35
+ const transport = {
36
+ timing: native.timing(),
37
+ serverAddr: await native.serverAddr(),
38
+ securityDetails: await native.securityDetails()
39
+ };
40
+ return new PlaywrightResponseHandle(native, headers, transport);
39
41
  } catch (cause) {
40
42
  return disposeAfterFailure(native, cause);
41
43
  }
@@ -53,7 +55,7 @@ var PlaywrightResponseHandle = class PlaywrightResponseHandle {
53
55
  else if (kind === "multipart") {
54
56
  const bytes = await this.native.body();
55
57
  result = decodeMultipart(bytes, this.headers["content-type"]);
56
- } else throw new TypeError(`Unsupported Playwright response kind: ${String(kind)}`);
58
+ } else throw new TypeError(`Unsupported response kind: ${String(kind)}`);
57
59
  } catch (cause) {
58
60
  return disposeAfterFailure(this.native, cause);
59
61
  }
@@ -90,12 +92,11 @@ function playwrightMultipart(fields) {
90
92
  return result;
91
93
  }
92
94
  /**
93
- * Disposes each response after reading or discarding it.
95
+ * Send requests with Playwright and dispose each response after use.
94
96
  *
95
97
  * @remarks
96
- * Use Playwright 1.62 or later. Pass the test's `request` fixture or
97
- * create one with `request.newContext()`. Use a single value per
98
- * request header and keep Content-Type enabled when sending a body.
98
+ * Use Playwright 1.62 or later. Do not set `content-type: null` on a
99
+ * request with a body.
99
100
  *
100
101
  * @example
101
102
  * ```ts
@@ -122,56 +123,54 @@ function playwrightTransport(config) {
122
123
  const resolveUrl = createUrlResolver(config.baseUrl);
123
124
  return async (request) => {
124
125
  const url = resolveUrl(request.url);
126
+ let prepared = false;
125
127
  try {
128
+ const input = request.input;
129
+ const native = input?.transport;
126
130
  const options = {
131
+ ...native,
127
132
  method: request.method,
128
133
  failOnStatusCode: false
129
134
  };
130
- try {
131
- const body = request.body;
132
- if (body !== void 0) switch (request.bodyKind) {
133
- case "none": throw new RequestPreparationError("none request body kind cannot have a body");
134
- case "json":
135
- options.data = encodeJson(body);
136
- break;
137
- case "text":
138
- options.data = body;
139
- break;
140
- case "binary":
141
- options.data = asBuffer(body);
142
- break;
143
- case "urlencoded":
144
- options.data = encodeFields(body);
145
- break;
146
- case "multipart":
147
- options.multipart = playwrightMultipart(body);
148
- break;
149
- default: throw new RequestPreparationError(`Unsupported Playwright body kind: ${String(request.bodyKind)}`);
150
- }
151
- } catch (cause) {
152
- if (cause instanceof RequestPreparationError) throw cause;
153
- throw new RequestPreparationError("Failed to serialize Playwright request", { cause });
135
+ if (native !== void 0) {
136
+ delete options.headers;
137
+ delete options.data;
138
+ delete options.form;
139
+ delete options.multipart;
140
+ delete options.params;
154
141
  }
155
- if (request.headers !== void 0 || request.body !== void 0) {
156
- let suppressContentType = false;
157
- const preparedHeaders = prepareHeaders(request.headers, request.bodyKind, request.body !== void 0, (suppressed) => {
158
- suppressContentType = suppressed;
159
- });
160
- if (suppressContentType && request.body !== void 0) throw new RequestPreparationError("Playwright cannot suppress Content-Type for a request with a body");
161
- if (options.multipart !== void 0 && request.input?.unchecked !== true) delete preparedHeaders["content-type"];
162
- for (const name in preparedHeaders) if (typeof preparedHeaders[name] !== "string") throw new RequestPreparationError(`Playwright cannot preserve repeated request header: ${name}`);
163
- const contentType = preparedHeaders["content-type"];
164
- if (request.bodyKind !== "json" && typeof options.data === "string" && typeof contentType === "string" && contentType.split(";", 1)[0].trim().toLowerCase() === "application/json") options.data = Buffer.from(options.data);
165
- options.headers = preparedHeaders;
142
+ const body = request.body;
143
+ if (body !== void 0) switch (request.bodyKind) {
144
+ case "none": throw new TypeError("Request body kind none does not allow a body");
145
+ case "json":
146
+ options.data = Buffer.from(encodeJson(body));
147
+ break;
148
+ case "text":
149
+ options.data = Buffer.from(body);
150
+ break;
151
+ case "binary":
152
+ options.data = asBuffer(body);
153
+ break;
154
+ case "urlencoded":
155
+ options.data = Buffer.from(encodeFields(body));
156
+ break;
157
+ case "multipart":
158
+ options.multipart = playwrightMultipart(body);
159
+ break;
160
+ default: throw new TypeError(`Unsupported request body kind: ${String(request.bodyKind)}`);
166
161
  }
167
- for (const key of NATIVE_OPTION_KEYS) {
168
- const value = request.input?.[key];
169
- if (value !== void 0) options[key] = value;
162
+ if (request.headers !== void 0 || request.body !== void 0) {
163
+ const selected = prepareHeaders(request.headers, request.bodyKind, request.body !== void 0, input?.unchecked === true);
164
+ if (selected.contentTypeSuppressed && request.body !== void 0) throw new TypeError("Playwright cannot suppress Content-Type for a request with a body");
165
+ options.headers = selected.fields;
170
166
  }
167
+ if (options.maxRedirects === void 0 && input?.follow !== true) options.maxRedirects = 0;
168
+ if (input?.timeout !== void 0) options.timeout = input.timeout;
169
+ prepared = true;
171
170
  const response = await config.context.fetch(url, options);
172
171
  return await PlaywrightResponseHandle.create(response);
173
- } catch (cause) {
174
- throw new TransportFailure(url, cause);
172
+ } catch (failure) {
173
+ throw transportError(prepared, request.method, url, request.meta, failure);
175
174
  }
176
175
  };
177
176
  }
@@ -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.0",
4
4
  "description": "Contract-first typed HTTP client for Fetch, Playwright and k6",
5
5
  "license": "MIT",
6
6
  "repository": {