@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/index.js CHANGED
@@ -1,22 +1,21 @@
1
- import { a as TransportFailure, i as ResponseCleanupError, n as FailureWithCleanupError, o as appendQuery, r as RequestPreparationError, t as ClientError } from "./errors-D1bIeOq9.js";
1
+ import { a as transportError, i as preserveCleanupError, n as FailureWithCleanupError, o as appendQuery, r as ResponseCleanupError, t as ClientError } from "./errors-25xWqgvt.js";
2
2
  // src/core/endpoint.ts
3
3
  function compilePath(url) {
4
4
  const suffixStart = url.search(/[?#]/);
5
- const pathnameEnd = suffixStart < 0 ? url.length : suffixStart;
5
+ const path = suffixStart < 0 ? url : url.slice(0, suffixStart);
6
6
  const names = [];
7
7
  const parts = [];
8
- let segmentStart = 0;
9
8
  let literalStart = 0;
10
- while (segmentStart < pathnameEnd) {
11
- const slash = url.indexOf("/", segmentStart);
12
- const segmentEnd = slash < 0 || slash >= pathnameEnd ? pathnameEnd : slash;
13
- if (url[segmentStart] === ":" && segmentStart + 1 < segmentEnd) {
14
- parts.push(url.slice(literalStart, segmentStart));
15
- names.push(url.slice(segmentStart + 1, segmentEnd));
16
- literalStart = segmentEnd;
9
+ let open = path.indexOf("{");
10
+ while (open >= 0) {
11
+ const close = path.indexOf("}", open + 1);
12
+ if (close < 0) break;
13
+ if (close > open + 1) {
14
+ parts.push(url.slice(literalStart, open));
15
+ names.push(url.slice(open + 1, close));
16
+ literalStart = close + 1;
17
17
  }
18
- if (segmentEnd === pathnameEnd) break;
19
- segmentStart = segmentEnd + 1;
18
+ open = path.indexOf("{", close + 1);
20
19
  }
21
20
  if (names.length === 0) return url;
22
21
  parts.push(url.slice(literalStart));
@@ -42,7 +41,7 @@ function type() {
42
41
  return typeMarker;
43
42
  }
44
43
  function executableSchema(input) {
45
- return input !== null && typeof input === "object" && "~standard" in input ? input : void 0;
44
+ return input?.["~standard"] === void 0 ? void 0 : input;
46
45
  }
47
46
  function normalizeBody(input) {
48
47
  if (typeof input === "string") return {
@@ -70,7 +69,7 @@ function endpoint(url, definition = {}) {
70
69
  const kinds = /* @__PURE__ */ new Set();
71
70
  for (const status in declaredResponses) {
72
71
  const declared = declaredResponses[status];
73
- const descriptor = declared !== null && typeof declared === "object" && declared !== typeMarker && !("~standard" in declared) && "body" in declared ? declared : void 0;
72
+ const descriptor = declared !== null && typeof declared === "object" && declared !== typeMarker && executableSchema(declared) === void 0 && "body" in declared ? declared : void 0;
74
73
  const body = normalizeBody(descriptor ? descriptor.body : declared);
75
74
  responses[status] = {
76
75
  kind: body.kind,
@@ -94,27 +93,9 @@ function endpoint(url, definition = {}) {
94
93
  }
95
94
  // src/core/client.ts
96
95
  const ONLY_NONE = ["none"];
97
- function schemaError(origin, field, context, failure, response) {
98
- const details = "issues" in failure ? {
99
- reason: "issues",
100
- issues: failure.issues
101
- } : {
102
- reason: "exception",
103
- cause: failure.cause
104
- };
105
- return new ClientError(origin === "request" ? {
106
- ...context,
107
- ...details,
108
- code: "request-schema",
109
- field
110
- } : {
111
- ...context,
112
- ...details,
113
- code: "response-schema",
114
- field,
115
- status: response.status,
116
- headers: response.headers
117
- });
96
+ function schemaError(method, url, meta, status, schema, issues, cause) {
97
+ const outcome = issues === void 0 ? "threw" : `reported ${issues.length} issue${issues.length === 1 ? "" : "s"}`;
98
+ return status === void 0 ? new ClientError("request", `Request ${schema} schema ${outcome}`, method, url, meta, void 0, schema, issues, cause) : new ClientError("response", `Response ${schema} schema ${outcome} (status ${status})`, method, url, meta, status, schema, issues, cause);
118
99
  }
119
100
  function selectResponseKinds(endpoint, expectation, discard) {
120
101
  if (discard) return ONLY_NONE;
@@ -122,36 +103,28 @@ function selectResponseKinds(endpoint, expectation, discard) {
122
103
  if (typeof expectation === "number") return endpoint.responses[expectation]?.responseKinds ?? ONLY_NONE;
123
104
  if (expectation.length === 1) return endpoint.responses[expectation[0]]?.responseKinds ?? ONLY_NONE;
124
105
  const kinds = /* @__PURE__ */ new Set();
125
- for (const status of expectation) kinds.add(endpoint.responses[status]?.kind ?? "none");
106
+ for (let i = 0; i < expectation.length; i++) {
107
+ const status = expectation[i];
108
+ kinds.add(endpoint.responses[status]?.kind ?? "none");
109
+ }
126
110
  return [...kinds];
127
111
  }
128
112
  async function rejectResponse(handle, primary, bodyWasRead = false) {
129
113
  try {
130
- if (handle.discard) await handle.discard();
131
- else if (!bodyWasRead) await handle.read("none");
114
+ if (!bodyWasRead) await handle.read("none");
115
+ else if (handle.discard) await handle.discard();
132
116
  } catch (cleanupError) {
133
117
  primary.cleanupError = cleanupError;
134
118
  }
135
119
  throw primary;
136
120
  }
137
- function preserveCleanupError(error, failure) {
138
- if (failure !== null && (typeof failure === "object" || typeof failure === "function") && "cleanupError" in failure) error.cleanupError = failure.cleanupError;
139
- return error;
140
- }
141
121
  async function invoke(endpoint, transport, input) {
142
122
  const unchecked = input?.unchecked === true;
143
123
  const discard = input?.discard === true;
144
124
  const expectedStatus = input?.status;
145
125
  const method = unchecked ? input?.method ?? endpoint.method : endpoint.method;
146
- const context = {
147
- method,
148
- meta: endpoint.meta
149
- };
150
- if (Array.isArray(expectedStatus) && expectedStatus.length === 0) throw new ClientError({
151
- ...context,
152
- code: "request-input",
153
- cause: /* @__PURE__ */ new TypeError("status must not be empty")
154
- });
126
+ const meta = endpoint.meta;
127
+ if (Array.isArray(expectedStatus) && expectedStatus.length === 0) throw new ClientError("request", "Invalid call input", method, void 0, meta, void 0, void 0, void 0, /* @__PURE__ */ new TypeError("status must not be empty"));
155
128
  let path = input?.path;
156
129
  let query = input?.query;
157
130
  let headers = input?.headers;
@@ -163,9 +136,9 @@ async function invoke(endpoint, transport, input) {
163
136
  result = endpoint.pathSchema["~standard"].validate(path);
164
137
  if ("then" in result) result = await result;
165
138
  } catch (cause) {
166
- throw schemaError("request", "path", context, { cause });
139
+ throw schemaError(method, void 0, meta, void 0, "path", void 0, cause);
167
140
  }
168
- if (result.issues) throw schemaError("request", "path", context, { issues: result.issues });
141
+ if (result.issues) throw schemaError(method, void 0, meta, void 0, "path", result.issues, void 0);
169
142
  path = result.value;
170
143
  }
171
144
  if (endpoint.querySchema !== void 0) {
@@ -174,9 +147,9 @@ async function invoke(endpoint, transport, input) {
174
147
  result = endpoint.querySchema["~standard"].validate(query);
175
148
  if ("then" in result) result = await result;
176
149
  } catch (cause) {
177
- throw schemaError("request", "query", context, { cause });
150
+ throw schemaError(method, void 0, meta, void 0, "query", void 0, cause);
178
151
  }
179
- if (result.issues) throw schemaError("request", "query", context, { issues: result.issues });
152
+ if (result.issues) throw schemaError(method, void 0, meta, void 0, "query", result.issues, void 0);
180
153
  query = result.value;
181
154
  }
182
155
  if (endpoint.headersSchema !== void 0) {
@@ -185,9 +158,9 @@ async function invoke(endpoint, transport, input) {
185
158
  result = endpoint.headersSchema["~standard"].validate(headers);
186
159
  if ("then" in result) result = await result;
187
160
  } catch (cause) {
188
- throw schemaError("request", "headers", context, { cause });
161
+ throw schemaError(method, void 0, meta, void 0, "headers", void 0, cause);
189
162
  }
190
- if (result.issues) throw schemaError("request", "headers", context, { issues: result.issues });
163
+ if (result.issues) throw schemaError(method, void 0, meta, void 0, "headers", result.issues, void 0);
191
164
  headers = result.value;
192
165
  }
193
166
  if (endpoint.body.schema !== void 0) {
@@ -196,9 +169,9 @@ async function invoke(endpoint, transport, input) {
196
169
  result = endpoint.body.schema["~standard"].validate(body);
197
170
  if ("then" in result) result = await result;
198
171
  } catch (cause) {
199
- throw schemaError("request", "body", context, { cause });
172
+ throw schemaError(method, void 0, meta, void 0, "body", void 0, cause);
200
173
  }
201
- if (result.issues) throw schemaError("request", "body", context, { issues: result.issues });
174
+ if (result.issues) throw schemaError(method, void 0, meta, void 0, "body", result.issues, void 0);
202
175
  body = result.value;
203
176
  }
204
177
  }
@@ -206,11 +179,7 @@ async function invoke(endpoint, transport, input) {
206
179
  try {
207
180
  url = appendQuery(unchecked && typeof path === "string" ? path : renderPath(endpoint.path, path), query);
208
181
  } catch (cause) {
209
- throw new ClientError({
210
- ...context,
211
- code: "request-url",
212
- cause
213
- });
182
+ throw new ClientError("request", "Cannot build request URL", method, void 0, meta, void 0, void 0, void 0, cause);
214
183
  }
215
184
  const bodyKind = unchecked ? input?.bodyKind ?? endpoint.body.kind : endpoint.body.kind;
216
185
  const responseKinds = selectResponseKinds(endpoint, expectedStatus, discard);
@@ -221,38 +190,22 @@ async function invoke(endpoint, transport, input) {
221
190
  bodyKind,
222
191
  body,
223
192
  responseKinds,
224
- meta: endpoint.meta,
193
+ meta,
225
194
  input
226
195
  };
227
196
  let handle;
228
197
  try {
229
198
  handle = await transport(transportRequest);
230
199
  } catch (failure) {
231
- context.url = failure instanceof TransportFailure ? failure.url : transportRequest.url;
232
- const attempt = failure instanceof TransportFailure ? failure.cause : failure;
233
- const cause = attempt instanceof FailureWithCleanupError ? attempt.cause : attempt;
234
- throw preserveCleanupError(cause instanceof RequestPreparationError ? new ClientError({
235
- ...context,
236
- code: "request-prepare",
237
- cause
238
- }) : new ClientError({
239
- ...context,
240
- code: "transport",
241
- cause
242
- }), attempt);
200
+ if (failure instanceof ClientError && failure.meta === meta) throw failure;
201
+ throw transportError(true, method, transportRequest.url, meta, failure);
243
202
  }
244
- context.url = handle.url;
203
+ const responseUrl = handle.url;
245
204
  const status = handle.status;
246
205
  const responseSpec = endpoint.responses[status];
247
206
  if (!(expectedStatus === void 0 ? responseSpec !== void 0 : typeof expectedStatus === "number" ? status === expectedStatus : expectedStatus.includes(status))) {
248
- const expectedStatuses = expectedStatus === void 0 ? Object.keys(endpoint.responses).map(Number) : typeof expectedStatus === "number" ? [expectedStatus] : expectedStatus;
249
- return rejectResponse(handle, new ClientError({
250
- ...context,
251
- code: "status",
252
- status,
253
- expectedStatuses,
254
- headers: handle.headers
255
- }));
207
+ const expected = expectedStatus === void 0 ? Object.keys(endpoint.responses).join(", ") : typeof expectedStatus === "number" ? expectedStatus : expectedStatus.join(", ");
208
+ return rejectResponse(handle, new ClientError("status", `Unexpected status ${status} (expected ${expected})`, method, responseUrl, meta, status, void 0, void 0, void 0));
256
209
  }
257
210
  let responseHeaders = handle.headers;
258
211
  if (responseSpec?.headersSchema) {
@@ -261,9 +214,9 @@ async function invoke(endpoint, transport, input) {
261
214
  result = responseSpec.headersSchema["~standard"].validate(responseHeaders);
262
215
  if ("then" in result) result = await result;
263
216
  } catch (cause) {
264
- return rejectResponse(handle, schemaError("response", "headers", context, { cause }, handle));
217
+ return rejectResponse(handle, schemaError(method, responseUrl, meta, status, "headers", void 0, cause));
265
218
  }
266
- if (result.issues) return rejectResponse(handle, schemaError("response", "headers", context, { issues: result.issues }, handle));
219
+ if (result.issues) return rejectResponse(handle, schemaError(method, responseUrl, meta, status, "headers", result.issues, void 0));
267
220
  responseHeaders = result.value;
268
221
  }
269
222
  const kind = discard || responseSpec === void 0 ? "none" : responseSpec.kind;
@@ -273,21 +226,8 @@ async function invoke(endpoint, transport, input) {
273
226
  } catch (failure) {
274
227
  const cause = failure instanceof FailureWithCleanupError ? failure.cause : failure;
275
228
  const cleanupFailed = cause instanceof ResponseCleanupError;
276
- const diagnostics = {
277
- ...context,
278
- status,
279
- headers: handle.headers
280
- };
281
- throw preserveCleanupError(kind === "none" || cleanupFailed ? new ClientError({
282
- ...diagnostics,
283
- code: "response-cleanup",
284
- cause: cleanupFailed ? cause.cause : cause
285
- }) : new ClientError({
286
- ...diagnostics,
287
- code: "response-decode",
288
- kind,
289
- cause
290
- }), failure);
229
+ const wrapped = kind === "none" || cleanupFailed ? new ClientError("transport", `Cannot release response (status ${status})`, method, responseUrl, meta, status, void 0, void 0, cleanupFailed ? cause.cause : cause) : new ClientError("response", `Cannot decode ${kind} response (status ${status})`, method, responseUrl, meta, status, void 0, void 0, cause);
230
+ throw preserveCleanupError(wrapped, failure);
291
231
  }
292
232
  if (!discard && responseSpec?.bodySchema !== void 0) {
293
233
  let result;
@@ -295,20 +235,20 @@ async function invoke(endpoint, transport, input) {
295
235
  result = responseSpec.bodySchema["~standard"].validate(responseBody);
296
236
  if ("then" in result) result = await result;
297
237
  } catch (cause) {
298
- return rejectResponse(handle, schemaError("response", "body", context, { cause }, handle), true);
238
+ return rejectResponse(handle, schemaError(method, responseUrl, meta, status, "body", void 0, cause), true);
299
239
  }
300
- if (result.issues) return rejectResponse(handle, schemaError("response", "body", context, { issues: result.issues }, handle), true);
240
+ if (result.issues) return rejectResponse(handle, schemaError(method, responseUrl, meta, status, "body", result.issues, void 0), true);
301
241
  responseBody = result.value;
302
242
  }
303
243
  if (handle.transport === void 0) return {
304
244
  status,
305
- url: handle.url,
245
+ url: responseUrl,
306
246
  headers: responseHeaders,
307
247
  body: responseBody
308
248
  };
309
249
  return {
310
250
  status,
311
- url: handle.url,
251
+ url: responseUrl,
312
252
  headers: responseHeaders,
313
253
  body: responseBody,
314
254
  transport: handle.transport
@@ -321,7 +261,11 @@ function bind(contract, transport) {
321
261
  if (typeof endpoint?.method === "string") return (input) => invoke(endpoint, adapter, input);
322
262
  const group = {};
323
263
  const entries = node;
324
- for (const key of Object.keys(entries)) group[key] = visit(entries[key]);
264
+ const keys = Object.keys(entries);
265
+ for (let i = 0; i < keys.length; i++) {
266
+ const key = keys[i];
267
+ group[key] = visit(entries[key]);
268
+ }
325
269
  return group;
326
270
  }
327
271
  return visit(contract);
@@ -329,13 +273,16 @@ function bind(contract, transport) {
329
273
  // src/index.ts
330
274
  const c = {
331
275
  /**
332
- * Use a full `:name` segment for a required path parameter.
276
+ * Declare an HTTP endpoint with its request and response types.
333
277
  *
334
278
  * @defaultValue GET with an optional JSON body.
335
279
  *
336
280
  * @remarks
337
- * Path values are URL-escaped.
338
- * With an empty or omitted response map, pass `status` on each call.
281
+ * Each `{name}` before `?` or `#` is a required path parameter. A
282
+ * parameter can be part of a segment, for example `/files/{name}.json`
283
+ * or `/jobs/{id}:cancel`. `{}` is literal text. The client escapes path
284
+ * values with `encodeURIComponent`. If there are no declared responses,
285
+ * pass `status` on each call.
339
286
  *
340
287
  * @example
341
288
  * ```ts
@@ -350,7 +297,8 @@ const c = {
350
297
  */
351
298
  endpoint,
352
299
  /**
353
- * Supply a type without runtime validation. A bare body hint uses JSON.
300
+ * Supply a type without runtime validation. As a body declaration, it
301
+ * selects JSON.
354
302
  *
355
303
  * @see {@link https://standardschema.dev/ | Standard Schema} for validation.
356
304
  */
@@ -359,7 +307,7 @@ const c = {
359
307
  * Bind an endpoint to get a callable function. Groups keep their keys.
360
308
  *
361
309
  * @remarks
362
- * Import an adapter from `/fetch`, `/playwright`, or `/k6`.
310
+ * Import a transport from `/fetch`, `/playwright`, or `/k6`.
363
311
  * See {@link Transport} to implement or wrap one.
364
312
  *
365
313
  * @example
package/dist/k6.d.ts CHANGED
@@ -1,25 +1,57 @@
1
- import { _ as Transport, c as MultipartFile, f as RequestKindMap, i as Fields, m as ResponseKindMap, r as FieldScalar } from "./types-Cq8XAc1z.js";
1
+ import { _ as Transport, a as Fields, c as MultipartFile, f as RequestKindMap, i as FieldScalar, m as ResponseKindMap, n as CommonOptions } from "./types-XCe4DTv4.js";
2
2
  import { FileData, Params, Response } from "k6/http";
3
3
  interface K6RequestKinds extends Omit<RequestKindMap, "multipart"> {
4
4
  readonly multipart: Fields<FieldScalar | MultipartFile | FileData>;
5
5
  }
6
6
  type K6Http = Pick<typeof import("k6/http"), "asyncRequest" | "file">;
7
+ /** A cookie that k6 parsed from `Set-Cookie`, with the k6 field names. */
8
+ interface K6Cookie {
9
+ readonly name: string;
10
+ readonly value: string;
11
+ readonly domain: string;
12
+ readonly path: string;
13
+ readonly http_only: boolean;
14
+ readonly secure: boolean;
15
+ readonly max_age: number;
16
+ readonly expires: number;
17
+ }
18
+ /**
19
+ * The k6 response as k6 gives it. `@types/k6` names two cookie fields
20
+ * `httpOnly` and `maxAge`, and its `tls_cipher_suite` type has no `""`.
21
+ */
22
+ type K6Response = Omit<Response, "cookies" | "tls_cipher_suite"> & {
23
+ readonly cookies: Readonly<Record<string, readonly K6Cookie[]>>;
24
+ readonly tls_cipher_suite: Response["tls_cipher_suite"] | "";
25
+ };
7
26
  interface K6ResponseMetadata {
8
- readonly timings: Response["timings"];
9
- readonly proto: Response["proto"];
10
- readonly remote_ip: Response["remote_ip"];
11
- readonly error: Response["error"];
12
- readonly error_code: Response["error_code"];
27
+ /** Parsed `Set-Cookie` values by cookie name. */
28
+ readonly cookies: K6Response["cookies"];
29
+ readonly timings: K6Response["timings"];
30
+ readonly proto: K6Response["proto"];
31
+ readonly remote_ip: K6Response["remote_ip"];
32
+ readonly remote_port: K6Response["remote_port"];
33
+ /** The TLS version, or `""` if the connection does not use TLS. */
34
+ readonly tls_version: K6Response["tls_version"];
35
+ /** The TLS cipher suite, or `""` if the connection does not use TLS. */
36
+ readonly tls_cipher_suite: K6Response["tls_cipher_suite"];
37
+ readonly error: K6Response["error"];
38
+ readonly error_code: K6Response["error_code"];
13
39
  }
14
- declare const NATIVE_OPTION_KEYS: readonly ["cookies", "timeout", "redirects", "auth", "compression", "tags", "jar", "responseCallback"];
15
- type K6NativeOptions = Pick<Params, (typeof NATIVE_OPTION_KEYS)[number]>;
40
+ type K6NativeOptions = CommonOptions & {
41
+ /**
42
+ * Passed to k6 as params. `redirects` here overrides `follow`.
43
+ * `timeout` here overrides `timeout`.
44
+ */
45
+ readonly transport?: Omit<Params, "headers" | "responseType">;
46
+ };
16
47
  /**
17
- * Capture response bodies according to the expected response kinds.
48
+ * Send requests with `k6/http`.
18
49
  *
19
50
  * @remarks
20
- * Use k6 2.2 or later and add `@types/k6` for TypeScript. Bundle npm
21
- * imports for k6. Multipart fields accept `http.file()` values. Use a
22
- * single value per request header.
51
+ * Use k6 2.2 or later and add `@types/k6` for TypeScript. k6 does not
52
+ * load npm packages directly. Bundle the script first. The transport
53
+ * captures response bodies only for the expected response kinds.
54
+ * Multipart fields accept `http.file()` values.
23
55
  *
24
56
  * @example
25
57
  * ```ts
@@ -30,7 +62,7 @@ type K6NativeOptions = Pick<Params, (typeof NATIVE_OPTION_KEYS)[number]>;
30
62
  * const health = c.bind(c.endpoint("/health"), transport);
31
63
  *
32
64
  * export default async function () {
33
- * await health({ status: 204, tags: { name: "health" } });
65
+ * await health({ status: 204, transport: { tags: { name: "health" } } });
34
66
  * }
35
67
  * ```
36
68
  *