@autometa/http 1.4.20 → 2.0.0-rc.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.
Files changed (55) hide show
  1. package/README.md +107 -2
  2. package/dist/assertions/http-adapters.d.ts +35 -0
  3. package/dist/assertions/http-assertions-plugin.d.ts +16 -0
  4. package/dist/assertions/http-ensure.d.ts +42 -0
  5. package/dist/axios-transport.d.ts +22 -0
  6. package/dist/default-schema.d.ts +8 -0
  7. package/dist/fetch-transport.d.ts +21 -0
  8. package/dist/http-request.d.ts +109 -0
  9. package/dist/http-response.d.ts +77 -0
  10. package/dist/http.d.ts +300 -0
  11. package/dist/index.cjs +2076 -0
  12. package/dist/index.cjs.map +1 -0
  13. package/dist/index.d.ts +15 -1116
  14. package/dist/index.js +1727 -845
  15. package/dist/index.js.map +1 -1
  16. package/dist/plugins.d.ts +43 -0
  17. package/dist/request-meta.config.d.ts +56 -0
  18. package/dist/schema.map.d.ts +11 -0
  19. package/dist/transform-response.d.ts +1 -0
  20. package/dist/transport.d.ts +11 -0
  21. package/dist/types.d.ts +39 -0
  22. package/package.json +31 -31
  23. package/.eslintignore +0 -3
  24. package/.eslintrc.cjs +0 -4
  25. package/.turbo/turbo-lint$colon$fix.log +0 -4
  26. package/.turbo/turbo-prettify.log +0 -5
  27. package/.turbo/turbo-test.log +0 -120
  28. package/CHANGELOG.md +0 -335
  29. package/dist/esm/index.js +0 -1117
  30. package/dist/esm/index.js.map +0 -1
  31. package/dist/index.d.cts +0 -1116
  32. package/src/axios-client.ts +0 -35
  33. package/src/default-client-factory.axios.spec.ts +0 -9
  34. package/src/default-client-factory.other.spec.ts +0 -13
  35. package/src/default-client-factory.ts +0 -7
  36. package/src/default-schema.spec.ts +0 -74
  37. package/src/default-schema.ts +0 -127
  38. package/src/http-client.ts +0 -20
  39. package/src/http-request.spec.ts +0 -172
  40. package/src/http-request.ts +0 -201
  41. package/src/http-response.ts +0 -107
  42. package/src/http.spec.ts +0 -189
  43. package/src/http.ts +0 -907
  44. package/src/index.ts +0 -13
  45. package/src/node_modules/.vitest/deps/_metadata.json +0 -8
  46. package/src/node_modules/.vitest/deps/package.json +0 -3
  47. package/src/node_modules/.vitest/results.json +0 -1
  48. package/src/request-meta.config.spec.ts +0 -81
  49. package/src/request-meta.config.ts +0 -134
  50. package/src/request.config.ts +0 -34
  51. package/src/schema.map.spec.ts +0 -50
  52. package/src/schema.map.ts +0 -68
  53. package/src/transform-response.ts +0 -43
  54. package/src/types.ts +0 -37
  55. package/tsup.config.ts +0 -14
