api-def 0.12.1 → 0.14.0-alpha.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.
Files changed (87) hide show
  1. package/README.md +3 -0
  2. package/bin/index.js +312 -313
  3. package/cjs/Api.d.ts +1 -1
  4. package/cjs/Api.js +99 -145
  5. package/cjs/ApiTypes.d.ts +3 -2
  6. package/cjs/ApiUtils.js +30 -32
  7. package/cjs/Endpoint.d.ts +1 -1
  8. package/cjs/Endpoint.js +112 -175
  9. package/cjs/EndpointBuilder.d.ts +17 -0
  10. package/cjs/EndpointBuilder.js +55 -36
  11. package/cjs/QueryHandling.js +12 -13
  12. package/cjs/RequestConfig.js +54 -36
  13. package/cjs/RequestContext.d.ts +2 -1
  14. package/cjs/RequestContext.js +143 -180
  15. package/cjs/RequestError.js +16 -19
  16. package/cjs/Requester.js +231 -312
  17. package/cjs/TextDecoding.js +31 -31
  18. package/cjs/Utils.d.ts +1 -0
  19. package/cjs/Utils.js +74 -25
  20. package/cjs/Validation.d.ts +8 -1
  21. package/cjs/backend/AxiosRequestBackend.d.ts +1 -1
  22. package/cjs/backend/AxiosRequestBackend.js +65 -172
  23. package/cjs/backend/FetchRequestBackend.d.ts +1 -1
  24. package/cjs/backend/FetchRequestBackend.js +108 -154
  25. package/cjs/backend/MockRequestBackend.d.ts +1 -1
  26. package/cjs/backend/MockRequestBackend.js +146 -208
  27. package/cjs/cache/ClientCaching.js +26 -74
  28. package/cjs/cache/LocalForageClientCacheBackend.js +15 -83
  29. package/cjs/cache/LocalStorageClientCacheBackend.js +14 -73
  30. package/cjs/index.d.ts +11 -11
  31. package/cjs/index.js +24 -21
  32. package/cjs/middleware/ClientCacheMiddleware.js +80 -103
  33. package/cjs/middleware/LoggingMiddleware.js +71 -42
  34. package/cjs/util/retry/index.js +42 -9
  35. package/cjs/util/retry/lib/retry.js +25 -27
  36. package/cjs/util/retry/lib/retryOperation.d.ts +1 -26
  37. package/cjs/util/retry/lib/retryOperation.js +21 -23
  38. package/esm/Api.d.ts +6 -6
  39. package/esm/Api.js +12 -25
  40. package/esm/ApiConstants.d.ts +1 -1
  41. package/esm/ApiTypes.d.ts +7 -6
  42. package/esm/ApiUtils.d.ts +2 -2
  43. package/esm/ApiUtils.js +4 -5
  44. package/esm/Endpoint.d.ts +6 -6
  45. package/esm/Endpoint.js +22 -28
  46. package/esm/EndpointBuilder.d.ts +21 -4
  47. package/esm/EndpointBuilder.js +38 -10
  48. package/esm/MockingTypes.d.ts +1 -1
  49. package/esm/QueryHandling.d.ts +1 -1
  50. package/esm/QueryHandling.js +2 -3
  51. package/esm/RequestConfig.d.ts +1 -1
  52. package/esm/RequestConfig.js +6 -7
  53. package/esm/RequestContext.d.ts +8 -7
  54. package/esm/RequestContext.js +33 -27
  55. package/esm/RequestError.d.ts +3 -3
  56. package/esm/RequestError.js +2 -3
  57. package/esm/Requester.d.ts +2 -2
  58. package/esm/Requester.js +45 -50
  59. package/esm/UtilTypes.d.ts +1 -1
  60. package/esm/Utils.d.ts +1 -0
  61. package/esm/Utils.js +54 -2
  62. package/esm/Validation.d.ts +8 -1
  63. package/esm/backend/AxiosRequestBackend.d.ts +4 -4
  64. package/esm/backend/AxiosRequestBackend.js +47 -84
  65. package/esm/backend/FetchRequestBackend.d.ts +5 -5
  66. package/esm/backend/FetchRequestBackend.js +50 -64
  67. package/esm/backend/MockRequestBackend.d.ts +4 -4
  68. package/esm/backend/MockRequestBackend.js +105 -136
  69. package/esm/backend/RequestBackend.d.ts +2 -2
  70. package/esm/cache/ClientCaching.d.ts +1 -1
  71. package/esm/cache/ClientCaching.js +8 -17
  72. package/esm/cache/LocalForageClientCacheBackend.d.ts +1 -1
  73. package/esm/cache/LocalForageClientCacheBackend.js +8 -25
  74. package/esm/cache/LocalStorageClientCacheBackend.d.ts +1 -1
  75. package/esm/cache/LocalStorageClientCacheBackend.js +9 -26
  76. package/esm/index.d.ts +16 -16
  77. package/esm/index.js +15 -15
  78. package/esm/middleware/ClientCacheMiddleware.d.ts +1 -1
  79. package/esm/middleware/ClientCacheMiddleware.js +8 -17
  80. package/esm/middleware/LoggingMiddleware.d.ts +1 -1
  81. package/esm/middleware/LoggingMiddleware.js +5 -6
  82. package/esm/util/retry/index.js +1 -1
  83. package/esm/util/retry/lib/retry.d.ts +1 -1
  84. package/esm/util/retry/lib/retry.js +13 -7
  85. package/esm/util/retry/lib/retryOperation.d.ts +1 -26
  86. package/esm/util/retry/lib/retryOperation.js +1 -1
  87. package/package.json +67 -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;
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,15 +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* () {
66
- return yield Requester.submit(new HotRequestHost(this, path instanceof URL ? path.href : path, requestMethod), config, null);
67
- });
55
+ this.hotRequest = (requestMethod) => async (path, config) => await Requester.submit(new HotRequestHost(this, path instanceof URL ? path.href : path, requestMethod), config, null);
68
56
  this.get = this.hotRequest(RequestMethod.GET);
