api-def 0.12.0 → 0.13.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 (84) hide show
  1. package/README.md +3 -0
  2. package/bin/index.js +312 -313
  3. package/cjs/Api.d.ts +6 -6
  4. package/cjs/Api.js +99 -143
  5. package/cjs/ApiTypes.d.ts +1 -1
  6. package/cjs/ApiUtils.d.ts +2 -1
  7. package/cjs/ApiUtils.js +41 -33
  8. package/cjs/Endpoint.d.ts +1 -1
  9. package/cjs/Endpoint.js +112 -175
  10. package/cjs/EndpointBuilder.js +23 -32
  11. package/cjs/QueryHandling.js +12 -13
  12. package/cjs/RequestConfig.js +54 -36
  13. package/cjs/RequestContext.d.ts +1 -1
  14. package/cjs/RequestContext.js +125 -180
  15. package/cjs/RequestError.js +16 -19
  16. package/cjs/Requester.js +230 -312
  17. package/cjs/TextDecoding.js +31 -31
  18. package/cjs/Utils.js +20 -23
  19. package/cjs/backend/AxiosRequestBackend.d.ts +1 -1
  20. package/cjs/backend/AxiosRequestBackend.js +65 -172
  21. package/cjs/backend/FetchRequestBackend.d.ts +1 -1
  22. package/cjs/backend/FetchRequestBackend.js +108 -154
  23. package/cjs/backend/MockRequestBackend.d.ts +1 -1
  24. package/cjs/backend/MockRequestBackend.js +146 -208
  25. package/cjs/cache/ClientCaching.js +26 -74
  26. package/cjs/cache/LocalForageClientCacheBackend.js +15 -83
  27. package/cjs/cache/LocalStorageClientCacheBackend.js +14 -73
  28. package/cjs/index.d.ts +11 -11
  29. package/cjs/index.js +24 -21
  30. package/cjs/middleware/ClientCacheMiddleware.js +80 -103
  31. package/cjs/middleware/LoggingMiddleware.js +71 -42
  32. package/cjs/util/retry/index.js +42 -9
  33. package/cjs/util/retry/lib/retry.js +25 -27
  34. package/cjs/util/retry/lib/retryOperation.d.ts +1 -26
  35. package/cjs/util/retry/lib/retryOperation.js +21 -23
  36. package/esm/Api.d.ts +11 -11
  37. package/esm/Api.js +12 -23
  38. package/esm/ApiConstants.d.ts +1 -1
  39. package/esm/ApiTypes.d.ts +5 -5
  40. package/esm/ApiUtils.d.ts +4 -3
  41. package/esm/ApiUtils.js +15 -7
  42. package/esm/Endpoint.d.ts +6 -6
  43. package/esm/Endpoint.js +22 -28
  44. package/esm/EndpointBuilder.d.ts +4 -4
  45. package/esm/EndpointBuilder.js +2 -2
  46. package/esm/MockingTypes.d.ts +1 -1
  47. package/esm/QueryHandling.d.ts +1 -1
  48. package/esm/QueryHandling.js +2 -3
  49. package/esm/RequestConfig.d.ts +1 -1
  50. package/esm/RequestConfig.js +6 -7
  51. package/esm/RequestContext.d.ts +7 -7
  52. package/esm/RequestContext.js +15 -27
  53. package/esm/RequestError.d.ts +3 -3
  54. package/esm/RequestError.js +2 -3
  55. package/esm/Requester.d.ts +2 -2
  56. package/esm/Requester.js +44 -50
  57. package/esm/UtilTypes.d.ts +1 -1
  58. package/esm/Utils.js +2 -1
  59. package/esm/Validation.d.ts +1 -1
  60. package/esm/backend/AxiosRequestBackend.d.ts +4 -4
  61. package/esm/backend/AxiosRequestBackend.js +47 -84
  62. package/esm/backend/FetchRequestBackend.d.ts +5 -5
  63. package/esm/backend/FetchRequestBackend.js +49 -63
  64. package/esm/backend/MockRequestBackend.d.ts +4 -4
  65. package/esm/backend/MockRequestBackend.js +105 -136
  66. package/esm/backend/RequestBackend.d.ts +2 -2
  67. package/esm/cache/ClientCaching.d.ts +1 -1
  68. package/esm/cache/ClientCaching.js +8 -17
  69. package/esm/cache/LocalForageClientCacheBackend.d.ts +1 -1
  70. package/esm/cache/LocalForageClientCacheBackend.js +8 -25
  71. package/esm/cache/LocalStorageClientCacheBackend.d.ts +1 -1
  72. package/esm/cache/LocalStorageClientCacheBackend.js +9 -26
  73. package/esm/index.d.ts +16 -16
  74. package/esm/index.js +15 -15
  75. package/esm/middleware/ClientCacheMiddleware.d.ts +1 -1
  76. package/esm/middleware/ClientCacheMiddleware.js +8 -17
  77. package/esm/middleware/LoggingMiddleware.d.ts +1 -1
  78. package/esm/middleware/LoggingMiddleware.js +5 -6
  79. package/esm/util/retry/index.js +1 -1
  80. package/esm/util/retry/lib/retry.d.ts +1 -1
  81. package/esm/util/retry/lib/retry.js +13 -7
  82. package/esm/util/retry/lib/retryOperation.d.ts +1 -26
  83. package/esm/util/retry/lib/retryOperation.js +1 -1
  84. package/package.json +66 -28