package/dist/esm/index.js DELETED
@@ -1,1117 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __decorateClass = (decorators, target, key, kind) => {
4
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
5
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
6
- if (decorator = decorators[i])
7
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
8
- if (kind && result)
9
- __defProp(target, key, result);
10
- return result;
11
- };
12
- var __accessCheck = (obj, member, msg) => {
13
- if (!member.has(obj))
14
- throw TypeError("Cannot " + msg);
15
- };
16
- var __privateGet = (obj, member, getter) => {
17
- __accessCheck(obj, member, "read from private field");
18
- return getter ? getter.call(obj) : member.get(obj);
19
- };
20
- var __privateAdd = (obj, member, value) => {
21
- if (member.has(obj))
22
- throw TypeError("Cannot add the same private member more than once");
23
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
24
- };
25
- var __privateSet = (obj, member, value, setter) => {
26
- __accessCheck(obj, member, "write to private field");
27
- setter ? setter.call(obj, value) : member.set(obj, value);
28
- return value;
29
- };
30
- var __privateMethod = (obj, member, method) => {
31
- __accessCheck(obj, member, "access private method");
32
- return method;
33
- };
34
-
35
- // src/http-response.ts
36
- var HTTPResponse = class _HTTPResponse {
37
- constructor() {
38
- this.headers = {};
39
- }
40
- static fromRaw(response) {
41
- const newResponse = new _HTTPResponse();
42
- Object.assign(newResponse, response);
43
- return response;
44
- }
45
- decompose(transformFnOrVal) {
46
- const value = getDecompositionValue(this.data, transformFnOrVal);
47
- return new HTTPResponseBuilder().status(this.status).statusText(this.statusText).headers(this.headers).request(this.request).data(value).build();
48
- }
49
- };
50
- function getDecompositionValue(data, transformFn) {
51
- return typeof transformFn === "function" ? transformFn(data) : transformFn;
52
- }
53
- var _response;
54
- var _HTTPResponseBuilder = class _HTTPResponseBuilder {
55
- constructor() {
56
- __privateAdd(this, _response, new HTTPResponse());
57
- }
58
- static create() {
59
- return new _HTTPResponseBuilder();
60
- }
61
- derive() {
62
- return _HTTPResponseBuilder.create().data(__privateGet(this, _response).data).headers(__privateGet(this, _response).headers).request(__privateGet(this, _response).request).status(__privateGet(this, _response).status).statusText(__privateGet(this, _response).statusText);
63
- }
64
- status(code) {
65
- __privateGet(this, _response).status = code;
66
- return this;
67
- }
68
- statusText(text) {
69
- __privateGet(this, _response).statusText = text;
70
- return this;
71
- }
72
- data(data) {
73
- __privateGet(this, _response).data = data;
74
- return this;
75
- }
76
- headers(dict) {
77
- __privateGet(this, _response).headers = dict;
78
- return this;
79
- }
80
- header(name, value) {
81
- __privateGet(this, _response).headers[name] = value;
82
- return this;
83
- }
84
- request(request) {
85
- __privateGet(this, _response).request = request;
86
- return this;
87
- }
88
- build() {
89
- return __privateGet(this, _response);
90
- }
91
- };
92
- _response = new WeakMap();
93
- var HTTPResponseBuilder = _HTTPResponseBuilder;
94
-
95
- // src/axios-client.ts
96
- import axios from "axios";
97
-
98
- // src/http-client.ts
99
- var defaultClient;
100
- var HTTPClient = class {
101
- static Use(client) {
102
- if (client) {
103
- defaultClient = client;
104
- }
105
- return function(target) {
106
- defaultClient = target;
107
- };
108
- }
109
- };
110
-
111
- // src/axios-client.ts
112
- var AxiosClient = class extends HTTPClient {
113
- async request(request, options) {
114
- const { baseUrl, route, params, headers, method, data } = request;
115
- const url = [baseUrl, ...route].join("/");
116
- const axiosRequest = {
117
- url,
118
- params,
119
- headers,
120
- method,
121
- data,
122
- validateStatus: function(status) {
123
- return status >= 0 && status < 600;
124
- },
125
- ...options
126
- };
127
- const response = await axios(axiosRequest);
128
- return HTTPResponseBuilder.create().status(response.status).statusText(response.statusText).data(response.data).headers(response.headers).request(request).build();
129
- }
130
- };
131
- AxiosClient = __decorateClass([
132
- HTTPClient.Use()
133
- ], AxiosClient);
134
-
135
- // src/http.ts
136
- import { Fixture, INJECTION_SCOPE } from "@autometa/injection";
137
-
138
- // src/default-client-factory.ts
139
- function defaultClientFactory() {
140
- const type = defaultClient;
141
- return new type();
142
- }
143
-
144
- // src/http-request.ts
145
- import { urlJoinP } from "url-join-ts";
146
- var HTTPRequest = class _HTTPRequest {
147
- constructor(config) {
148
- this.headers = {};
149
- this.params = {};
150
- this.route = [];
151
- Object.assign(this, config);
152
- }
153
- /**
154
- * Returns the full URL of the request, including the base url,
155
- * routes, and query parameters.
156
- *
157
- * ```ts
158
- * console.log(request.fullUrl())// https://example.com/foo?bar=baz?array=1,2,3
159
- * ```
160
- *
161
- * Note characters may be converted to escape codes. I.e (space => %20) and (comma => %2C)
162
- *
163
- * N.B this getter estimates what the url will be. The actual value
164
- * might be different depending on your underlying HTTPClient and
165
- * configuration. For example, query parameters might
166
- * use different array formats.
167
- */
168
- get fullUrl() {
169
- return urlJoinP(this.baseUrl, this.route, this.params);
170
- }
171
- /**
172
- * Returns a new independent copy of the request.
173
- */
174
- static derive(original) {
175
- const request = new _HTTPRequest();
176
- request.headers = { ...original.headers };
177
- request.params = { ...original.params };
178
- request.baseUrl = original.baseUrl;
179
- request.route = [...original.route];
180
- request.method = original.method;
181
- request.data = original.data;
182
- return request;
183
- }
184
- };
185
- var _request, _dynamicHeaders, _setDynamicHeaders, setDynamicHeaders_fn;
186
- var _HTTPRequestBuilder = class _HTTPRequestBuilder {
187
- constructor(request = () => new HTTPRequest()) {
188
- __privateAdd(this, _setDynamicHeaders);
189
- __privateAdd(this, _request, void 0);
190
- __privateAdd(this, _dynamicHeaders, /* @__PURE__ */ new Map());
191
- if (typeof request === "function") {
192
- __privateSet(this, _request, request());
193
- return;
194
- }
195
- __privateSet(this, _request, request);
196
- }
197
- static create() {
198
- return new _HTTPRequestBuilder();
199
- }
200
- get request() {
201
- return __privateGet(this, _request);
202
- }
203
- async resolveDynamicHeaders(request = __privateGet(this, _request)) {
204
- for (const [name, value] of __privateGet(this, _dynamicHeaders)) {
205
- try {
206
- if (!request.headers)
207
- request.headers = {};
208
- request.headers[name] = String(await value());
209
- } catch (e) {
210
- const cause = e;
211
- const msg = `Failed to resolve dynamic header "${name}":
212
- ${cause}`;
213
- throw new Error(msg);
214
- }
215
- }
216
- return this;
217
- }
218
- url(url) {
219
- __privateGet(this, _request).baseUrl = url;
220
- return this;
221
- }
222
- route(...route) {
223
- __privateGet(this, _request).route.push(...route);
224
- return this;
225
- }
226
- param(name, value) {
227
- if (Array.isArray(value)) {
228
- const asStr = value.flatMap(String);
229
- __privateGet(this, _request).params[name] = asStr;
230
- return this;
231
- }
232
- if (!Array.isArray(value) && typeof value === "object") {
233
- __privateGet(this, _request).params[name] = value;
234
- return this;
235
- }
236
- __privateGet(this, _request).params[name] = String(value);
237
- return this;
238
- }
239
- params(dict) {
240
- Object.assign(__privateGet(this, _request).params, dict);
241
- return this;
242
- }
243
- data(data) {
244
- __privateGet(this, _request).data = data;
245
- return this;
246
- }
247
- header(name, value, onArray = (value2) => value2.join(",")) {
248
- if (typeof value === "function") {
249
- if (__privateGet(this, _request).headers[name]) {
250
- delete __privateGet(this, _request).headers[name];
251
- }
252
- __privateGet(this, _dynamicHeaders).set(name, value);
253
- return this;
254
- }
255
- if (__privateGet(this, _dynamicHeaders).has(name)) {
256
- __privateGet(this, _dynamicHeaders).delete(name);
257
- }
258
- const val = Array.isArray(value) ? onArray(value) : String(value);
259
- __privateGet(this, _request).headers[name] = val;
260
- return this;
261
- }
262
- headers(dict) {
263
- Object.assign(__privateGet(this, _request).headers, dict);
264
- return this;
265
- }
266
- get() {
267
- return __privateGet(this, _request);
268
- }
269
- method(method) {
270
- __privateGet(this, _request).method = method;
271
- return this;
272
- }
273
- derive() {
274
- var _a;
275
- const request = HTTPRequest.derive(__privateGet(this, _request));
276
- return __privateMethod(_a = new _HTTPRequestBuilder(request), _setDynamicHeaders, setDynamicHeaders_fn).call(_a, __privateGet(this, _dynamicHeaders));
277
- }
278
- build() {
279
- return __privateGet(this, _request);
280
- }
281
- async buildAsync() {
282
- await this.resolveDynamicHeaders();
283
- return __privateGet(this, _request);
284
- }
285
- };
286
- _request = new WeakMap();
287
- _dynamicHeaders = new WeakMap();
288
- _setDynamicHeaders = new WeakSet();
289
- setDynamicHeaders_fn = function(headers) {
290
- __privateSet(this, _dynamicHeaders, new Map(headers));
291
- return this;
292
- };
293
- var HTTPRequestBuilder = _HTTPRequestBuilder;
294
-
295
- // src/schema.map.ts
296
- var _map;
297
- var _SchemaMap = class _SchemaMap {
298
- constructor(map) {
299
- __privateAdd(this, _map, void 0);
300
- if (map instanceof _SchemaMap) {
301
- __privateSet(this, _map, new Map(__privateGet(map, _map)));
302
- return;
303
- }
304
- __privateSet(this, _map, new Map(map));
305
- }
306
- derive() {
307
- return new _SchemaMap(__privateGet(this, _map));
308
- }
309
- registerStatus(parser, ...codes) {
310
- codes.forEach((code) => {
311
- if (__privateGet(this, _map).has(code)) {
312
- const msg = `Status code ${code} is already registered with a parser`;
313
- throw new Error(msg);
314
- }
315
- __privateGet(this, _map).set(code, parser);
316
- });
317
- }
318
- registerRange(parser, from, to) {
319
- for (let i = from; i <= to; i++) {
320
- if (__privateGet(this, _map).has(i)) {
321
- throw new Error(`Status code ${i} is already registered with a parser`);
322
- }
323
- __privateGet(this, _map).set(i, parser);
324
- }
325
- }
326
- validate(status, data, requireSchema) {
327
- const parser = this.getParser(status, requireSchema);
328
- if ("parse" in parser) {
329
- return parser.parse(data);
330
- }
331
- if ("validate" in parser) {
332
- return parser.validate(data);
333
- }
334
- try {
335
- return parser(data);
336
- } catch (e) {
337
- const msg = `Failed to schema parse response data for status code ${status} with data:
338
-
339
- ${JSON.stringify(data, null, 2)}}`;
340
- throw new Error(msg);
341
- }
342
- }
343
- getParser(status, requireSchema) {
344
- const parser = __privateGet(this, _map).get(status);
345
- if (!parser && requireSchema) {
346
- const msg = `No parser registered for status code ${status} but 'requireSchema' is true`;
347
- throw new Error(msg);
348
- }
349
- if (parser) {
350
- return parser;
351
- }
352
- return (data) => data;
353
- }
354
- toObject() {
355
- return Object.fromEntries(__privateGet(this, _map));
356
- }
357
- };
358
- _map = new WeakMap();
359
- var SchemaMap = _SchemaMap;
360
-
361
- // src/request-meta.config.ts
362
- var MetaConfig = class {
363
- constructor() {
364
- this.onSend = [];
365
- this.onReceive = [];
366
- this.options = {};
367
- }
368
- };
369
- var _schemaMap, _requireSchema, _allowPlainText, _onBeforeSend, _onAfterSend, _throwOnServerError, _options, _setOnSend, setOnSend_fn, _setOnReceive, setOnReceive_fn;
370
- var _MetaConfigBuilder = class _MetaConfigBuilder {
371
- constructor() {
372
- __privateAdd(this, _setOnSend);
373
- __privateAdd(this, _setOnReceive);
374
- __privateAdd(this, _schemaMap, new SchemaMap());
375
- __privateAdd(this, _requireSchema, false);
376
- __privateAdd(this, _allowPlainText, false);
377
- __privateAdd(this, _onBeforeSend, []);
378
- __privateAdd(this, _onAfterSend, []);
379
- __privateAdd(this, _throwOnServerError, false);
380
- __privateAdd(this, _options, {});
381
- }
382
- options(options) {
383
- __privateSet(this, _options, { ...options });
384
- return this;
385
- }
386
- schemaMap(map) {
387
- __privateSet(this, _schemaMap, map);
388
- return this;
389
- }
390
- schema(parser, ...args) {
391
- args.forEach((arg) => {
392
- if (typeof arg === "number") {
393
- __privateGet(this, _schemaMap).registerStatus(parser, arg);
394
- } else if (Array.isArray(arg)) {
395
- __privateGet(this, _schemaMap).registerStatus(parser, ...arg);
396
- } else {
397
- __privateGet(this, _schemaMap).registerRange(parser, arg.from, arg.to);
398
- }
399
- });
400
- return this;
401
- }
402
- requireSchema(value) {
403
- __privateSet(this, _requireSchema, value);
404
- return this;
405
- }
406
- allowPlainText(value) {
407
- __privateSet(this, _allowPlainText, value);
408
- return this;
409
- }
410
- onBeforeSend(description, hook) {
411
- __privateGet(this, _onBeforeSend).push([description, hook]);
412
- return this;
413
- }
414
- throwOnServerError(value) {
415
- __privateSet(this, _throwOnServerError, value);
416
- return this;
417
- }
418
- onReceiveResponse(description, hook) {
419
- __privateGet(this, _onAfterSend).push([description, hook]);
420
- return this;
421
- }
422
- build() {
423
- const config = new MetaConfig();
424
- config.schemas = __privateGet(this, _schemaMap).derive();
425
- config.requireSchema = __privateGet(this, _requireSchema);
426
- config.allowPlainText = __privateGet(this, _allowPlainText);
427
- config.onSend = __privateGet(this, _onBeforeSend);
428
- config.onReceive = __privateGet(this, _onAfterSend);
429
- config.options = __privateGet(this, _options);
430
- config.throwOnServerError = __privateGet(this, _throwOnServerError);
431
- return config;
432
- }
433
- derive() {
434
- var _a, _b;
435
- return __privateMethod(_b = __privateMethod(_a = new _MetaConfigBuilder().schemaMap(__privateGet(this, _schemaMap).derive()).requireSchema(__privateGet(this, _requireSchema)).allowPlainText(__privateGet(this, _allowPlainText)).throwOnServerError(__privateGet(this, _throwOnServerError)).options(__privateGet(this, _options)), _setOnSend, setOnSend_fn).call(_a, __privateGet(this, _onBeforeSend)), _setOnReceive, setOnReceive_fn).call(_b, __privateGet(this, _onAfterSend));
436
- }
437
- };
438
- _schemaMap = new WeakMap();
439
- _requireSchema = new WeakMap();
440
- _allowPlainText = new WeakMap();
441
- _onBeforeSend = new WeakMap();
442
- _onAfterSend = new WeakMap();
443
- _throwOnServerError = new WeakMap();
444
- _options = new WeakMap();
445
- _setOnSend = new WeakSet();
446
- setOnSend_fn = function(hooks) {
447
- __privateSet(this, _onBeforeSend, [...hooks]);
448
- return this;
449
- };
450
- _setOnReceive = new WeakSet();
451
- setOnReceive_fn = function(hooks) {
452
- __privateSet(this, _onAfterSend, [...hooks]);
453
- return this;
454
- };
455
- var MetaConfigBuilder = _MetaConfigBuilder;
456
-
457
- // src/transform-response.ts
458
- import { AutomationError } from "@autometa/errors";
459
- import isJson from "@stdlib/assert-is-json";
460
- import { highlight } from "cli-highlight";
461
- function transformResponse(allowPlainText, data) {
462
- if (data === null) {
463
- return null;
464
- }
465
- if (data === void 0) {
466
- return void 0;
467
- }
468
- if (data === "") {
469
- return data;
470
- }
471
- if (isJson(data)) {
472
- return JSON.parse(data);
473
- }
474
- if (typeof data === "string" && ["true", "false"].includes(data)) {
475
- return JSON.parse(data);
476
- }
477
- if (typeof data === "string" && /^\d*\.?\d+$/.test(data)) {
478
- return JSON.parse(data);
479
- }
480
- if (typeof data === "object") {
481
- return data;
482
- }
483
- if (allowPlainText) {
484
- return data;
485
- }
486
- const dataStr = typeof data === "string" ? data : JSON.stringify(data);
487
- const response = highlight(dataStr, { language: "html" });
488
- const message = [
489
- `Could not parse a response as json, and this request was not configured to allow plain text responses.`,
490
- `To allow plain text responses, use the 'allowPlainText' method on the HTTP client.`,
491
- "",
492
- response
493
- ];
494
- throw new AutomationError(message.join("\n"));
495
- }
496
-
497
- // src/http.ts
498
- import { AutomationError as AutomationError2 } from "@autometa/errors";
499
- var _request2, _metaConfig, _makeRequest, makeRequest_fn, _validateResponse, validateResponse_fn;
500
- var HTTP = class {
501
- constructor(client = defaultClientFactory(), builder = new HTTPRequestBuilder(), metaConfig = new MetaConfigBuilder()) {
502
- this.client = client;
503
- __privateAdd(this, _makeRequest);
504
- __privateAdd(this, _validateResponse);
505
- __privateAdd(this, _request2, void 0);
506
- __privateAdd(this, _metaConfig, void 0);
507
- __privateSet(this, _request2, builder);
508
- __privateSet(this, _metaConfig, metaConfig.derive());
509
- }
510
- static create(client = new AxiosClient(), builder = new HTTPRequestBuilder(), metaConfig = new MetaConfigBuilder()) {
511
- const derived = new HTTP(client, builder, metaConfig);
512
- return derived;
513
- }
514
- /**
515
- * Sets the base url of the request for this client, such as
516
- * `https://api.example.com`, and could include always-used routes like
517
- * the api version, such as `/v1` or `/api/v1` at the end.
518
- *
519
- * ```ts
520
- *
521
- * \@Fixture(INJECTION_SCOPE.TRANSIENT)
522
- * export abstract class BaseClient {
523
- * constructor(protected readonly http: HTTP) {
524
- * this.http.url("https://api.example.com");
525
- * }
526
- * }
527
- * ```
528
- * @param url
529
- * @returns
530
- */
531
- url(url) {
532
- __privateGet(this, _request2).url(url);
533
- return this;
534
- }
535
- sharedOptions(options) {
536
- __privateGet(this, _metaConfig).options(options);
537
- return this;
538
- }
539
- /**
540
- * If set to true, all requests derived from this client will require a schema be defined
541
- * matching any response status code. If set to false, a schema will still be used for validation
542
- * if defined, or the unadulterated original body will be returned if no schema matches.
543
- *
544
- * @param required Whether or not a schema is required for all responses.
545
- * @returns This instance of HTTP.
546
- */
547
- requireSchema(required) {
548
- __privateGet(this, _metaConfig).requireSchema(required);
549
- return this;
550
- }
551
- /**
552
- * If set to true, all requests derived from this client will allow plain text
553
- * responses. If set to false, plain text responses will throw an serialization error.
554
- *
555
- * Useful when an endpoint returns a HTML or plain text response. If the plain text
556
- * is the value of `true` or `false`, or a number, it will be parsed into the
557
- * appropriate type.
558
- *
559
- * This method is a shared chain method, and will return the same instance of HTTP.
560
- *
561
- * @param allow Whether or not plain text responses are allowed.
562
- * @returns This instance of HTTP.
563
- */
564
- sharedAllowPlainText(allow) {
565
- __privateGet(this, _metaConfig).allowPlainText(allow);
566
- return this;
567
- }
568
- /**
569
- * If set to true, all requests derived from this client will allow plain text
570
- * responses. If set to false, plain text responses will throw an serialization error.
571
- *
572
- * Useful when an endpoint returns a HTML or plain text response. If the plain text
573
- * is the value of `true` or `false`, or a number, it will be parsed into the
574
- * appropriate type.
575
- *
576
- * This method is a request chain method, and will return a new instance of HTTP.
577
- *
578
- * @param allow Whether or not plain text responses are allowed.
579
- * @returns A new child instance of HTTP derived from this one.
580
- */
581
- allowPlainText(allow) {
582
- return HTTP.create(
583
- this.client,
584
- __privateGet(this, _request2).derive(),
585
- __privateGet(this, _metaConfig).derive().allowPlainText(allow)
586
- );
587
- }
588
- /**
589
- * Attaches a route to the request, such as `/product` or `/user`. Subsequent calls
590
- * to this method will append the route to the existing route, such as `/product/1`.
591
- *
592
- * Numbers will be converted to strings automatically. Routes can be defined one
593
- * at a time or as a spread argument.
594
- *
595
- * ```ts
596
- * constructor(http: HTTP) {
597
- * super(http);
598
- * this.http.sharedRoute("user", id).get();
599
- * }
600
- *
601
- * // or
602
- *
603
- * constructor(http: HTTP) {
604
- * super(http);
605
- * this.http
606
- * .sharedRoute("user")
607
- * .sharedRoute(id)
608
- * .get();
609
- * }
610
- * ```
611
- *
612
- * This method is a shared chain method, and will return the same instance of HTTP. All
613
- * child clients will inherit the routes defined by this method. Useful to configure
614
- * in the constructor body.
615
- *
616
- * @param route A route or spread list of routes to append to the request.
617
- * @returns This instance of HTTP.
618
- */
619
- sharedRoute(...route) {
620
- __privateGet(this, _request2).route(...route.map((r) => r.toString()));
621
- return this;
622
- }
623
- /**
624
- * Attaches a route to the request, such as `/product` or `/user`. Subsequent calls
625
- * to this method will append the route to the existing route, such as `/product/1`.
626
- *
627
- * Numbers will be converted to strings automatically. Routes can be defined one
628
- * at a time or as a spread argument.
629
- *
630
- * ```ts
631
- * getUser(id: number) {
632
- * return this.http.route("user", id).get();
633
- * }
634
- *
635
- * // or
636
- *
637
- * getUser(id: number) {
638
- * return this.http
639
- * .route("user")
640
- * .route(id)
641
- * .get();
642
- * }
643
- * ```
644
- *
645
- * This method is a request chain method, and will return a new instance of HTTP, inheriting
646
- * any routes previously defined and appending the new route. Useful to configure
647
- * in class methods as part of finalizing a request.
648
- *
649
- * @param route A route or spread list of routes to append to the request.
650
- * @returns A new child instance of HTTP derived from this one.
651
- */
652
- route(...route) {
653
- const mapped = route.map((r) => String(r));
654
- return HTTP.create(
655
- this.client,
656
- __privateGet(this, _request2).derive().route(...mapped),
657
- __privateGet(this, _metaConfig).derive()
658
- );
659
- }
660
- sharedSchema(parser, ...args) {
661
- __privateGet(this, _metaConfig).schema(parser, ...args);
662
- return this;
663
- }
664
- schema(parser, ...args) {
665
- return HTTP.create(
666
- this.client,
667
- __privateGet(this, _request2).derive(),
668
- __privateGet(this, _metaConfig).derive().schema(parser, ...args)
669
- );
670
- }
671
- sharedParam(name, value) {
672
- __privateGet(this, _request2).param(name, value);
673
- return this;
674
- }
675
- /**
676
- * `onSend` is a pre-request hook which will be executed in order of definition
677
- * immediately before the request is sent. This hook can be used to analyze or
678
- * log the request state.
679
- *
680
- * ```ts
681
- *
682
- * \@Fixture(INJECTION_SCOPE.TRANSIENT)
683
- * export class UserController extends BaseController {
684
- * constructor(private readonly http: HTTP) {
685
- * super(http);
686
- * this.http
687
- * .sharedRoute("user")
688
- * .sharedOnSend("log request",
689
- * (request) => console.log(JSON.stringify(request, null, 2))
690
- * );
691
- * }
692
- * }
693
- * ```
694
- *
695
- * This method is a shared chain method, and will return the same instance of HTTP. All
696
- * child clients will inherit the onSend hooks defined by this method. Useful to configure
697
- * in the constructor body.
698
- *
699
- * @param description A description of the hook, used for debugging.
700
- * @param hook The hook to execute.
701
- * @returns This instance of HTTP.
702
- */
703
- sharedOnSend(description, hook) {
704
- __privateGet(this, _metaConfig).onBeforeSend(description, hook);
705
- return this;
706
- }
707
- /**
708
- * `onReceive` is a post-request hook which will be executed in order of definition
709
- * immediately after the response is received. This hook can be used to analyze or
710
- * log the response state.
711
- *
712
- * ```ts
713
- *
714
- * \@Fixture(INJECTION_SCOPE.TRANSIENT)
715
- * export class UserController extends BaseController {
716
- * constructor(private readonly http: HTTP) {
717
- * super(http);
718
- * this.http
719
- * .sharedRoute("user")
720
- * .sharedOnReceive("log response",
721
- * (response) => console.log(JSON.stringify(response, null, 2))
722
- * );
723
- * }
724
- * }
725
- * ```
726
- *
727
- * This method is a shared chain method, and will return the same instance of HTTP. All
728
- * child clients will inherit the onReceive hooks defined by this method. Useful to configure
729
- * in the constructor body.
730
- *
731
- * @param description A description of the hook, used for debugging.
732
- * @param hook The hook to execute.
733
- * @returns This instance of HTTP.
734
- */
735
- sharedOnReceive(description, hook) {
736
- __privateGet(this, _metaConfig).onReceiveResponse(description, hook);
737
- return this;
738
- }
739
- /**
740
- * Attaches a query string parameter object to the request. Query string
741
- * parameters are key-value pairs which are appended to the request url, such as
742
- * `https://api.example.com?name=John&age=30`.
743
- *
744
- * This method is a shared chain method, and will return the same instance of HTTP. All
745
- * child clients will inherit the query string parameters defined by this method. Useful to configure
746
- * in the constructor body.
747
- *
748
- * ```ts
749
- * constructor(http: HTTP) {
750
- * super(http);
751
- * this.http
752
- * .sharedParams({ 'is-test': "true" })
753
- * ```
754
- * @param name The name of the query string parameter.
755
- * @param value The value of the query string parameter.
756
- * @returns This instance of HTTP.
757
- */
758
- sharedParams(dict) {
759
- __privateGet(this, _request2).params(dict);
760
- return this;
761
- }
762
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
763
- param(name, ...value) {
764
- return HTTP.create(
765
- this.client,
766
- __privateGet(this, _request2).derive().param(name, value),
767
- __privateGet(this, _metaConfig).derive()
768
- );
769
- }
770
- /**
771
- * Attaches a query string parameter object to the request. Query string
772
- * parameters are key-value pairs which are appended to the request url, such as
773
- * `https://api.example.com?name=John&age=30`.
774
- *
775
- * This method is a shared chain method, and will return the same instance of HTTP. All
776
- * child clients will inherit the query string parameters defined by this method. Useful to configure
777
- * in the constructor body.
778
- *
779
- * ```ts
780
- * getUser(id: number) {
781
- * return this.http
782
- * .route(id)
783
- * .param({ name: "John", age: "30" })
784
- *
785
- * @param name The name of the query string parameter.
786
- * @param value The value of the query string parameter.
787
- * @returns This instance of HTTP.
788
- */
789
- params(dict) {
790
- return HTTP.create(
791
- this.client,
792
- __privateGet(this, _request2).derive().params(dict),
793
- __privateGet(this, _metaConfig).derive()
794
- );
795
- }
796
- /**
797
- * Attaches a shared data payload to this client. The data payload is the body of the request,
798
- * and can be any type. If the data payload is an object, it will be serialized to JSON.
799
- *
800
- * This method is a shared chain method, and will return the same instance of HTTP. All
801
- * child clients will inherit the data payload defined by this method. Useful to configure
802
- * in the constructor body.
803
- *
804
- * @param data The data payload to attach to the request.
805
- * @returns This instance of HTTP.
806
- */
807
- sharedData(data) {
808
- __privateGet(this, _request2).data(data);
809
- return this;
810
- }
811
- /**
812
- * Attaches a shared header to this client. Headers are string:string key-value pairs which are
813
- * sent with the request, such as `Content-Type: application/json`.
814
- *
815
- * Numbers, Booleans and Null will be converted to string values automatically.
816
- *
817
- * A Factory function can also be provided to generate the header value at the time of request.
818
- *
819
- * This method is a shared chain method, and will return the same instance of HTTP. All
820
- * child clients will inherit the header defined by this method. Useful to configure
821
- * in the constructor body.
822
- *
823
- * @param name The name of the header.
824
- * @param value The value of the header.
825
- */
826
- sharedHeader(name, value) {
827
- __privateGet(this, _request2).header(name, value);
828
- return this;
829
- }
830
- header(name, value) {
831
- return HTTP.create(
832
- this.client,
833
- __privateGet(this, _request2).derive().header(name, value),
834
- __privateGet(this, _metaConfig).derive()
835
- );
836
- }
837
- /**
838
- * Attaches a data payload to this request. The data payload is the body of the request,
839
- * and can be any type. If the data payload is an object, it will be serialized to JSON.
840
- *
841
- * This method is a request chain method, and will return a new instance of HTTP, inheriting
842
- * any data payload previously defined and appending the new payload. Useful to configure
843
- * in class methods as part of finalizing a request.
844
- *
845
- * @param data The data payload to attach to the request.
846
- * @returns A new child instance of HTTP derived from this one.
847
- */
848
- data(data) {
849
- __privateGet(this, _request2).data(data);
850
- return HTTP.create(
851
- this.client,
852
- __privateGet(this, _request2).derive().data(data),
853
- __privateGet(this, _metaConfig).derive()
854
- );
855
- }
856
- /**
857
- * `onSend` is a pre-request hook which will be executed in order of definition
858
- * immediately before the request is sent. This hook can be used to modify the request,
859
- * or to log the state of a request before final send-off.
860
- *
861
- * ```ts
862
- *
863
- * \@Fixture(INJECTION_SCOPE.TRANSIENT)
864
- * export class UserController extends BaseController {
865
- * constructor(private readonly http: HTTP) {
866
- * super(http);
867
- * }
868
- *
869
- * getUser(id: number) {
870
- * return this.http
871
- * .route(id)
872
- * .onSend("log request",
873
- * (request) => console.log(JSON.stringify(request, null, 2)
874
- * )
875
- * .get();
876
- * }
877
- * ```
878
- *
879
- * This method is a request chain method, and will return a new instance of HTTP, inheriting
880
- * any onSend hooks previously defined and appending the new hook. Useful to configure
881
- * in class methods as part of finalizing a request.
882
- *
883
- * @param description A description of the hook, used for debugging.
884
- * @param hook The hook to execute.
885
- * @returns A new child instance of HTTP derived from this one.
886
- */
887
- onSend(description, hook) {
888
- return HTTP.create(
889
- this.client,
890
- __privateGet(this, _request2).derive(),
891
- __privateGet(this, _metaConfig).derive().onBeforeSend(description, hook)
892
- );
893
- }
894
- /**
895
- * `onReceive` is a post-request hook which will be executed in order of definition
896
- * immediately after the response is received. This hook can be used to modify the response,
897
- * or to log the state of a response after it is received.
898
- *
899
- * ```ts
900
- *
901
- * \@Fixture(INJECTION_SCOPE.TRANSIENT)
902
- * export class UserController extends BaseController {
903
- * constructor(private readonly http: HTTP) {
904
- * super(http);
905
- * }
906
- *
907
- * getUser(id: number) {
908
- * return this.http
909
- * .route(id)
910
- * .onReceive("log response",
911
- * (response) => console.log(JSON.stringify(response, null, 2)
912
- * )
913
- * .get();
914
- * }
915
- * ```
916
- *
917
- * This method is a request chain method, and will return a new instance of HTTP, inheriting
918
- * any onReceive hooks previously defined and appending the new hook. Useful to configure
919
- * in class methods as part of finalizing a request.
920
- *
921
- * @param description A description of the hook, used for debugging.
922
- * @param hook The hook to execute.
923
- * @returns A new child instance of HTTP derived from this one.
924
- */
925
- onReceive(description, hook) {
926
- return HTTP.create(
927
- this.client,
928
- __privateGet(this, _request2).derive(),
929
- __privateGet(this, _metaConfig).derive().onReceiveResponse(description, hook)
930
- );
931
- }
932
- /**
933
- * Executes the current request state as a GET request.
934
- *
935
- * @param options Additional options to pass to the underlying http client, such
936
- * as e.g Axios configuration values.
937
- * @returns A promise which resolves to the response.
938
- */
939
- get(options) {
940
- return __privateMethod(this, _makeRequest, makeRequest_fn).call(this, __privateGet(this, _request2).derive().method("GET"), options);
941
- }
942
- /**
943
- * Executes the current request state as a POST request.
944
- *
945
- * @param data The data payload to attach to the request.
946
- * @param options Additional options to pass to the underlying http client, such
947
- * as e.g Axios configuration values.
948
- * @returns A promise which resolves to the response.
949
- */
950
- post(options) {
951
- return __privateMethod(this, _makeRequest, makeRequest_fn).call(this, __privateGet(this, _request2).derive().method("POST"), options);
952
- }
953
- /**
954
- * Executes the current request state as a DELETE request.
955
- *
956
- * @param options Additional options to pass to the underlying http client, such
957
- * as e.g Axios configuration values.
958
- * @returns A promise which resolves to the response.
959
- * as e.g Axios configuration values.
960
- */
961
- delete(options) {
962
- return __privateMethod(this, _makeRequest, makeRequest_fn).call(this, __privateGet(this, _request2).derive().method("DELETE"), options);
963
- }
964
- /**
965
- * Executes the current request state as a PUT request.
966
- *
967
- * @param options Additional options to pass to the underlying http client, such
968
- * as e.g Axios configuration values.
969
- * @returns A promise which resolves to the response.
970
- */
971
- put(options) {
972
- return __privateMethod(this, _makeRequest, makeRequest_fn).call(this, __privateGet(this, _request2).derive().method("PUT"), options);
973
- }
974
- /**
975
- * Executes the current request state as a PATCH request.
976
- *
977
- * @param options Additional options to pass to the underlying http client, such
978
- * as e.g Axios configuration values.
979
- * @returns A promise which resolves to the response.
980
- */
981
- patch(options) {
982
- return __privateMethod(this, _makeRequest, makeRequest_fn).call(this, __privateGet(this, _request2).derive().method("PATCH"), options);
983
- }
984
- head(options) {
985
- return __privateMethod(this, _makeRequest, makeRequest_fn).call(this, __privateGet(this, _request2).derive().method("HEAD"), options);
986
- }
987
- options(options) {
988
- return __privateMethod(this, _makeRequest, makeRequest_fn).call(this, __privateGet(this, _request2).derive().method("OPTIONS"), options);
989
- }
990
- trace(options) {
991
- return __privateMethod(this, _makeRequest, makeRequest_fn).call(this, __privateGet(this, _request2).derive().method("TRACE"), options);
992
- }
993
- connect(options) {
994
- return __privateMethod(this, _makeRequest, makeRequest_fn).call(this, __privateGet(this, _request2).derive().method("CONNECT"), options);
995
- }
996
- async runOnSendHooks(meta, request) {
997
- for (const [description, hook] of meta.onSend) {
998
- try {
999
- await hook(request);
1000
- } catch (e) {
1001
- const cause = e;
1002
- const msg = `An error occurred while sending a request in hook: '${description}'`;
1003
- throw new AutomationError2(msg, { cause });
1004
- }
1005
- }
1006
- }
1007
- async runOnReceiveHooks(meta, response) {
1008
- for (const [description, hook] of meta.onReceive) {
1009
- try {
1010
- await hook(response);
1011
- } catch (e) {
1012
- const cause = e;
1013
- const msg = `An error occurred while receiving a response in hook: '${description}'`;
1014
- throw new AutomationError2(msg, { cause });
1015
- }
1016
- }
1017
- }
1018
- };
1019
- _request2 = new WeakMap();
1020
- _metaConfig = new WeakMap();
1021
- _makeRequest = new WeakSet();
1022
- makeRequest_fn = async function(builder, options) {
1023
- const request = (await builder.resolveDynamicHeaders()).build();
1024
- const meta = __privateGet(this, _metaConfig).derive().build();
1025
- await this.runOnSendHooks(meta, request);
1026
- const opts = { ...meta.options, ...options };
1027
- const result = await this.client.request(request, opts);
1028
- result.data = transformResponse(meta.allowPlainText, result.data);
1029
- await this.runOnReceiveHooks(meta, result);
1030
- const validated = __privateMethod(this, _validateResponse, validateResponse_fn).call(this, result, meta);
1031
- return validated;
1032
- };
1033
- _validateResponse = new WeakSet();
1034
- validateResponse_fn = function(response, meta) {
1035
- const { status, data } = response;
1036
- const validated = meta.schemas.validate(
1037
- status,
1038
- data,
1039
- meta.requireSchema
1040
- );
1041
- response.data = validated;
1042
- return response;
1043
- };
1044
- HTTP = __decorateClass([
1045
- Fixture(INJECTION_SCOPE.TRANSIENT)
1046
- ], HTTP);
1047
-
1048
- // src/default-schema.ts
1049
- import isJson2 from "@stdlib/assert-is-json";
1050
- function AnySchema(data) {
1051
- return data;
1052
- }
1053
- function EmptySchema(data) {
1054
- if (data !== null && data !== void 0 && data !== "null") {
1055
- throw new Error(`Expected null but got <${typeof data}> for ${data}`);
1056
- }
1057
- return data === "null" ? null : data;
1058
- }
1059
- function NullSchema(data) {
1060
- if (data !== null && data !== "null") {
1061
- throw new Error(`Expected null but got <${typeof data}> for ${data}`);
1062
- }
1063
- return null;
1064
- }
1065
- function UndefinedSchema(data) {
1066
- if (data !== void 0) {
1067
- throw new Error(`Expected undefined but got <${typeof data}> for ${data}`);
1068
- }
1069
- return void 0;
1070
- }
1071
- function BooleanSchema(data) {
1072
- if (!(typeof data === "boolean") && ["true", "false"].includes(String(data)) === false) {
1073
- throw new Error(`Expected boolean but got <${typeof data}> for ${data}`);
1074
- }
1075
- return JSON.parse(data);
1076
- }
1077
- function NumberSchema(data) {
1078
- if (!(typeof data === "number") && /^\d*\.?\d+$/.test(String(data)) === false) {
1079
- throw new Error(`Expected number but got <${typeof data}> for ${data}`);
1080
- }
1081
- return JSON.parse(data);
1082
- }
1083
- function StringSchema(data) {
1084
- if (typeof data !== "string") {
1085
- throw new Error(`Expected string but got <${typeof data}> for ${data}`);
1086
- }
1087
- return data;
1088
- }
1089
- function JSONSchema(data) {
1090
- if (typeof data === "object") {
1091
- return data;
1092
- }
1093
- if (!isJson2(data)) {
1094
- throw new Error(`Expected JSON but got <${typeof data}> for ${data}`);
1095
- }
1096
- const result = JSON.parse(data);
1097
- return result;
1098
- }
1099
- export {
1100
- AnySchema,
1101
- AxiosClient,
1102
- BooleanSchema,
1103
- EmptySchema,
1104
- HTTP,
1105
- HTTPClient,
1106
- HTTPRequest,
1107
- HTTPRequestBuilder,
1108
- HTTPResponse,
1109
- HTTPResponseBuilder,
1110
- JSONSchema,
1111
- NullSchema,
1112
- NumberSchema,
1113
- StringSchema,
1114
- UndefinedSchema,
1115
- defaultClient
1116
- };
1117
- //# sourceMappingURL=index.js.map