69
57
  this.post = this.hotRequest(RequestMethod.POST);
70
58
  this.put = this.hotRequest(RequestMethod.PUT);
71
59
  this.delete = this.hotRequest(RequestMethod.DELETE);
72
60
  this.patch = this.hotRequest(RequestMethod.PATCH);
73
- const requestBackend = (_a = options.requestBackend) !== null && _a !== void 0 ? _a : getRequestBackend();
61
+ const requestBackend = options.requestBackend ?? getRequestBackend();
74
62
  if (!requestBackend) {
75
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`");
76
64
  }
@@ -78,8 +66,8 @@ export class Api {
78
66
  name: options.name,
79
67
  baseUrl: options.baseUrl,
80
68
  middleware: options.middleware || [],
81
- defaultRequestConfig: (_c = (_b = options.defaultRequestConfig) !== null && _b !== void 0 ? _b : options.config) !== null && _c !== void 0 ? _c : undefined,
82
- mocking: (_d = options.mocking) !== null && _d !== void 0 ? _d : undefined,
69
+ defaultRequestConfig: options.defaultRequestConfig ?? options.config ?? undefined,
70
+ mocking: options.mocking ?? undefined,
83
71
  requestBackend: requestBackend,
84
72
  };
85
73
  //this.mutable = options.mutable ?? false;
@@ -129,9 +117,8 @@ export class Api {
129
117
  return ((typeof this.defaultRequestConfig === "function" ? this.defaultRequestConfig() : this.defaultRequestConfig) || {});
130
118
  }
131
119
  resolveUrl(options) {
132
- var _a;
133
120
  return resolveUrl({
134
- baseUrl: (_a = options.baseUrl) !== null && _a !== void 0 ? _a : this.baseUrl,
121
+ baseUrl: options.baseUrl ?? this.baseUrl,
135
122
  path: options.path,
136
123
  });
137
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,13 +1,14 @@
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;
9
9
  export type Query = string | undefined | Record<string, any>;
10
- export type Body = string | number | Record<string, any>;
10
+ export type Body = string | number | Record<string, any> | FormData;
11
+ export type RequestBodyEncoding = "application/json" | "multipart/form-data" | "application/x-www-form-urlencoded";
11
12
  export type State = Record<string, any>;
12
13
  export interface ApiResponse<T = any> {
13
14
  readonly method: RequestMethod;
package/esm/ApiUtils.d.ts CHANGED
@@ -1,5 +1,5 @@
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
4
  path: string | URL;
5
5
  baseUrl: string;
package/esm/ApiUtils.js CHANGED
@@ -2,17 +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");
9
8
  };
10
9
  export const isAbsoluteUrl = (url) => {
11
10
  return /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(url);
12
11
  };
13
12
  const DEFAULT_ACCEPTABLE_STATUS = [[200, 299], 304];
14
13
  export const isAcceptableStatus = (status, acceptableStatus) => {
15
- const acceptable = acceptableStatus !== null && acceptableStatus !== void 0 ? acceptableStatus : DEFAULT_ACCEPTABLE_STATUS;
14
+ const acceptable = acceptableStatus ?? DEFAULT_ACCEPTABLE_STATUS;
16
15
  for (const cmpStatus of acceptable) {
17
16
  if (Array.isArray(cmpStatus)) {
18
17
  const [min, max] = cmpStatus;
@@ -33,7 +32,7 @@ const JSON_CONTENT_TYPES = ["text/json", "application/json"];
33
32
  const ARRAY_BUFFER_CONTENT_TYPES = ["application/octet-stream"];
34
33
  const STREAM_CONTENT_TYPES = ["text/event-stream", "application/x-ndjson"];
35
34
  export const inferResponseType = (contentType) => {
36
- const contentTypePart = contentType === null || contentType === void 0 ? void 0 : contentType.split(";")[0].trim();
35
+ const contentTypePart = contentType?.split(";")[0].trim();
37
36
  if (contentTypePart) {
38
37
  if (TEXT_CONTENT_TYPES.includes(contentTypePart)) {
39
38
  return "text";
@@ -93,7 +92,7 @@ export const resolveUrl = (options) => {
93
92
  }
94
93
  let result = !baseUrl.endsWith("/") ? `${baseUrl}/` : baseUrl;
95
94
  result += path.startsWith("/") ? path.substring(1) : path;
96
- let origin = undefined;
95
+ let origin;
97
96
  if (typeof window !== "undefined") {
98
97
  origin = window.origin;
99
98
  }
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,9 @@
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
+ import type { BodyValidationOptions, ValidationOptions } from "./Validation.js";
6
7
  type DefaultResponseOf<T extends ResponseType | undefined> = T extends "text" ? string : T extends "arraybuffer" ? ArrayBuffer : "stream" extends T ? AsyncIterable<Uint8Array> : unknown;
7
8
  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
9
  responseType?: TResponseType;
@@ -11,10 +12,26 @@ export default class EndpointBuilder<TResponse = unknown, TParams extends Params
11
12
  private api;
12
13
  private readonly validation;
13
14
  constructor(api: Api);
15
+ queryOf<TNewQuery extends Query>(options?: ValidationOptions<TNewQuery>): EndpointBuilder<TResponse, TParams, TNewQuery, TBody, TState, TRequestHeaders, TResponseHeaders>;
16
+ /**
17
+ * @deprecated Pass `{ schema }` instead.
18
+ */
14
19
  queryOf<TNewQuery extends Query>(schema?: zod.Schema<TNewQuery>): EndpointBuilder<TResponse, TParams, TNewQuery, TBody, TState, TRequestHeaders, TResponseHeaders>;
15
20
  paramsOf<TNewParams extends Params>(): EndpointBuilder<TResponse, TNewParams, TQuery, TBody, TState, TRequestHeaders, TResponseHeaders>;
21
+ bodyOf<TNewBody extends Body>(options?: BodyValidationOptions<TNewBody>): EndpointBuilder<TResponse, TParams, TQuery, TNewBody, TState, TRequestHeaders, TResponseHeaders>;
22
+ /**
23
+ * @deprecated Pass `{ schema }` instead.
24
+ */
16
25
  bodyOf<TNewBody extends Body>(schema?: zod.Schema<TNewBody>): EndpointBuilder<TResponse, TParams, TQuery, TNewBody, TState, TRequestHeaders, TResponseHeaders>;
26
+ responseOf<TNewResponse>(options?: ValidationOptions<TNewResponse>): EndpointBuilder<TNewResponse, TParams, TQuery, TBody, TState, TRequestHeaders, TResponseHeaders>;
27
+ /**
28
+ * @deprecated Pass `{ schema }` instead.
29
+ */
17
30
  responseOf<TNewResponse>(schema?: zod.Schema<TNewResponse>): EndpointBuilder<TNewResponse, TParams, TQuery, TBody, TState, TRequestHeaders, TResponseHeaders>;
31
+ stateOf<TNewState extends State>(options?: ValidationOptions<TNewState>): EndpointBuilder<TResponse, TParams, TQuery, TBody, TNewState, TRequestHeaders, TResponseHeaders>;
32
+ /**
33
+ * @deprecated Pass `{ schema }` instead.
34
+ */
18
35
  stateOf<TNewState extends State>(schema?: zod.Schema<TNewState>): EndpointBuilder<TResponse, TParams, TQuery, TBody, TNewState, TRequestHeaders, TResponseHeaders>;
19
36
  requestHeadersOf<TNewRequestHeaders extends RawHeaders>(): EndpointBuilder<TResponse, TParams, TQuery, TBody, TState, TNewRequestHeaders, TResponseHeaders>;
20
37
  responseHeadersOf<TNewResponseHeaders extends RawHeaders>(): EndpointBuilder<TResponse, TParams, TQuery, TBody, TState, TRequestHeaders, TNewResponseHeaders>;
@@ -1,26 +1,54 @@
1
- import Endpoint from "./Endpoint";
1
+ import Endpoint from "./Endpoint.js";
2
+ const isSchema = (value) => {
3
+ return value !== undefined && "parse" in value;
4
+ };
5
+ const warnDeprecatedSchemaArgument = (methodName) => {
6
+ console.warn(`[api-def] ${methodName}(schema) is deprecated. Use ${methodName}({ schema }) instead.`);
7
+ };
2
8
  export default class EndpointBuilder {
3
9
  constructor(api) {
4
10
  this.validation = {};
5
11
  this.api = api;
6
12
  }
7
- queryOf(schema) {
8
- this.validation.query = schema;
13
+ queryOf(optionsOrSchema) {
14
+ if (optionsOrSchema && isSchema(optionsOrSchema)) {
15
+ warnDeprecatedSchemaArgument("queryOf");
16
+ this.validation.query = optionsOrSchema;
17
+ return this;
18
+ }
19
+ this.validation.query = optionsOrSchema?.schema;
9
20
  return this;
10
21
  }
11
22
  paramsOf() {
12
23
  return this;
13
24
  }
14
- bodyOf(schema) {
15
- this.validation.body = schema;
25
+ bodyOf(optionsOrSchema) {
26
+ if (optionsOrSchema && isSchema(optionsOrSchema)) {
27
+ warnDeprecatedSchemaArgument("bodyOf");
28
+ this.validation.body = optionsOrSchema;
29
+ this.validation.bodyEncoding = "application/json";
30
+ return this;
31
+ }
32
+ this.validation.body = optionsOrSchema?.schema;
33
+ this.validation.bodyEncoding = optionsOrSchema?.encoding ?? "application/json";
16
34
  return this;
17
35
  }
18
- responseOf(schema) {
19
- this.validation.response = schema;
36
+ responseOf(optionsOrSchema) {
37
+ if (optionsOrSchema && isSchema(optionsOrSchema)) {
38
+ warnDeprecatedSchemaArgument("responseOf");
39
+ this.validation.response = optionsOrSchema;
40
+ return this;
41
+ }
42
+ this.validation.response = optionsOrSchema?.schema;
20
43
  return this;
21
44
  }
22
- stateOf(schema) {
23
- this.validation.state = schema;
45
+ stateOf(optionsOrSchema) {
46
+ if (optionsOrSchema && isSchema(optionsOrSchema)) {
47
+ warnDeprecatedSchemaArgument("stateOf");
48
+ this.validation.state = optionsOrSchema;
49
+ return this;
50
+ }
51
+ this.validation.state = optionsOrSchema?.schema;
24
52
  return this;
25
53
  }
26
54
  requestHeadersOf() {
@@ -30,7 +58,7 @@ export default class EndpointBuilder {
30
58
  return this;
31
59
  }
32
60
  build(options) {
33
- const endpoint = new Endpoint(this.api, Object.assign(Object.assign({}, options), { validation: this.validation }));
61
+ const endpoint = new Endpoint(this.api, { ...options, validation: this.validation });
34
62
  this.api.endpoints[endpoint.id] = endpoint;
35
63
  return endpoint;
36
64
  }
@@ -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>;