@@ -1,49 +1,47 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
12
4
  };
13
5
  Object.defineProperty(exports, "__esModule", { value: true });
14
6
  exports.operation = void 0;
15
- var retryOperation_1 = require("./retryOperation");
16
- var operation = function (options) {
17
- var timeouts = _timeouts(options);
7
+ const retryOperation_1 = __importDefault(require("./retryOperation"));
8
+ const operation = (options) => {
9
+ const timeouts = _timeouts(options);
18
10
  return new retryOperation_1.default(timeouts, {
19
11
  forever: options && (options.forever || options.retries === Number.POSITIVE_INFINITY),
20
- unref: options === null || options === void 0 ? void 0 : options.unref,
21
- maxRetryTime: options === null || options === void 0 ? void 0 : options.maxRetryTime,
12
+ unref: options?.unref,
13
+ maxRetryTime: options?.maxRetryTime,
22
14
  });
23
15
  };
24
16
  exports.operation = operation;
25
- var _timeouts = function (options) {
26
- var _a;
27
- var createTimeout = function (attempt, opts) {
28
- var random = opts.randomize ? Math.random() + 1 : 1;
29
- var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
17
+ const _timeouts = (options) => {
18
+ const createTimeout = (attempt, opts) => {
19
+ const random = opts.randomize ? Math.random() + 1 : 1;
20
+ let timeout = Math.round(random * Math.max(opts.minTimeout, 1) * opts.factor ** attempt);
30
21
  timeout = Math.min(timeout, opts.maxTimeout);
31
22
  return timeout;
32
23
  };
33
- var defaultRetries = 10;
34
- var opts = __assign({ retries: defaultRetries, factor: 2, minTimeout: 1 * 1000, maxTimeout: Number.POSITIVE_INFINITY, randomize: false }, options);
24
+ const defaultRetries = 10;
25
+ const opts = {
26
+ retries: defaultRetries,
27
+ factor: 2,
28
+ minTimeout: 1 * 1000,
29
+ maxTimeout: Number.POSITIVE_INFINITY,
30
+ randomize: false,
31
+ ...options,
32
+ };
35
33
  if (opts.minTimeout > opts.maxTimeout) {
36
34
  throw new Error("minTimeout is greater than maxTimeout");
37
35
  }
38
- var timeouts = [];
39
- var numRetries = (_a = opts.retries) !== null && _a !== void 0 ? _a : defaultRetries;
40
- for (var i = 0; i < numRetries; i++) {
36
+ const timeouts = [];
37
+ const numRetries = opts.retries ?? defaultRetries;
38
+ for (let i = 0; i < numRetries; i++) {
41
39
  timeouts.push(createTimeout(i, opts));
42
40
  }
43
- if ((options === null || options === void 0 ? void 0 : options.forever) && !timeouts.length) {
41
+ if (options?.forever && !timeouts.length) {
44
42
  timeouts.push(createTimeout(numRetries, opts));
45
43
  }
46
44
  // sort the array numerically ascending
47
- timeouts.sort(function (a, b) { return a - b; });
45
+ timeouts.sort((a, b) => a - b);
48
46
  return timeouts;
49
47
  };
@@ -1,27 +1,2 @@
1
- export default RetryOperation;
2
1
  declare function RetryOperation(timeouts: any, options: any): void;
3
- declare class RetryOperation {
4
- constructor(timeouts: any, options: any);
5
- _originalTimeouts: any;
6
- _timeouts: any;
7
- _options: any;
8
- _maxRetryTime: any;
9
- _fn: any;
10
- _errors: any[];
11
- _attempts: number;
12
- _operationTimeout: any;
13
- _operationTimeoutCb: any;
14
- _timeout: NodeJS.Timeout | null;
15
- _operationStart: number | null;
16
- _timer: NodeJS.Timeout | null;
17
- _cachedTimeouts: any;
18
- reset(): void;
19
- stop(): void;
20
- retry(err: any): boolean;
21
- attempt(fn: any, timeoutOps: any): void;
22
- try(fn: any): void;
23
- start: (fn: any) => void;
24
- errors(): any[];
25
- attempts(): number;
26
- mainError(): any;
27
- }
2
+ export default RetryOperation;
@@ -4,7 +4,7 @@ function RetryOperation(timeouts, options) {
4
4
  this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
5
5
  this._timeouts = timeouts;
6
6
  this._options = options || {};
7
- this._maxRetryTime = (options === null || options === void 0 ? void 0 : options.maxRetryTime) || Number.POSITIVE_INFINITY;
7
+ this._maxRetryTime = options?.maxRetryTime || Number.POSITIVE_INFINITY;
8
8
  this._fn = null;
9
9
  this._errors = [];
10
10
  this._attempts = 1;
@@ -32,21 +32,20 @@ RetryOperation.prototype.stop = function () {
32
32
  this._cachedTimeouts = null;
33
33
  };
34
34
  RetryOperation.prototype.retry = function (err) {
35
- var _this = this;
36
35
  if (this._timeout) {
37
36
  clearTimeout(this._timeout);
38
37
  }
39
38
  if (!err) {
40
39
  return false;
41
40
  }
42
- var currentTime = new Date().getTime();
41
+ const currentTime = new Date().getTime();
43
42
  if (err && currentTime - this._operationStart >= this._maxRetryTime) {
44
43
  this._errors.push(err);
45
44
  this._errors.unshift(new Error("RetryOperation timeout occurred"));
46
45
  return false;
47
46
  }
48
47
  this._errors.push(err);
49
- var timeout = this._timeouts.shift();
48
+ let timeout = this._timeouts.shift();
50
49
  if (timeout === undefined) {
51
50
  if (this._cachedTimeouts) {
52
51
  // retry forever, only keep last error
@@ -57,17 +56,17 @@ RetryOperation.prototype.retry = function (err) {
57
56
  return false;
58
57
  }
59
58
  }
60
- this._timer = setTimeout(function () {
61
- _this._attempts++;
62
- if (_this._operationTimeoutCb) {
63
- _this._timeout = setTimeout(function () {
64
- _this._operationTimeoutCb(_this._attempts);
65
- }, _this._operationTimeout);
66
- if (_this._options.unref) {
67
- _this._timeout.unref();
59
+ this._timer = setTimeout(() => {
60
+ this._attempts++;
61
+ if (this._operationTimeoutCb) {
62
+ this._timeout = setTimeout(() => {
63
+ this._operationTimeoutCb(this._attempts);
64
+ }, this._operationTimeout);
65
+ if (this._options.unref) {
66
+ this._timeout.unref();
68
67
  }
69
68
  }
70
- _this._fn(_this._attempts);
69
+ this._fn(this._attempts);
71
70
  }, timeout);
72
71
  if (this._options.unref) {
73
72
  this._timer.unref();
@@ -75,7 +74,6 @@ RetryOperation.prototype.retry = function (err) {
75
74
  return true;
76
75
  };
77
76
  RetryOperation.prototype.attempt = function (fn, timeoutOps) {
78
- var _this = this;
79
77
  this._fn = fn;
80
78
  if (timeoutOps) {
81
79
  if (timeoutOps.timeout) {
@@ -86,8 +84,8 @@ RetryOperation.prototype.attempt = function (fn, timeoutOps) {
86
84
  }
87
85
  }
88
86
  if (this._operationTimeoutCb) {
89
- this._timeout = setTimeout(function () {
90
- _this._operationTimeoutCb();
87
+ this._timeout = setTimeout(() => {
88
+ this._operationTimeoutCb();
91
89
  }, this._operationTimeout);
92
90
  }
93
91
  this._operationStart = new Date().getTime();
@@ -112,13 +110,13 @@ RetryOperation.prototype.mainError = function () {
112
110
  if (this._errors.length === 0) {
113
111
  return null;
114
112
  }
115
- var counts = {};
116
- var mainError = null;
117
- var mainErrorCount = 0;
118
- for (var i = 0; i < this._errors.length; i++) {
119
- var error = this._errors[i];
120
- var message = error.message;
121
- var count = (counts[message] || 0) + 1;
113
+ const counts = {};
114
+ let mainError = null;
115
+ let mainErrorCount = 0;
116
+ for (let i = 0; i < this._errors.length; i++) {
117
+ const error = this._errors[i];
118
+ const message = error.message;
119
+ const count = (counts[message] || 0) + 1;
122
120
  counts[message] = count;
123
121
  if (count >= mainErrorCount) {
124
122
  mainError = error;
package/esm/Api.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import type { ApiResponse, BaseRequestConfig, RequestConfig, RequestMiddleware } from "./ApiTypes";
2
- import { type ResolveUrlOptions } from "./ApiUtils";
3
- import type Endpoint from "./Endpoint";
4
- import EndpointBuilder from "./EndpointBuilder";
5
- import type { ApiMockingConfig } from "./MockingTypes";
6
- import type RequestBackend from "./backend/RequestBackend";
1
+ import type { ApiResponse, BaseRequestConfig, RequestConfig, RequestMiddleware } from "./ApiTypes.js";
2
+ import { type ResolveUrlOptions } from "./ApiUtils.js";
3
+ import type RequestBackend from "./backend/RequestBackend.js";
4
+ import type Endpoint from "./Endpoint.js";
5
+ import EndpointBuilder from "./EndpointBuilder.js";
6
+ import type { ApiMockingConfig } from "./MockingTypes.js";
7
7
  export declare const getRequestBackend: () => RequestBackend | null;
8
8
  export declare const isRequestBackendDefault: () => boolean;
9
9
  export declare const setRequestBackend: (backend: RequestBackend) => void;
@@ -48,10 +48,10 @@ export declare class Api implements ApiInfo {
48
48
  getConfig(): BaseRequestConfig;
49
49
  computeRequestConfig(): BaseRequestConfig;
50
50
  private hotRequest;
51
- get: <R = unknown>(path: string, config: RequestConfig) => Promise<ApiResponse<R>>;
52
- post: <R = unknown>(path: string, config: RequestConfig) => Promise<ApiResponse<R>>;
53
- put: <R = unknown>(path: string, config: RequestConfig) => Promise<ApiResponse<R>>;
54
- delete: <R = unknown>(path: string, config: RequestConfig) => Promise<ApiResponse<R>>;
55
- patch: <R = unknown>(path: string, config: RequestConfig) => Promise<ApiResponse<R>>;
51
+ get: <R = unknown>(path: string | URL, config: RequestConfig) => Promise<ApiResponse<R>>;
52
+ post: <R = unknown>(path: string | URL, config: RequestConfig) => Promise<ApiResponse<R>>;
53
+ put: <R = unknown>(path: string | URL, config: RequestConfig) => Promise<ApiResponse<R>>;
54
+ delete: <R = unknown>(path: string | URL, config: RequestConfig) => Promise<ApiResponse<R>>;
55
+ patch: <R = unknown>(path: string | URL, config: RequestConfig) => Promise<ApiResponse<R>>;
56
56
  resolveUrl(options: ApiResolveUrlOptions): URL;
57
57
  }
package/esm/Api.js CHANGED
@@ -1,19 +1,10 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { RequestMethod } from "./ApiConstants";
11
- import { resolveUrl } from "./ApiUtils";
12
- import EndpointBuilder from "./EndpointBuilder";
13
- import { processRequestConfigs } from "./RequestConfig";
14
- import * as Requester from "./Requester";
15
- import * as Utils from "./Utils";
16
- import FetchRequestBackend from "./backend/FetchRequestBackend";
1
+ import { RequestMethod } from "./ApiConstants.js";
2
+ import { resolveUrl } from "./ApiUtils.js";
3
+ import FetchRequestBackend from "./backend/FetchRequestBackend.js";
4
+ import EndpointBuilder from "./EndpointBuilder.js";
5
+ import { processRequestConfigs } from "./RequestConfig.js";
6
+ import * as Requester from "./Requester.js";
7
+ import * as Utils from "./Utils.js";
17
8
  // use fetch as default if it is present
18
9
  let requestBackend = Utils.getGlobalFetch() ? new FetchRequestBackend() : null;
19
10
  let requestBackendIsDefault = true;
@@ -50,7 +41,6 @@ export class Api {
50
41
  //private mutable = false;
51
42
  //private wasMutable = false;
52
43
  constructor(options) {
53
- var _a, _b, _c, _d;
54
44
  this.endpoints = {};
55
45
  /*configure(info: Partial<ApiInfo>): void {
56
46
  if (!this.mutable) {
@@ -62,13 +52,13 @@ export class Api {
62
52
  Object.assign(this.info, info);
63
53
  this.mutable = false;
64
54
  }*/
65
- this.hotRequest = (requestMethod) => (path, config) => __awaiter(this, void 0, void 0, function* () { return yield Requester.submit(new HotRequestHost(this, path, requestMethod), config, null); });
55
+ this.hotRequest = (requestMethod) => async (path, config) => await Requester.submit(new HotRequestHost(this, path instanceof URL ? path.href : path, requestMethod), config, null);
66
56
  this.get = this.hotRequest(RequestMethod.GET);
67
57
  this.post = this.hotRequest(RequestMethod.POST);
68
58
  this.put = this.hotRequest(RequestMethod.PUT);
69
59
  this.delete = this.hotRequest(RequestMethod.DELETE);
70
60
  this.patch = this.hotRequest(RequestMethod.PATCH);
71
- const requestBackend = (_a = options.requestBackend) !== null && _a !== void 0 ? _a : getRequestBackend();
61
+ const requestBackend = options.requestBackend ?? getRequestBackend();
72
62
  if (!requestBackend) {
73
63
  throw new Error("[api-def] No request backend provided in either Api options or globally, use `setRequestBackend()` to set one or pass one via `requestBackend`");
74
64
  }
@@ -76,8 +66,8 @@ export class Api {
76
66
  name: options.name,
77
67
  baseUrl: options.baseUrl,
78
68
  middleware: options.middleware || [],
79
- defaultRequestConfig: (_c = (_b = options.defaultRequestConfig) !== null && _b !== void 0 ? _b : options.config) !== null && _c !== void 0 ? _c : undefined,
80
- mocking: (_d = options.mocking) !== null && _d !== void 0 ? _d : undefined,
69
+ defaultRequestConfig: options.defaultRequestConfig ?? options.config ?? undefined,
70
+ mocking: options.mocking ?? undefined,
81
71
  requestBackend: requestBackend,
82
72
  };
83
73
  //this.mutable = options.mutable ?? false;
@@ -127,9 +117,8 @@ export class Api {
127
117
  return ((typeof this.defaultRequestConfig === "function" ? this.defaultRequestConfig() : this.defaultRequestConfig) || {});
128
118
  }
129
119
  resolveUrl(options) {
130
- var _a;
131
120
  return resolveUrl({
132
- baseUrl: (_a = options.baseUrl) !== null && _a !== void 0 ? _a : this.baseUrl,
121
+ baseUrl: options.baseUrl ?? this.baseUrl,
133
122
  path: options.path,
134
123
  });
135
124
  }
@@ -1,4 +1,4 @@
1
- import type { EnumOf } from "./Utils";
1
+ import type { EnumOf } from "./Utils.js";
2
2
  export declare const RequestMethod: {
3
3
  readonly POST: "post";
4
4
  readonly GET: "get";
package/esm/ApiTypes.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import type { Api } from "./Api";
2
- import type { CacheSource, EventResultType, RequestEvent, RequestMethod, ResponseType } from "./ApiConstants";
3
- import type RequestContext from "./RequestContext";
4
- import type { Validation } from "./Validation";
5
- import type RequestBackend from "./backend/RequestBackend";
1
+ import type { Api } from "./Api.js";
2
+ import type { CacheSource, EventResultType, RequestEvent, RequestMethod, ResponseType } from "./ApiConstants.js";
3
+ import type RequestBackend from "./backend/RequestBackend.js";
4
+ import type RequestContext from "./RequestContext.js";
5
+ import type { Validation } from "./Validation.js";
6
6
  export type AcceptableStatus = number | [min: number, max: number];
7
7
  export type RawHeaders = Record<string, string | number | boolean | null | undefined>;
8
8
  export type Params = string;
package/esm/ApiUtils.d.ts CHANGED
@@ -1,11 +1,12 @@
1
- import type { ResponseType } from "./ApiConstants";
2
- import type { AcceptableStatus, CancelledRequestError } from "./ApiTypes";
1
+ import type { ResponseType } from "./ApiConstants.js";
2
+ import type { AcceptableStatus, CancelledRequestError } from "./ApiTypes.js";
3
3
  export interface ResolveUrlOptions {
4
- path: string;
4
+ path: string | URL;
5
5
  baseUrl: string;
6
6
  }
7
7
  export declare const isCancelledError: (error: Error) => error is CancelledRequestError;
8
8
  export declare const isNetworkError: (error: Error) => boolean;
9
+ export declare const isAbsoluteUrl: (url: string) => boolean;
9
10
  export declare const isAcceptableStatus: (status: number, acceptableStatus?: AcceptableStatus[]) => boolean;
10
11
  export declare const inferResponseType: (contentType: string | null | undefined) => ResponseType;
11
12
  export declare const resolvePathParams: (path: string, params: Record<string, string> | undefined, allowMissing?: boolean) => string;
package/esm/ApiUtils.js CHANGED
@@ -2,14 +2,16 @@ export const isCancelledError = (error) => {
2
2
  return "isCancelledRequest" in error;
3
3
  };
4
4
  export const isNetworkError = (error) => {
5
- var _a;
6
5
  return (error.name === "NetworkError" ||
7
6
  error.message === "Network Error" ||
8
- ((_a = error.constructor) === null || _a === void 0 ? void 0 : _a.name) === "NetworkError");
7
+ error.constructor?.name === "NetworkError");
8
+ };
9
+ export const isAbsoluteUrl = (url) => {
10
+ return /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(url);
9
11
  };
10
12
  const DEFAULT_ACCEPTABLE_STATUS = [[200, 299], 304];
11
13
  export const isAcceptableStatus = (status, acceptableStatus) => {
12
- const acceptable = acceptableStatus !== null && acceptableStatus !== void 0 ? acceptableStatus : DEFAULT_ACCEPTABLE_STATUS;
14
+ const acceptable = acceptableStatus ?? DEFAULT_ACCEPTABLE_STATUS;
13
15
  for (const cmpStatus of acceptable) {
14
16
  if (Array.isArray(cmpStatus)) {
15
17
  const [min, max] = cmpStatus;
@@ -30,7 +32,7 @@ const JSON_CONTENT_TYPES = ["text/json", "application/json"];
30
32
  const ARRAY_BUFFER_CONTENT_TYPES = ["application/octet-stream"];
31
33
  const STREAM_CONTENT_TYPES = ["text/event-stream", "application/x-ndjson"];
32
34
  export const inferResponseType = (contentType) => {
33
- const contentTypePart = contentType === null || contentType === void 0 ? void 0 : contentType.split(";")[0].trim();
35
+ const contentTypePart = contentType?.split(";")[0].trim();
34
36
  if (contentTypePart) {
35
37
  if (TEXT_CONTENT_TYPES.includes(contentTypePart)) {
36
38
  return "text";
@@ -48,7 +50,7 @@ export const inferResponseType = (contentType) => {
48
50
  return "text";
49
51
  };
50
52
  export const resolvePathParams = (path, params, allowMissing) => {
51
- const computedPath = path.startsWith("/") ? path : `/${path}`;
53
+ const computedPath = path.startsWith("/") || isAbsoluteUrl(path) ? path : `/${path}`;
52
54
  if (params) {
53
55
  const computedPathParts = computedPath.split("/");
54
56
  const unusedKeys = new Set(Object.keys(params));
@@ -82,14 +84,20 @@ export const resolvePathParams = (path, params, allowMissing) => {
82
84
  };
83
85
  export const resolveUrl = (options) => {
84
86
  const { baseUrl, path } = options;
87
+ if (path instanceof URL) {
88
+ return new URL(path.href);
89
+ }
90
+ if (isAbsoluteUrl(path)) {
91
+ return new URL(path);
92
+ }
85
93
  let result = !baseUrl.endsWith("/") ? `${baseUrl}/` : baseUrl;
86
94
  result += path.startsWith("/") ? path.substring(1) : path;
87
- let origin = undefined;
95
+ let origin;
88
96
  if (typeof window !== "undefined") {
89
97
  origin = window.origin;
90
98
  }
91
99
  if (!origin) {
92
- if (result.indexOf("://") === -1) {
100
+ if (!isAbsoluteUrl(result)) {
93
101
  result = `https://${result}`;
94
102
  }
95
103
  }
package/esm/Endpoint.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import type { Api } from "./Api";
2
- import type { RequestMethod, ResponseType } from "./ApiConstants";
3
- import type { ApiResponse, BaseRequestConfig, Body, ComputedRequestConfig, Params, Query, RawHeaders, RequestConfig, RequestHost, RequestMiddleware, State } from "./ApiTypes";
4
- import type * as Mocking from "./MockingTypes";
5
- import type { Validation } from "./Validation";
6
- import type RequestBackend from "./backend/RequestBackend";
1
+ import type { Api } from "./Api.js";
2
+ import type { RequestMethod, ResponseType } from "./ApiConstants.js";
3
+ import type { ApiResponse, BaseRequestConfig, Body, ComputedRequestConfig, Params, Query, RawHeaders, RequestConfig, RequestHost, RequestMiddleware, State } from "./ApiTypes.js";
4
+ import type RequestBackend from "./backend/RequestBackend.js";
5
+ import type * as Mocking from "./MockingTypes.js";
6
+ import type { Validation } from "./Validation.js";
7
7
  export interface EndpointResolveUrlOptions<TParams extends Params | undefined, TQuery extends Query | undefined> {
8
8
  baseUrl?: string;
9
9
  params?: (TParams extends string | symbol | number ? Record<TParams, string> : never) | undefined;
package/esm/Endpoint.js CHANGED
@@ -1,20 +1,17 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import * as Requester from "./Requester";
11
- import { resolvePathParams } from "./ApiUtils";
12
- import { processRequestConfigs } from "./RequestConfig";
1
+ import { resolvePathParams } from "./ApiUtils.js";
2
+ import { processRequestConfigs } from "./RequestConfig.js";
3
+ import * as Requester from "./Requester.js";
13
4
  export default class Endpoint {
14
5
  constructor(api, options) {
15
- var _a, _b;
16
6
  this.api = api;
17
- this.info = Object.assign(Object.assign({}, options), { config: undefined, name: options.name || options.id, validation: options.validation || {}, middleware: options.middleware || [], defaultRequestConfig: (_b = (_a = options.defaultRequestConfig) !== null && _a !== void 0 ? _a : options.config) !== null && _b !== void 0 ? _b : {} });
7
+ this.info = {
8
+ ...options,
9
+ config: undefined,
10
+ name: options.name || options.id,
11
+ validation: options.validation || {},
12
+ middleware: options.middleware || [],
13
+ defaultRequestConfig: options.defaultRequestConfig ?? options.config ?? {},
14
+ };
18
15
  }
19
16
  get id() {
20
17
  return this.info.id;
@@ -50,22 +47,19 @@ export default class Endpoint {
50
47
  get middleware() {
51
48
  return this.info.middleware || [];
52
49
  }
53
- submit(config) {
54
- return __awaiter(this, void 0, void 0, function* () {
55
- var _a, _b;
56
- let mock = false;
57
- const apiMocking = this.api.mocking;
58
- if (apiMocking) {
59
- const mockingEnabled = (_a = (typeof apiMocking.enabled === "function" ? apiMocking.enabled() : apiMocking.enabled)) !== null && _a !== void 0 ? _a : false;
60
- if (mockingEnabled) {
61
- if (!((_b = this.mocking) === null || _b === void 0 ? void 0 : _b.handler)) {
62
- throw new Error(`[api-def] Endpoint for '${this.path}' has no mocking`);
63
- }
64
- mock = true;
50
+ async submit(config) {
51
+ let mock = false;
52
+ const apiMocking = this.api.mocking;
53
+ if (apiMocking) {
54
+ const mockingEnabled = (typeof apiMocking.enabled === "function" ? apiMocking.enabled() : apiMocking.enabled) ?? false;
55
+ if (mockingEnabled) {
56
+ if (!this.mocking?.handler) {
57
+ throw new Error(`[api-def] Endpoint for '${this.path}' has no mocking`);
65
58
  }
59
+ mock = true;
66
60
  }
67
- return Requester.submit(this, config, mock ? this.mocking : null);
68
- });
61
+ }
62
+ return Requester.submit(this, config, mock ? this.mocking : null);
69
63
  }
70
64
  resolveUrl(options) {
71
65
  const { query } = options;
@@ -1,8 +1,8 @@
1
1
  import type * as zod from "zod";
2
- import type { Api } from "./Api";
3
- import type { ResponseType } from "./ApiConstants";
4
- import type { Body, Params, Query, RawHeaders, State } from "./ApiTypes";
5
- import Endpoint, { type EndpointOptions } from "./Endpoint";
2
+ import type { Api } from "./Api.js";
3
+ import type { ResponseType } from "./ApiConstants.js";
4
+ import type { Body, Params, Query, RawHeaders, State } from "./ApiTypes.js";
5
+ import Endpoint, { type EndpointOptions } from "./Endpoint.js";
6
6
  type DefaultResponseOf<T extends ResponseType | undefined> = T extends "text" ? string : T extends "arraybuffer" ? ArrayBuffer : "stream" extends T ? AsyncIterable<Uint8Array> : unknown;
7
7
  export type EndpointBuildOptions<TResponse = unknown, TParams extends Params | undefined = undefined, TQuery extends Query | undefined = undefined, TBody extends Body | undefined = undefined, TState extends State = State, TRequestHeaders extends RawHeaders | undefined = RawHeaders | undefined, TResponseHeaders extends RawHeaders | undefined = RawHeaders | undefined, TPath extends string = string, TResponseType extends ResponseType | undefined = undefined> = Omit<EndpointOptions<TResponse, TParams, TQuery, TBody, TState, TPath, TRequestHeaders, TResponseHeaders>, "validation"> & {
8
8
  responseType?: TResponseType;
@@ -1,4 +1,4 @@
1
- import Endpoint from "./Endpoint";
1
+ import Endpoint from "./Endpoint.js";
2
2
  export default class EndpointBuilder {
3
3
  constructor(api) {
4
4
  this.validation = {};
@@ -30,7 +30,7 @@ export default class EndpointBuilder {
30
30
  return this;
31
31
  }
32
32
  build(options) {
33
- const endpoint = new Endpoint(this.api, Object.assign(Object.assign({}, options), { validation: this.validation }));
33
+ const endpoint = new Endpoint(this.api, { ...options, validation: this.validation });
34
34
  this.api.endpoints[endpoint.id] = endpoint;
35
35
  return endpoint;
36
36
  }
@@ -1,4 +1,4 @@
1
- import type { ApiResponse, Body, Params, Query, RawHeaders, State } from "./ApiTypes";
1
+ import type { ApiResponse, Body, Params, Query, RawHeaders, State } from "./ApiTypes.js";
2
2
  export interface ApiMockingConfig {
3
3
  enabled: boolean | (() => boolean);
4
4
  }
@@ -1,3 +1,3 @@
1
- import type { QueryStringify } from "./ApiTypes";
1
+ import type { QueryStringify } from "./ApiTypes.js";
2
2
  export declare const DEFAULT_QUERY_STRINGIFY: QueryStringify;
3
3
  export declare const DEFAULT_QUERY_PARSE: (queryString: string) => Record<string, any>;
@@ -1,10 +1,9 @@
1
1
  export const DEFAULT_QUERY_STRINGIFY = (query) => {
2
- var _a, _b;
3
2
  const queryStrings = [];
4
3
  const queryKeys = Object.keys(query);
5
4
  for (let i = 0; i < queryKeys.length; i++) {
6
5
  const key = queryKeys[i];
7
- queryStrings.push(`${key}=${(_b = (_a = query[key]) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ""}`);
6
+ queryStrings.push(`${key}=${query[key]?.toString() ?? ""}`);
8
7
  }
9
8
  return queryStrings.join("&");
10
9
  };
@@ -13,7 +12,7 @@ export const DEFAULT_QUERY_PARSE = (queryString) => {
13
12
  const queryStrings = queryString.split("&");
14
13
  for (let i = 0; i < queryStrings.length; i++) {
15
14
  const [key, value] = queryStrings[i].split("=");
16
- query[key] = !(value === null || value === void 0 ? void 0 : value.length) ? true : value;
15
+ query[key] = !value?.length ? true : value;
17
16
  }
18
17
  return query;
19
18
  };
@@ -1,2 +1,2 @@
1
- import { type BaseRequestConfig, type Body, type ComputedRequestConfig, type Params, type Query, type RawHeaders, type RequestConfig, type State } from "./ApiTypes";
1
+ import { type BaseRequestConfig, type Body, type ComputedRequestConfig, type Params, type Query, type RawHeaders, type RequestConfig, type State } from "./ApiTypes.js";
2
2
  export declare const processRequestConfigs: <TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State, TRequestHeaders extends RawHeaders | undefined>(configs: (RequestConfig<TParams, TQuery, TBody, TState, TRequestHeaders> | BaseRequestConfig | undefined)[]) => ComputedRequestConfig<TParams, TQuery, TBody, TState, TRequestHeaders>;
@@ -1,24 +1,23 @@
1
- import { COMPUTED_CONFIG_SYMBOL, } from "./ApiTypes";
2
- import { DEFAULT_QUERY_PARSE, DEFAULT_QUERY_STRINGIFY } from "./QueryHandling";
3
- import * as Utils from "./Utils";
1
+ import { COMPUTED_CONFIG_SYMBOL, } from "./ApiTypes.js";
2
+ import { DEFAULT_QUERY_PARSE, DEFAULT_QUERY_STRINGIFY } from "./QueryHandling.js";
3
+ import * as Utils from "./Utils.js";
4
4
  const MERGED_CONFIG_KEYS = ["headers"];
5
5
  export const processRequestConfigs = (configs) => {
6
- var _a, _b;
7
6
  const computedConfig = Utils.assign({
8
7
  [COMPUTED_CONFIG_SYMBOL]: true,
9
8
  }, ...configs);
10
9
  // merge other values
11
10
  for (const key of MERGED_CONFIG_KEYS) {
12
11
  computedConfig[key] = Utils.assign({}, ...configs.reduce((acc, config) => {
13
- if (config === null || config === void 0 ? void 0 : config[key]) {
12
+ if (config?.[key]) {
14
13
  acc.push(config[key]);
15
14
  }
16
15
  return acc;
17
16
  }, []));
18
17
  }
19
18
  computedConfig.queryHandling = {
20
- parse: ((_a = computedConfig.queryHandling) === null || _a === void 0 ? void 0 : _a.parse) || DEFAULT_QUERY_PARSE,
21
- stringify: ((_b = computedConfig.queryHandling) === null || _b === void 0 ? void 0 : _b.stringify) || computedConfig.queryParser || DEFAULT_QUERY_STRINGIFY,
19
+ parse: computedConfig.queryHandling?.parse || DEFAULT_QUERY_PARSE,
20
+ stringify: computedConfig.queryHandling?.stringify || computedConfig.queryParser || DEFAULT_QUERY_STRINGIFY,
22
21
  };
23
22
  computedConfig.queryParser = undefined;
24
23
  const query = computedConfig.query;
@@ -1,10 +1,10 @@
1
- import type { Api } from "./Api";
2
- import type { RequestEvent, RequestMethod, ResponseType } from "./ApiConstants";
3
- import type { ApiResponse, Body, ComputedRequestConfig, EventResult, Params, Query, RawHeaders, RequestCacheInfo, RequestEventHandlers, RequestHost, RequestStats, State } from "./ApiTypes";
4
- import type { EndpointMockingConfig } from "./MockingTypes";
5
- import type { RequestError } from "./RequestError";
6
- import type { Validation } from "./Validation";
7
- import type RequestBackend from "./backend/RequestBackend";
1
+ import type { Api } from "./Api.js";
2
+ import type { RequestEvent, RequestMethod, ResponseType } from "./ApiConstants.js";
3
+ import type { ApiResponse, Body, ComputedRequestConfig, EventResult, Params, Query, RawHeaders, RequestCacheInfo, RequestEventHandlers, RequestHost, RequestStats, State } from "./ApiTypes.js";
4
+ import type RequestBackend from "./backend/RequestBackend.js";
5
+ import type { EndpointMockingConfig } from "./MockingTypes.js";
6
+ import type { RequestError } from "./RequestError.js";
7
+ import type { Validation } from "./Validation.js";
8
8
  export default class RequestContext<TResponse = any, TParams extends Params | undefined = Params | undefined, TQuery extends Query | undefined = Query | undefined, TBody extends Body | undefined = Body | undefined, TState extends State = State> {
9
9
  readonly id: number;
10
10
  readonly key: string;