keq 2.9.0 → 2.10.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 (151) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/esm/src/constant.d.ts +2 -0
  3. package/dist/esm/src/constant.js +2 -0
  4. package/dist/esm/src/core.d.ts +30 -0
  5. package/dist/esm/src/core.js +162 -53
  6. package/dist/esm/src/exception/abort.exception.d.ts +3 -0
  7. package/dist/esm/src/exception/abort.exception.js +6 -0
  8. package/dist/esm/src/index.d.ts +1 -0
  9. package/dist/esm/src/index.js +1 -0
  10. package/dist/esm/src/is/is-abort-signal.d.ts +1 -0
  11. package/dist/esm/src/is/is-abort-signal.js +8 -0
  12. package/dist/esm/src/middlewares/fetch-arguments-middleware.js +5 -1
  13. package/dist/esm/src/middlewares/retry-middleware.js +20 -3
  14. package/dist/esm/src/middlewares/timeout-middleware.js +3 -1
  15. package/dist/esm/src/types/keq-context.d.ts +10 -1
  16. package/dist/esm/src/types/keq-context.js +1 -1
  17. package/dist/umd/src/constant.d.ts +2 -0
  18. package/dist/umd/src/constant.js +3 -1
  19. package/dist/umd/src/core.d.ts +30 -0
  20. package/dist/umd/src/core.js +162 -53
  21. package/dist/umd/src/exception/abort.exception.d.ts +3 -0
  22. package/dist/umd/src/exception/abort.exception.js +20 -0
  23. package/dist/umd/src/index.d.ts +1 -0
  24. package/dist/umd/src/index.js +4 -2
  25. package/dist/umd/src/is/is-abort-signal.d.ts +1 -0
  26. package/dist/umd/src/is/is-abort-signal.js +22 -0
  27. package/dist/umd/src/middlewares/fetch-arguments-middleware.js +4 -0
  28. package/dist/umd/src/middlewares/retry-middleware.js +21 -4
  29. package/dist/umd/src/middlewares/timeout-middleware.js +4 -2
  30. package/dist/umd/src/types/keq-context.d.ts +10 -1
  31. package/package.json +10 -13
  32. package/.claude/settings.local.json +0 -26
  33. package/packages/cache/.turbo/turbo-build.log +0 -29
  34. package/packages/cache/dist/index.d.mts +0 -354
  35. package/packages/cache/dist/index.d.mts.map +0 -1
  36. package/packages/cache/dist/index.d.ts +0 -353
  37. package/packages/cache/dist/index.d.ts.map +0 -1
  38. package/packages/cache/dist/index.js +0 -1271
  39. package/packages/cache/dist/index.js.map +0 -1
  40. package/packages/cache/dist/index.mjs +0 -1237
  41. package/packages/cache/dist/index.mjs.map +0 -1
  42. package/packages/cli/.turbo/turbo-build.log +0 -91
  43. package/packages/cli/dist/cli.cjs +0 -1364
  44. package/packages/cli/dist/cli.cjs.map +0 -1
  45. package/packages/cli/dist/cli.d.cts +0 -1
  46. package/packages/cli/dist/cli.d.mts +0 -1
  47. package/packages/cli/dist/cli.mjs +0 -1359
  48. package/packages/cli/dist/cli.mjs.map +0 -1
  49. package/packages/cli/dist/compiler-0Kli6UCr.cjs +0 -738
  50. package/packages/cli/dist/compiler-0Kli6UCr.cjs.map +0 -1
  51. package/packages/cli/dist/compiler-C3AE8j54.mjs +0 -715
  52. package/packages/cli/dist/compiler-C3AE8j54.mjs.map +0 -1
  53. package/packages/cli/dist/index.cjs +0 -20
  54. package/packages/cli/dist/index.cjs.map +0 -1
  55. package/packages/cli/dist/index.d.cts +0 -17
  56. package/packages/cli/dist/index.d.cts.map +0 -1
  57. package/packages/cli/dist/index.d.mts +0 -17
  58. package/packages/cli/dist/index.d.mts.map +0 -1
  59. package/packages/cli/dist/index.mjs +0 -10
  60. package/packages/cli/dist/index.mjs.map +0 -1
  61. package/packages/cli/dist/init-BNhD2oCI.mjs +0 -168
  62. package/packages/cli/dist/init-BNhD2oCI.mjs.map +0 -1
  63. package/packages/cli/dist/init-DqxLcRSQ.cjs +0 -170
  64. package/packages/cli/dist/init-DqxLcRSQ.cjs.map +0 -1
  65. package/packages/cli/dist/logger-D7PyVZo3.cjs +0 -46
  66. package/packages/cli/dist/logger-D7PyVZo3.cjs.map +0 -1
  67. package/packages/cli/dist/logger-QLBHySQ3.mjs +0 -12
  68. package/packages/cli/dist/logger-QLBHySQ3.mjs.map +0 -1
  69. package/packages/cli/dist/micro-function.translator-BmJZzkKh.cjs +0 -16
  70. package/packages/cli/dist/micro-function.translator-BmJZzkKh.cjs.map +0 -1
  71. package/packages/cli/dist/micro-function.translator-CDfkj4Tt.mjs +0 -11
  72. package/packages/cli/dist/micro-function.translator-CDfkj4Tt.mjs.map +0 -1
  73. package/packages/cli/dist/mock-command-Bp1LxSls.mjs +0 -350
  74. package/packages/cli/dist/mock-command-Bp1LxSls.mjs.map +0 -1
  75. package/packages/cli/dist/mock-command-WZcfy5Iq.cjs +0 -353
  76. package/packages/cli/dist/mock-command-WZcfy5Iq.cjs.map +0 -1
  77. package/packages/cli/dist/plugins-CgMhaNZq.cjs +0 -3558
  78. package/packages/cli/dist/plugins-CgMhaNZq.cjs.map +0 -1
  79. package/packages/cli/dist/plugins-DCvJ8iHR.mjs +0 -3280
  80. package/packages/cli/dist/plugins-DCvJ8iHR.mjs.map +0 -1
  81. package/packages/cli/dist/plugins.cjs +0 -36
  82. package/packages/cli/dist/plugins.d.cts +0 -2
  83. package/packages/cli/dist/plugins.d.mts +0 -2
  84. package/packages/cli/dist/plugins.mjs +0 -2
  85. package/packages/cli/dist/runtime-config-BWQlPhiB.d.cts +0 -780
  86. package/packages/cli/dist/runtime-config-BWQlPhiB.d.cts.map +0 -1
  87. package/packages/cli/dist/runtime-config-CrzK-Ucf.d.mts +0 -780
  88. package/packages/cli/dist/runtime-config-CrzK-Ucf.d.mts.map +0 -1
  89. package/packages/cli/dist/translators.cjs +0 -14
  90. package/packages/cli/dist/translators.cjs.map +0 -1
  91. package/packages/cli/dist/translators.d.cts +0 -14
  92. package/packages/cli/dist/translators.d.cts.map +0 -1
  93. package/packages/cli/dist/translators.d.mts +0 -14
  94. package/packages/cli/dist/translators.d.mts.map +0 -1
  95. package/packages/cli/dist/translators.mjs +0 -12
  96. package/packages/cli/dist/translators.mjs.map +0 -1
  97. package/packages/cli/node_modules/.bin/eslint +0 -21
  98. package/packages/cli/node_modules/.bin/jiti +0 -21
  99. package/packages/cli/node_modules/.bin/js-yaml +0 -21
  100. package/packages/cli/node_modules/.bin/jsf +0 -21
  101. package/packages/cli/node_modules/.bin/jsonpath +0 -21
  102. package/packages/cli/node_modules/.bin/jsonpath-plus +0 -21
  103. package/packages/cli/node_modules/.bin/semver +0 -21
  104. package/packages/cli/node_modules/.bin/tsc +0 -21
  105. package/packages/cli/node_modules/.bin/tsserver +0 -21
  106. package/packages/exception/.turbo/turbo-build.log +0 -29
  107. package/packages/exception/dist/index.d.mts +0 -21
  108. package/packages/exception/dist/index.d.mts.map +0 -1
  109. package/packages/exception/dist/index.d.ts +0 -21
  110. package/packages/exception/dist/index.d.ts.map +0 -1
  111. package/packages/exception/dist/index.js +0 -104
  112. package/packages/exception/dist/index.js.map +0 -1
  113. package/packages/exception/dist/index.mjs +0 -99
  114. package/packages/exception/dist/index.mjs.map +0 -1
  115. package/packages/headers/.turbo/turbo-build.log +0 -29
  116. package/packages/headers/dist/index.d.mts +0 -46
  117. package/packages/headers/dist/index.d.mts.map +0 -1
  118. package/packages/headers/dist/index.d.ts +0 -46
  119. package/packages/headers/dist/index.d.ts.map +0 -1
  120. package/packages/headers/dist/index.js +0 -81
  121. package/packages/headers/dist/index.js.map +0 -1
  122. package/packages/headers/dist/index.mjs +0 -75
  123. package/packages/headers/dist/index.mjs.map +0 -1
  124. package/packages/keq/.turbo/turbo-build.log +0 -29
  125. package/packages/keq/dist/index.d.mts +0 -962
  126. package/packages/keq/dist/index.d.mts.map +0 -1
  127. package/packages/keq/dist/index.d.ts +0 -962
  128. package/packages/keq/dist/index.d.ts.map +0 -1
  129. package/packages/keq/dist/index.js +0 -1876
  130. package/packages/keq/dist/index.js.map +0 -1
  131. package/packages/keq/dist/index.mjs +0 -1814
  132. package/packages/keq/dist/index.mjs.map +0 -1
  133. package/packages/nestjs/.turbo/turbo-build.log +0 -29
  134. package/packages/nestjs/dist/index.d.mts +0 -52
  135. package/packages/nestjs/dist/index.d.mts.map +0 -1
  136. package/packages/nestjs/dist/index.d.ts +0 -52
  137. package/packages/nestjs/dist/index.d.ts.map +0 -1
  138. package/packages/nestjs/dist/index.js +0 -166
  139. package/packages/nestjs/dist/index.js.map +0 -1
  140. package/packages/nestjs/dist/index.mjs +0 -136
  141. package/packages/nestjs/dist/index.mjs.map +0 -1
  142. package/packages/test/.turbo/turbo-build.log +0 -6
  143. package/packages/url/.turbo/turbo-build.log +0 -29
  144. package/packages/url/dist/index.d.mts +0 -9
  145. package/packages/url/dist/index.d.mts.map +0 -1
  146. package/packages/url/dist/index.d.ts +0 -9
  147. package/packages/url/dist/index.d.ts.map +0 -1
  148. package/packages/url/dist/index.js +0 -43
  149. package/packages/url/dist/index.js.map +0 -1
  150. package/packages/url/dist/index.mjs +0 -40
  151. package/packages/url/dist/index.mjs.map +0 -1
@@ -1,1876 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __copyProps = (to, from, except, desc) => {
10
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
- key = keys[i];
12
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
- get: ((k) => from[k]).bind(null, key),
14
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
- });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
- value: mod,
21
- enumerable: true
22
- }) : target, mod));
23
- //#endregion
24
- let ts_custom_error = require("ts-custom-error");
25
- let _opendoc_uri_template = require("@opendoc/uri-template");
26
- let mitt = require("mitt");
27
- mitt = __toESM(mitt);
28
- let klona = require("klona");
29
- let klona_json = require("klona/json");
30
- let eventsource_parser_stream = require("eventsource-parser/stream");
31
- let qs = require("qs");
32
- qs = __toESM(qs);
33
- let picomatch = require("picomatch");
34
- picomatch = __toESM(picomatch);
35
- let fastq = require("fastq");
36
- fastq = __toESM(fastq);
37
- //#region src/exception/exception.ts
38
- var Exception = class extends ts_custom_error.CustomError {
39
- constructor(message) {
40
- super(message);
41
- Object.defineProperty(this, "name", { value: "KeqError" });
42
- }
43
- };
44
- //#endregion
45
- //#region src/exception/type.exception.ts
46
- var TypeException = class extends Exception {
47
- constructor(msg) {
48
- super(msg || "Invalid Type");
49
- }
50
- };
51
- //#endregion
52
- //#region src/exception/abort.exception.ts
53
- var AbortException = class AbortException extends DOMException {
54
- constructor(msg) {
55
- super(msg, "AbortError");
56
- Object.setPrototypeOf(this, AbortException.prototype);
57
- }
58
- };
59
- //#endregion
60
- //#region src/exception/timeout.exception.ts
61
- var TimeoutException = class extends AbortException {
62
- constructor(msg) {
63
- super(msg);
64
- }
65
- };
66
- //#endregion
67
- //#region src/exception/mutex.exception.ts
68
- var MutexException = class extends Exception {
69
- constructor(message) {
70
- super(message);
71
- Object.defineProperty(this, "name", { value: "MutexException" });
72
- }
73
- };
74
- //#endregion
75
- //#region \0@oxc-project+runtime@0.127.0/helpers/typeof.js
76
- function _typeof(o) {
77
- "@babel/helpers - typeof";
78
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
79
- return typeof o;
80
- } : function(o) {
81
- return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
82
- }, _typeof(o);
83
- }
84
- //#endregion
85
- //#region \0@oxc-project+runtime@0.127.0/helpers/toPrimitive.js
86
- function toPrimitive(t, r) {
87
- if ("object" != _typeof(t) || !t) return t;
88
- var e = t[Symbol.toPrimitive];
89
- if (void 0 !== e) {
90
- var i = e.call(t, r || "default");
91
- if ("object" != _typeof(i)) return i;
92
- throw new TypeError("@@toPrimitive must return a primitive value.");
93
- }
94
- return ("string" === r ? String : Number)(t);
95
- }
96
- //#endregion
97
- //#region \0@oxc-project+runtime@0.127.0/helpers/toPropertyKey.js
98
- function toPropertyKey(t) {
99
- var i = toPrimitive(t, "string");
100
- return "symbol" == _typeof(i) ? i : i + "";
101
- }
102
- //#endregion
103
- //#region \0@oxc-project+runtime@0.127.0/helpers/defineProperty.js
104
- function _defineProperty(e, r, t) {
105
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
106
- value: t,
107
- enumerable: !0,
108
- configurable: !0,
109
- writable: !0
110
- }) : e[r] = t, e;
111
- }
112
- //#endregion
113
- //#region src/exception/http-exceptions/request.exception.ts
114
- var RequestException = class extends Exception {
115
- constructor(statusCode, message, options) {
116
- super(message);
117
- _defineProperty(this, "statusCode", void 0);
118
- _defineProperty(this, "retry", void 0);
119
- _defineProperty(this, "response", void 0);
120
- this.statusCode = statusCode;
121
- this.retry = !options?.fatal;
122
- this.response = options?.response;
123
- Object.defineProperty(this, "name", { value: "RequestException" });
124
- }
125
- };
126
- //#endregion
127
- //#region src/exception/http-exceptions/bad-request.exception.ts
128
- var BadRequestException = class extends RequestException {
129
- constructor(message = "Bad Request", options) {
130
- super(400, message, {
131
- fatal: true,
132
- ...options
133
- });
134
- Object.defineProperty(this, "name", { value: "BadRequestException" });
135
- }
136
- };
137
- //#endregion
138
- //#region src/exception/http-exceptions/unauthorized.exception.ts
139
- var UnauthorizedException = class extends RequestException {
140
- constructor(message = "Unauthorized", options) {
141
- super(401, message, {
142
- fatal: true,
143
- ...options
144
- });
145
- Object.defineProperty(this, "name", { value: "UnauthorizedException" });
146
- }
147
- };
148
- //#endregion
149
- //#region src/exception/http-exceptions/forbidden.exception.ts
150
- var ForbiddenException = class extends RequestException {
151
- constructor(message = "Forbidden", options) {
152
- super(403, message, {
153
- fatal: true,
154
- ...options
155
- });
156
- Object.defineProperty(this, "name", { value: "ForbiddenException" });
157
- }
158
- };
159
- //#endregion
160
- //#region src/exception/http-exceptions/not-founded.exception.ts
161
- var NotFoundedException = class extends RequestException {
162
- constructor(message = "Not Founded", options) {
163
- super(404, message, {
164
- fatal: true,
165
- ...options
166
- });
167
- Object.defineProperty(this, "name", { value: "NotFoundedException" });
168
- }
169
- };
170
- //#endregion
171
- //#region src/exception/http-exceptions/method-not-allowed.exception.ts
172
- var MethodNotAllowedException = class extends RequestException {
173
- constructor(message = "Method Not Allowed", options) {
174
- super(405, message, {
175
- fatal: true,
176
- ...options
177
- });
178
- Object.defineProperty(this, "name", { value: "MethodNotAllowedException" });
179
- }
180
- };
181
- //#endregion
182
- //#region src/exception/http-exceptions/not-acceptable.exception.ts
183
- var NotAcceptableException = class extends RequestException {
184
- constructor(message = "Not Acceptable", options) {
185
- super(406, message, {
186
- fatal: true,
187
- ...options
188
- });
189
- Object.defineProperty(this, "name", { value: "NotAcceptableException" });
190
- }
191
- };
192
- //#endregion
193
- //#region src/exception/http-exceptions/proxy-authentication-required.exception.ts
194
- var ProxyAuthenticationRequiredException = class extends RequestException {
195
- constructor(message = "Proxy Authentication Required", options) {
196
- super(407, message, {
197
- fatal: true,
198
- ...options
199
- });
200
- Object.defineProperty(this, "name", { value: "ProxyAuthenticationRequiredException" });
201
- }
202
- };
203
- //#endregion
204
- //#region src/exception/http-exceptions/request-timeout.exception.ts
205
- var RequestTimeoutException = class extends RequestException {
206
- constructor(message = "Request Timeout", options) {
207
- super(408, message, {
208
- fatal: false,
209
- ...options
210
- });
211
- Object.defineProperty(this, "name", { value: "RequestTimeoutException" });
212
- }
213
- };
214
- //#endregion
215
- //#region src/exception/http-exceptions/conflict.exception.ts
216
- var ConflictException = class extends RequestException {
217
- constructor(message = "Conflict", options) {
218
- super(409, message, {
219
- fatal: true,
220
- ...options
221
- });
222
- Object.defineProperty(this, "name", { value: "ConflictException" });
223
- }
224
- };
225
- //#endregion
226
- //#region src/exception/http-exceptions/precondition-failed.exception.ts
227
- var PreconditionFailedException = class extends RequestException {
228
- constructor(message = "Precondition Failed", options) {
229
- super(412, message, {
230
- fatal: true,
231
- ...options
232
- });
233
- Object.defineProperty(this, "name", { value: "PreconditionFailedException" });
234
- }
235
- };
236
- //#endregion
237
- //#region src/exception/http-exceptions/content-too-large.exception.ts
238
- var ContentTooLargeException = class extends RequestException {
239
- constructor(message = "Content Too Large", options) {
240
- super(413, message, {
241
- fatal: true,
242
- ...options
243
- });
244
- Object.defineProperty(this, "name", { value: "ContentTooLargeException" });
245
- }
246
- };
247
- //#endregion
248
- //#region src/exception/http-exceptions/uri-too-long.exception.ts
249
- var UriTooLongException = class extends RequestException {
250
- constructor(message = "URI Too Long", options) {
251
- super(414, message, {
252
- fatal: true,
253
- ...options
254
- });
255
- Object.defineProperty(this, "name", { value: "UriTooLongException" });
256
- }
257
- };
258
- //#endregion
259
- //#region src/exception/http-exceptions/unsupported-media-type.exception.ts
260
- var UnsupportedMediaTypeException = class extends RequestException {
261
- constructor(message = "Unsupported Media Type", options) {
262
- super(415, message, {
263
- fatal: true,
264
- ...options
265
- });
266
- Object.defineProperty(this, "name", { value: "UnsupportedMediaTypeException" });
267
- }
268
- };
269
- //#endregion
270
- //#region src/exception/http-exceptions/im-a-teapot.exception.ts
271
- var ImATeapotException = class extends RequestException {
272
- constructor(message = "I'm a teapot", options) {
273
- super(418, message, {
274
- fatal: true,
275
- ...options
276
- });
277
- Object.defineProperty(this, "name", { value: "ImATeapotException" });
278
- }
279
- };
280
- //#endregion
281
- //#region src/exception/http-exceptions/too-many-requests.exception.ts
282
- var TooManyRequestsException = class extends RequestException {
283
- constructor(message = "Too Many Requests", options) {
284
- super(429, message, {
285
- fatal: false,
286
- ...options
287
- });
288
- Object.defineProperty(this, "name", { value: "TooManyRequestsException" });
289
- }
290
- };
291
- //#endregion
292
- //#region src/exception/http-exceptions/internal-server-error.exception.ts
293
- var InternalServerErrorException = class extends RequestException {
294
- constructor(message = "Internal Server Error", options) {
295
- super(500, message, {
296
- fatal: false,
297
- ...options
298
- });
299
- Object.defineProperty(this, "name", { value: "InternalServerErrorException" });
300
- }
301
- };
302
- //#endregion
303
- //#region src/exception/http-exceptions/not-implemented.exception.ts
304
- var NotImplementedException = class extends RequestException {
305
- constructor(message = "Not Implemented", options) {
306
- super(501, message, {
307
- fatal: true,
308
- ...options
309
- });
310
- Object.defineProperty(this, "name", { value: "NotImplementedException" });
311
- }
312
- };
313
- //#endregion
314
- //#region src/exception/http-exceptions/bad-gateway.exception.ts
315
- var BadGatewayException = class extends RequestException {
316
- constructor(message = "Bad Gateway", options) {
317
- super(502, message, {
318
- fatal: false,
319
- ...options
320
- });
321
- Object.defineProperty(this, "name", { value: "BadGatewayException" });
322
- }
323
- };
324
- //#endregion
325
- //#region src/exception/http-exceptions/service-unavailable.exception.ts
326
- var ServiceUnavailableException = class extends RequestException {
327
- constructor(message = "Service Unavailable", options) {
328
- super(503, message, {
329
- fatal: false,
330
- ...options
331
- });
332
- Object.defineProperty(this, "name", { value: "ServiceUnavailableException" });
333
- }
334
- };
335
- //#endregion
336
- //#region src/exception/http-exceptions/gateway-timeout.exception.ts
337
- var GatewayTimeoutException = class extends RequestException {
338
- constructor(message = "Gateway Timeout", options) {
339
- super(504, message, {
340
- fatal: false,
341
- ...options
342
- });
343
- Object.defineProperty(this, "name", { value: "GatewayTimeoutException" });
344
- }
345
- };
346
- //#endregion
347
- //#region src/utils/base64.ts
348
- const base64Encode = globalThis.btoa || ((str) => Buffer.from(str).toString("base64"));
349
- globalThis.atob;
350
- //#endregion
351
- //#region src/validator/validator.ts
352
- /**
353
- * Validator 类用于类型检查
354
- */
355
- var Validator = class Validator {
356
- /**
357
- * 检查是否为浏览器环境
358
- */
359
- static isBrowser() {
360
- return typeof window !== "undefined";
361
- }
362
- /**
363
- * 检查是否为字符串
364
- */
365
- static isString(value) {
366
- return typeof value === "string";
367
- }
368
- /**
369
- * 检查是否为对象
370
- */
371
- static isObject(value) {
372
- return typeof value === "object" && value !== null;
373
- }
374
- /**
375
- * 检查是否为函数
376
- */
377
- static isFunction(value) {
378
- return typeof value === "function";
379
- }
380
- /**
381
- * 检查是否为 ArrayBuffer
382
- */
383
- static isArrayBuffer(body) {
384
- return body instanceof ArrayBuffer;
385
- }
386
- /**
387
- * 检查是否为 ReadableStream
388
- */
389
- static isReadableStream(body) {
390
- return body instanceof ReadableStream;
391
- }
392
- /**
393
- * 检查是否为 Blob 或 File 类对象
394
- */
395
- static isBlob(value) {
396
- if (value instanceof Blob) return true;
397
- return Validator.isObject(value) && Validator.isString(value["type"]) && Validator.isFunction(value["arrayBuffer"]) && Validator.isFunction(value["stream"]) && Validator.isFunction(value.constructor) && ["Blob", "File"].includes(value.constructor.name) && "size" in value;
398
- }
399
- /**
400
- * 检查是否为 File
401
- */
402
- static isFile(object) {
403
- if (Validator.isBrowser()) return object instanceof Blob;
404
- return Validator.isBlob(object);
405
- }
406
- /**
407
- * 检查是否为 Buffer
408
- */
409
- static isBuffer(obj) {
410
- return Validator.isBrowser() ? false : Buffer.isBuffer(obj);
411
- }
412
- /**
413
- * 检查是否为 FormData
414
- */
415
- static isFormData(object) {
416
- if (object instanceof FormData) return true;
417
- return Validator.isObject(object) && Validator.isFunction(object["append"]) && Validator.isFunction(object["delete"]) && Validator.isFunction(object["get"]) && Validator.isFunction(object["getAll"]) && Validator.isFunction(object["has"]) && Validator.isFunction(object["set"]) && Validator.isFunction(object["entries"]) && Validator.isFunction(object["keys"]) && Validator.isFunction(object["values"]);
418
- }
419
- /**
420
- * 检查是否为 Headers
421
- */
422
- static isHeaders(obj) {
423
- if (obj instanceof Headers) return true;
424
- if (Validator.isObject(obj) && Validator.isFunction(obj["forEach"]) && Validator.isFunction(obj["get"]) && Validator.isFunction(obj["has"]) && Validator.isFunction(obj["set"]) && Validator.isFunction(obj["append"]) && Validator.isFunction(obj["delete"]) && Validator.isFunction(obj["entries"]) && Validator.isFunction(obj["keys"]) && Validator.isFunction(obj["values"])) return true;
425
- return false;
426
- }
427
- /**
428
- * 检查是否为 URLSearchParams
429
- */
430
- static isUrlSearchParams(obj) {
431
- if (obj instanceof URLSearchParams) return true;
432
- return Validator.isObject(obj) && Validator.isFunction(obj["append"]) && Validator.isFunction(obj["delete"]) && Validator.isFunction(obj["entries"]) && Validator.isFunction(obj["forEach"]) && Validator.isFunction(obj["get"]) && Validator.isFunction(obj["getAll"]) && Validator.isFunction(obj["has"]) && Validator.isFunction(obj["keys"]) && Validator.isFunction(obj["set"]) && Validator.isFunction(obj["values"]) && Validator.isFunction(obj["sort"]) && Validator.isFunction(obj["toString"]);
433
- }
434
- /**
435
- * 检查是否为合法的 Header 值
436
- * 允许范围: HTAB(\t), 0x20-0x7E, 0x80-0xFF
437
- * 禁止换行等控制字符
438
- */
439
- static isHeaderValue(str) {
440
- return /^[\t\x20-\x7E\x80-\xFF]*$/.test(String(str));
441
- }
442
- /**
443
- * 检查是否为 BodyInit 类型
444
- * BodyInit 包括: Blob | ArrayBuffer | TypedArray | DataView | FormData | URLSearchParams | ReadableStream | string
445
- */
446
- static isBodyInit(value) {
447
- if (value === null || value === void 0) return false;
448
- return Validator.isString(value) || Validator.isBlob(value) || Validator.isArrayBuffer(value) || Validator.isFormData(value) || Validator.isUrlSearchParams(value) || Validator.isReadableStream(value) || Validator.isBuffer(value) || ArrayBuffer.isView(value);
449
- }
450
- };
451
- //#endregion
452
- //#region src/utils/shallow-clone.ts
453
- /**
454
- * @description 浅拷贝
455
- */
456
- function shallowClone(obj) {
457
- if (Array.isArray(obj)) return [...obj];
458
- if (Validator.isObject(obj)) return { ...obj };
459
- return obj;
460
- }
461
- //#endregion
462
- //#region src/utils/sleep.ts
463
- function sleep(ms) {
464
- return new Promise((resolve) => setTimeout(resolve, ms));
465
- }
466
- //#endregion
467
- //#region src/request-init/utils/clone-body.ts
468
- function cloneBody(obj) {
469
- if (Validator.isFormData(obj)) {
470
- const formData = new FormData();
471
- for (const [key, value] of obj.entries()) formData.append(key, value);
472
- return formData;
473
- }
474
- if (Validator.isUrlSearchParams(obj)) {
475
- const urlSearchParams = new URLSearchParams();
476
- for (const [key, value] of obj.entries()) urlSearchParams.append(key, value);
477
- return urlSearchParams;
478
- }
479
- if (Validator.isFile(obj)) return obj;
480
- if (Validator.isBlob(obj)) return obj;
481
- if (Validator.isBuffer(obj)) return obj;
482
- if (obj === null) return null;
483
- if (Array.isArray(obj)) return obj.map(cloneBody);
484
- if (Validator.isObject(obj)) {
485
- const cloned = {};
486
- for (const key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) cloned[key] = cloneBody(obj[key]);
487
- return cloned;
488
- }
489
- return obj;
490
- }
491
- //#endregion
492
- //#region src/request-init/utils/clone-headers.ts
493
- function cloneHeaders(headers) {
494
- const cloned = new Headers();
495
- for (const [key, value] of headers.entries()) cloned.append(key, value);
496
- return cloned;
497
- }
498
- //#endregion
499
- //#region src/request-init/utils/compile-url.ts
500
- function compileUrl(obj, pathParameters) {
501
- const url = new URL(typeof obj === "string" ? obj : obj.href);
502
- url.pathname = new _opendoc_uri_template.UriTemplateParser(decodeURIComponent(url.pathname), pathParameters).expand();
503
- return url;
504
- }
505
- //#endregion
506
- //#region src/request-init/utils/to-form-data.ts
507
- function toFormData(body) {
508
- const form = new FormData();
509
- for (const [key, value] of Object.entries(body)) if (Array.isArray(value)) for (const v of value) form.append(key, v);
510
- else form.append(key, value);
511
- return form;
512
- }
513
- //#endregion
514
- //#region src/request-init/utils/to-url-search-params.ts
515
- function toUrlSearchParams(body) {
516
- const params = new URLSearchParams();
517
- Object.entries(body).map(([key, value]) => {
518
- if (Array.isArray(value)) for (const v of value) params.append(key, v);
519
- else params.append(key, value);
520
- });
521
- return params;
522
- }
523
- //#endregion
524
- //#region src/request-init/utils/clone-request-init.ts
525
- function cloneRequestInit(init) {
526
- return new KeqRequestInit({
527
- url: init.url,
528
- pathParameters: init.pathParameters,
529
- method: init.method,
530
- headers: init.headers,
531
- body: init.body,
532
- cache: init.cache,
533
- credentials: init.credentials,
534
- integrity: init.integrity,
535
- keepalive: init.keepalive,
536
- mode: init.mode,
537
- redirect: init.redirect,
538
- referrer: init.referrer,
539
- referrerPolicy: init.referrerPolicy
540
- });
541
- }
542
- //#endregion
543
- //#region src/request-init/request-init.ts
544
- const AbortControllerProperty = "__KeqProtectedProperty(context.request.abortController)__";
545
- var KeqRequestInit = class {
546
- constructor(options) {
547
- _defineProperty(this, "url", void 0);
548
- _defineProperty(this, "pathParameters", void 0);
549
- _defineProperty(this, "method", void 0);
550
- _defineProperty(this, "headers", void 0);
551
- _defineProperty(this, "body", void 0);
552
- _defineProperty(this, "cache", void 0);
553
- _defineProperty(this, "credentials", void 0);
554
- _defineProperty(this, "integrity", void 0);
555
- _defineProperty(this, "keepalive", void 0);
556
- _defineProperty(this, "mode", void 0);
557
- _defineProperty(this, "redirect", void 0);
558
- _defineProperty(this, "referrer", void 0);
559
- _defineProperty(this, "referrerPolicy", void 0);
560
- _defineProperty(this, AbortControllerProperty, new AbortController());
561
- this.url = new URL(options.url.href);
562
- this.pathParameters = shallowClone(options.pathParameters);
563
- this.method = options.method;
564
- this.headers = cloneHeaders(options.headers);
565
- this.body = cloneBody(options.body);
566
- this.cache = options.cache;
567
- this.credentials = options.credentials;
568
- this.integrity = options.integrity;
569
- this.keepalive = options.keepalive;
570
- this.mode = options.mode;
571
- this.redirect = options.redirect;
572
- this.referrer = options.referrer;
573
- this.referrerPolicy = options.referrerPolicy;
574
- }
575
- get __url__() {
576
- return compileUrl(this.url, this.pathParameters);
577
- }
578
- get signal() {
579
- return this[AbortControllerProperty].signal;
580
- }
581
- abort(reason) {
582
- if (!this["__KeqProtectedProperty(context.request.abortController)__"].signal.aborted) this[AbortControllerProperty].abort(reason);
583
- }
584
- getContentType() {
585
- const contentType = this.headers.get("Content-Type");
586
- if (contentType) return contentType;
587
- if (!this.body) return void 0;
588
- if (Validator.isFormData(this.body)) return "multipart/form-data";
589
- if (Validator.isUrlSearchParams(this.body)) return "application/x-www-form-urlencoded";
590
- if (Validator.isArrayBuffer(this.body)) return "application/octet-stream";
591
- if (typeof this.body === "object") return "application/json";
592
- }
593
- toFetchBody(contentType) {
594
- const body = this.body;
595
- if (body === void 0) return;
596
- if (body === null) return null;
597
- if (Validator.isBodyInit(body)) return body;
598
- if (!contentType || contentType === "application/json") return JSON.stringify(body);
599
- if (contentType === "application/x-www-form-urlencoded") {
600
- if (Array.isArray(body)) throw new Exception("request.body is an array, that cannot be serialized as application/x-www-form-urlencoded format");
601
- return toUrlSearchParams(body);
602
- }
603
- if (contentType === "multipart/form-data") {
604
- if (Array.isArray(body)) throw new Exception("FormData cannot send array");
605
- return toFormData(body);
606
- }
607
- throw new Exception(`Cannot auto serialize request.body with Content-Type: ${contentType}`);
608
- }
609
- toFetchArguments() {
610
- const contentType = this.getContentType();
611
- const headers = cloneHeaders(this.headers);
612
- if (contentType) headers.set("Content-Type", contentType);
613
- const body = this.toFetchBody(contentType);
614
- if (contentType === "multipart/form-data") headers.delete("Content-Type");
615
- const requestInit = {
616
- method: this.method.toUpperCase(),
617
- headers,
618
- body,
619
- cache: this.cache,
620
- credentials: this.credentials,
621
- integrity: this.integrity,
622
- keepalive: this.keepalive,
623
- mode: this.mode,
624
- redirect: this.redirect,
625
- referrer: this.referrer,
626
- referrerPolicy: this.referrerPolicy,
627
- signal: this.signal
628
- };
629
- return [this.__url__.href, requestInit];
630
- }
631
- };
632
- //#endregion
633
- //#region src/context/orchestrator-context.ts
634
- const OrchestratorProperty = "__KeyProtectedProperty(context.orchestration.orchestrator)__";
635
- const ExecutorProperty$1 = "__KeyProtectedProperty(context.orchestration.executor)__";
636
- var KeqOrchestratorContext = class {
637
- constructor(orchestrator, executor) {
638
- _defineProperty(this, OrchestratorProperty, void 0);
639
- _defineProperty(this, ExecutorProperty$1, void 0);
640
- this[OrchestratorProperty] = orchestrator;
641
- this[ExecutorProperty$1] = executor;
642
- }
643
- get middlewares() {
644
- return this[OrchestratorProperty].executors.map((exe) => exe.context);
645
- }
646
- /**
647
- * The middleware context of the current middleware
648
- */
649
- get middleware() {
650
- return this[ExecutorProperty$1].context;
651
- }
652
- fork() {
653
- return this[OrchestratorProperty].fork();
654
- }
655
- merge(source) {
656
- this[OrchestratorProperty].merge(source);
657
- }
658
- };
659
- //#endregion
660
- //#region src/context/execution-context.ts
661
- const ContextOrchestratorProperty = "__KeyProtectedProperty(context.orchestrator)__";
662
- const ContextOrchestrationProperty = "__KeyProtectedProperty(context.orchestration)__";
663
- var KeqExecutionContext = class {
664
- constructor(orchestrator, executor) {
665
- _defineProperty(this, ContextOrchestratorProperty, void 0);
666
- _defineProperty(this, ContextOrchestrationProperty, void 0);
667
- this[ContextOrchestratorProperty] = orchestrator;
668
- this[ContextOrchestrationProperty] = new KeqOrchestratorContext(orchestrator, executor);
669
- }
670
- get orchestration() {
671
- return this[ContextOrchestrationProperty];
672
- }
673
- /**
674
- * The unique identifier of the request's location in the code
675
- */
676
- get locationId() {
677
- return this[ContextOrchestratorProperty].context.locationId;
678
- }
679
- get request() {
680
- return this[ContextOrchestratorProperty].context.request;
681
- }
682
- get global() {
683
- return this[ContextOrchestratorProperty].context.global;
684
- }
685
- get emitter() {
686
- return this[ContextOrchestratorProperty].context.emitter;
687
- }
688
- get options() {
689
- return this[ContextOrchestratorProperty].context.options;
690
- }
691
- set output(value) {
692
- if (this.options.resolveWith && this.options.resolveWith !== "intelligent") console.warn(`The request is configured to resolve with ${this.options.resolveWith}, so setting context.output maybe no effect.`);
693
- this[ContextOrchestratorProperty].context.output = value;
694
- }
695
- get res() {
696
- return this[ContextOrchestratorProperty].context.res;
697
- }
698
- set res(value) {
699
- this[ContextOrchestratorProperty].context.res = value;
700
- }
701
- get response() {
702
- return this[ContextOrchestratorProperty].context.response;
703
- }
704
- get data() {
705
- return this[ContextOrchestratorProperty].context.data;
706
- }
707
- };
708
- //#endregion
709
- //#region src/context/utils/watch-object.ts
710
- function watchObject(obj, listeners) {
711
- return new Proxy(obj, { get(target, prop) {
712
- if (prop in listeners) return new Proxy(target[prop], { apply(target, thisArg, argArray) {
713
- const listener = listeners[prop];
714
- listener(target, thisArg, argArray);
715
- return target.apply(thisArg, argArray);
716
- } });
717
- return target[prop];
718
- } });
719
- }
720
- //#endregion
721
- //#region src/context/utils/clone-shared-context.ts
722
- function cloneSharedContext(context) {
723
- const cloned = new KeqSharedContext({
724
- locationId: context[ContextLocationIdProperty],
725
- request: cloneRequestInit(context[ContextRequestProperty]),
726
- global: context[ContextGlobalProperty],
727
- options: (0, klona.klona)(context[ContextOptionsProperty]),
728
- data: (0, klona.klona)(context[ContextDataProperty])
729
- });
730
- context[ContextEmitterProperty].all.forEach((handlers, type) => {
731
- for (const handler of handlers) cloned.emitter.on(type, handler);
732
- });
733
- return cloned;
734
- }
735
- //#endregion
736
- //#region src/context/utils/fork.ts
737
- const ForkedObjectBrandPropertyKey = "__KeqProtectedProperty(forked.object.brand)__";
738
- const ARRAY_MUTATORS = new Set([
739
- "push",
740
- "pop",
741
- "shift",
742
- "unshift",
743
- "splice",
744
- "sort",
745
- "reverse",
746
- "fill",
747
- "copyWithin"
748
- ]);
749
- function objectPath(obj, path) {
750
- return path.reduce((o, k) => o[k], obj);
751
- }
752
- /**
753
- * Fork an json object, using copy-on-write strategy to avoid unnecessary deep cloning.
754
- */
755
- function fork(original) {
756
- if (original === null || typeof original !== "object") return original;
757
- let current = original;
758
- const ensureCopy = () => {
759
- if (current === original) current = (0, klona_json.klona)(original);
760
- return current;
761
- };
762
- const createProxy = (path = []) => {
763
- const getTarget = () => objectPath(current, path);
764
- return new Proxy(getTarget(), {
765
- get(target, prop) {
766
- const realTarget = getTarget();
767
- if (prop === ForkedObjectBrandPropertyKey) return realTarget;
768
- const value = realTarget[prop];
769
- if (current !== original) return value;
770
- if (Array.isArray(realTarget) && ARRAY_MUTATORS.has(prop)) return new Proxy(value, { apply(fn, thisArg, args) {
771
- ensureCopy();
772
- const t = objectPath(current, path);
773
- return Reflect.apply(t[prop], t, args);
774
- } });
775
- if (typeof value === "object" && value !== null) return createProxy([...path, prop]);
776
- return value;
777
- },
778
- set(target, prop, value) {
779
- ensureCopy();
780
- objectPath(current, path)[prop] = value;
781
- return true;
782
- },
783
- deleteProperty(target, prop) {
784
- ensureCopy();
785
- delete objectPath(current, path)[prop];
786
- return true;
787
- },
788
- ownKeys(target) {
789
- const realTarget = getTarget();
790
- return Reflect.ownKeys(realTarget);
791
- },
792
- getOwnPropertyDescriptor(target, prop) {
793
- const realTarget = getTarget();
794
- return Reflect.getOwnPropertyDescriptor(realTarget, prop);
795
- }
796
- });
797
- };
798
- return createProxy();
799
- }
800
- function unwrap(proxy) {
801
- return proxy && proxy[ForkedObjectBrandPropertyKey] ? proxy[ForkedObjectBrandPropertyKey] : proxy;
802
- }
803
- //#endregion
804
- //#region src/context/utils/create-proxy-response.ts
805
- const JsonCachePropertyKey = "__KeqProtectedProperty(response.proxy.cache.json)__";
806
- const TextCachePropertyKey = "__KeqProtectedProperty(response.proxy.cache.text)__";
807
- function createProxyResponse(response) {
808
- return new Proxy(response, { get(res, prop) {
809
- if (typeof prop === "string") {
810
- if (prop === "json") return new Proxy(res[prop], { apply() {
811
- if (res[JsonCachePropertyKey]) return fork(res[JsonCachePropertyKey]);
812
- return res.clone().json().then((body) => {
813
- res[JsonCachePropertyKey] = body;
814
- return fork(body);
815
- });
816
- } });
817
- else if (prop === "text") return new Proxy(res[prop], { apply() {
818
- if (res[TextCachePropertyKey]) return fork(res[TextCachePropertyKey]);
819
- return res.clone().text().then((body) => {
820
- res[TextCachePropertyKey] = body;
821
- return body;
822
- });
823
- } });
824
- else if ([
825
- "arrayBuffer",
826
- "blob",
827
- "buffer",
828
- "formData"
829
- ].includes(prop))
830
- /**
831
- * clone when invoking body, json, text, arrayBuffer, blob, buffer, formData
832
- * to avoid time-consuming cloning
833
- */
834
- return new Proxy(res[prop], { apply(target, thisArg, argArray) {
835
- return res.clone()[prop](...argArray);
836
- } });
837
- else if (prop === "body") return res.clone().body;
838
- }
839
- if (typeof res[prop] === "function") return res[prop].bind(res);
840
- return res[prop];
841
- } });
842
- }
843
- //#endregion
844
- //#region src/context/shared-context.ts
845
- const ContextLocationIdProperty = "__KeqProtectedProperty(context.locationId)__";
846
- const ContextRequestProperty = "__KeqProtectedProperty(context.request)__";
847
- const ContextGlobalProperty = "__KeqProtectedProperty(context.global)__";
848
- const ContextEmitterProperty = "__KeqProtectedProperty(context.emitter)__";
849
- const ContextOptionsProperty = "__KeqProtectedProperty(context.options)__";
850
- const ContextDataProperty = "__KeqProtectedProperty(context.data)__";
851
- const ContextOutputProperty = "__KeqProtectedProperty(context.output)__";
852
- var KeqSharedContext = class {
853
- constructor(options) {
854
- _defineProperty(this, ContextLocationIdProperty, void 0);
855
- _defineProperty(this, ContextRequestProperty, void 0);
856
- _defineProperty(this, ContextGlobalProperty, void 0);
857
- _defineProperty(this, ContextEmitterProperty, void 0);
858
- _defineProperty(this, ContextOptionsProperty, void 0);
859
- _defineProperty(this, ContextOutputProperty, void 0);
860
- _defineProperty(this, ContextDataProperty, {});
861
- _defineProperty(
862
- this,
863
- /**
864
- * original response
865
- */
866
- "res",
867
- void 0
868
- );
869
- this[ContextLocationIdProperty] = options.locationId;
870
- this[ContextRequestProperty] = watchObject(new KeqRequestInit(options.request), { abort: (target, thisArg, argArray) => {
871
- this[ContextEmitterProperty].emit("abort", {
872
- context: this,
873
- reason: argArray[0]
874
- });
875
- } });
876
- this[ContextEmitterProperty] = options.emitter || (0, mitt.default)();
877
- this[ContextGlobalProperty] = options.global;
878
- this[ContextOptionsProperty] = options.options ? shallowClone(options.options) : {};
879
- this[ContextDataProperty] = options.data || {};
880
- }
881
- /**
882
- * The unique identifier of the request's location in the code
883
- */
884
- get locationId() {
885
- return this[ContextLocationIdProperty];
886
- }
887
- get request() {
888
- return this[ContextRequestProperty];
889
- }
890
- get global() {
891
- return this[ContextGlobalProperty];
892
- }
893
- get emitter() {
894
- return this[ContextEmitterProperty];
895
- }
896
- get options() {
897
- return this[ContextOptionsProperty];
898
- }
899
- set output(value) {
900
- this[ContextOutputProperty] = value;
901
- }
902
- get response() {
903
- if (!this.res) return void 0;
904
- return createProxyResponse(this.res);
905
- }
906
- get data() {
907
- return this[ContextDataProperty];
908
- }
909
- };
910
- //#endregion
911
- //#region src/middleware/utils/get-middleware-name.ts
912
- function getMiddlewareName(middleware) {
913
- return middleware.__keqMiddlewareName__ || middleware.name || "anonymous";
914
- }
915
- //#endregion
916
- //#region src/middleware/utils/compose-middleware.ts
917
- function composeMiddleware(middlewares, options) {
918
- if (!middlewares.length) throw new TypeException("At least one middleware");
919
- const middleware = [...middlewares].reverse().reduce(function(prev, curr) {
920
- return async (ctx, next) => {
921
- await curr(ctx, async () => prev(ctx, next));
922
- };
923
- });
924
- if (options?.name) middleware.__keqMiddlewareName__ = options.name;
925
- else middleware.__keqMiddlewareName__ = `composeMiddleware(${middlewares.map((i) => getMiddlewareName(i)).join(", ")})`;
926
- return middleware;
927
- }
928
- //#endregion
929
- //#region src/context/middleware-context.ts
930
- const ExecutorProperty = "__KeyProtectedProperty(context.orchestration.middlewares)__";
931
- var KeqMiddlewareContext = class {
932
- constructor(executor) {
933
- _defineProperty(this, ExecutorProperty, void 0);
934
- this[ExecutorProperty] = executor;
935
- }
936
- get name() {
937
- return this[ExecutorProperty].name;
938
- }
939
- get status() {
940
- return this[ExecutorProperty].status;
941
- }
942
- get finished() {
943
- return this.status === "fulfilled" || this.status === "rejected";
944
- }
945
- };
946
- //#endregion
947
- //#region src/orchestrator/executor.ts
948
- var KeqMiddlewareExecutor = class {
949
- constructor(middleware) {
950
- this.middleware = middleware;
951
- _defineProperty(this, "name", void 0);
952
- _defineProperty(this, "status", "idle");
953
- _defineProperty(this, "context", void 0);
954
- this.name = getMiddlewareName(middleware);
955
- this.context = new KeqMiddlewareContext(this);
956
- }
957
- async execute(context, next) {
958
- if (this.status !== "idle") throw new Exception(`Middleware "${this.name}" has already been executed.`);
959
- try {
960
- this.status = "pending";
961
- context.emitter.emit("middleware:before", { context });
962
- await this.middleware(context, next);
963
- context.emitter.emit("middleware:after", { context });
964
- if (this.status === "pending") this.status = "fulfilled";
965
- } catch (error) {
966
- if (this.status === "pending") this.status = "rejected";
967
- throw error;
968
- }
969
- }
970
- };
971
- //#endregion
972
- //#region src/request-init/utils/assign-request-init.ts
973
- function assignRequestInit(target, source) {
974
- target.url = source.url;
975
- target.pathParameters = source.pathParameters;
976
- target.method = source.method;
977
- target.headers = source.headers;
978
- target.body = source.body;
979
- target.cache = source.cache;
980
- target.credentials = source.credentials;
981
- target.integrity = source.integrity;
982
- target.keepalive = source.keepalive;
983
- target.mode = source.mode;
984
- target.redirect = source.redirect;
985
- target.referrer = source.referrer;
986
- target.referrerPolicy = source.referrerPolicy;
987
- target[AbortControllerProperty] = source[AbortControllerProperty];
988
- }
989
- //#endregion
990
- //#region src/context/utils/assign-shared-context.ts
991
- function assignSharedContext(target, source) {
992
- assignRequestInit(target.request, source.request);
993
- Object.assign(target.global, source.global);
994
- Object.assign(target.options, source.options);
995
- Object.assign(target.data, source.data);
996
- target[ContextEmitterProperty] = source[ContextEmitterProperty];
997
- target[ContextOutputProperty] = source[ContextOutputProperty];
998
- target.res = source.res;
999
- }
1000
- //#endregion
1001
- //#region src/orchestrator/orchestrator.ts
1002
- var KeqMiddlewareOrchestrator = class KeqMiddlewareOrchestrator {
1003
- constructor(context, middlewares = [], inherit) {
1004
- _defineProperty(this, "main", void 0);
1005
- _defineProperty(this, "status", "idle");
1006
- _defineProperty(this, "context", void 0);
1007
- _defineProperty(this, "executors", []);
1008
- _defineProperty(this, "current", -1);
1009
- this.context = context;
1010
- this.executors = middlewares.map((mw) => new KeqMiddlewareExecutor(mw));
1011
- if (inherit?.main) this.main = inherit.main;
1012
- }
1013
- cancelNotFinished() {
1014
- const current = this.current;
1015
- for (let i = current + 1; i < this.executors.length; i++) {
1016
- const executor = this.executors[i];
1017
- if (executor.status === "pending") executor.status = "canceled";
1018
- }
1019
- }
1020
- async run() {
1021
- if (this.executors.length === 0) return;
1022
- const executors = [...this.executors];
1023
- const next = async (nextIndex) => {
1024
- if (nextIndex >= executors.length) return;
1025
- const nextExecutor = executors[nextIndex];
1026
- if (nextExecutor.status !== "idle") throw new Exception(`Cannot call next() because the next Middleware(${nextExecutor.name}) status is ${nextExecutor.status}. If you want to re-execute it, please fork a new orchestrator.`);
1027
- if (this.current + 1 !== nextIndex) {
1028
- const parentExecutor = executors[nextIndex - 1];
1029
- throw new Exception(parentExecutor ? `Cannot call next() outside Middleware(${parentExecutor.name}) runtime. You can fork a new orchestration and execute the forked one anywhere.` : "Cannot jump to non-sequential middleware. Please call next() in order.");
1030
- }
1031
- const last = this.current;
1032
- this.current = nextIndex;
1033
- const context = new KeqExecutionContext(this, nextExecutor);
1034
- try {
1035
- await nextExecutor.execute(context, () => next.call(this, nextIndex + 1));
1036
- } finally {
1037
- if (this.current === last + 1) this.current = last;
1038
- else if (this.current > last) {
1039
- this.cancelNotFinished();
1040
- this.current = last;
1041
- }
1042
- }
1043
- };
1044
- await next.call(this, 0);
1045
- }
1046
- async execute() {
1047
- if (this.status !== "idle") throw new Exception("Orchestrator has already been executed.");
1048
- this.status = "pending";
1049
- try {
1050
- await this.run();
1051
- this.status = "fulfilled";
1052
- } catch (error) {
1053
- this.status = "rejected";
1054
- throw error;
1055
- }
1056
- }
1057
- fork() {
1058
- const context = cloneSharedContext(this.context);
1059
- const next = this.current + 1;
1060
- return new KeqMiddlewareOrchestrator(context, this.executors.slice(next).map((executor) => executor.middleware), { main: {
1061
- orchestrator: this.main ? this.main.orchestrator : this,
1062
- index: this.main ? this.main.index + next : next
1063
- } });
1064
- }
1065
- merge(source) {
1066
- if (!source.main) throw new TypeException("Source orchestrator is not a forked orchestrator.");
1067
- const target = this.main ? this.main.orchestrator : this;
1068
- if (source.main.orchestrator !== target) throw new TypeException("Cannot rebase to unrelated orchestrator");
1069
- if (source.main.index !== this.current + 1) throw new TypeException(`Cannot merge from non-current(expected: ${this.current + 1}, actual: ${source.main.index}) forked orchestrator`);
1070
- assignSharedContext(this.context, source.context);
1071
- for (const [i, executor] of this.executors.slice(source.main.index).entries()) executor.status = source.executors[i].status;
1072
- }
1073
- };
1074
- //#endregion
1075
- //#region src/request/utils/fix-content-type.ts
1076
- function fixContentType(contentType) {
1077
- if (["json", "xml"].includes(contentType)) return `application/${contentType}`;
1078
- else if (["html", "css"].includes(contentType)) return `text/${contentType}`;
1079
- else if (["form-data"].includes(contentType)) return `multipart/${contentType}`;
1080
- else if ([
1081
- "jpeg",
1082
- "bmp",
1083
- "apng",
1084
- "gif",
1085
- "x-icon",
1086
- "png",
1087
- "webp",
1088
- "tiff"
1089
- ].includes(contentType)) return `image/${contentType}`;
1090
- else if (contentType === "form") return "application/x-www-form-urlencoded";
1091
- else if (contentType === "svg") return "image/svg+xml";
1092
- return contentType;
1093
- }
1094
- //#endregion
1095
- //#region src/request/utils/get-location-id.ts
1096
- function getLocationId(depth = 0) {
1097
- const err = /* @__PURE__ */ new Error();
1098
- if (!err.stack) return "";
1099
- return err.stack.split("\n")[depth + 2].trim();
1100
- }
1101
- //#endregion
1102
- //#region src/request/utils/resolve-with.ts
1103
- async function resolveWith(response, mode) {
1104
- if (mode === "response") return response.clone();
1105
- if (mode === "text") return await response.text();
1106
- if (mode === "json") return unwrap(await response.json());
1107
- if (mode === "form-data") return await response.formData();
1108
- if (mode === "blob") return await response.blob();
1109
- if (mode === "array-buffer") return await response.arrayBuffer();
1110
- if (mode === "sse") {
1111
- if (!response.body) return response.body;
1112
- return response.clone().body.pipeThrough(new TextDecoderStream()).pipeThrough(new eventsource_parser_stream.EventSourceParserStream());
1113
- }
1114
- }
1115
- //#endregion
1116
- //#region src/request/utils/intelligent-parse-response.ts
1117
- async function intelligentParseResponse(response) {
1118
- if (!response) return void 0;
1119
- if (response.status === 204) return;
1120
- const contentType = response.headers.get("content-type") || "";
1121
- try {
1122
- if (contentType.match(/^application\/(.+\+)?json/)) return resolveWith(response, "json");
1123
- else if (contentType.includes("multipart/form-data")) return resolveWith(response, "form-data");
1124
- else if (contentType.includes("plain/text")) return resolveWith(response, "text");
1125
- else if (contentType.includes("text/event-stream")) return resolveWith(response, "sse");
1126
- } catch (err) {
1127
- console.warn(`Failed to intelligent parse response body: ${response.url}`, err);
1128
- throw err;
1129
- }
1130
- }
1131
- //#endregion
1132
- //#region src/request/utils/merge-keq-request-body.ts
1133
- function mergeKeqRequestBody(left, right) {
1134
- if (right === void 0) return left;
1135
- if (typeof right === "number") throw new TypeError("Cannot set request body to a number.");
1136
- if (left === null || right === null || Validator.isBuffer(right) || Validator.isArrayBuffer(right) || Validator.isBlob(right) || Validator.isReadableStream(right) || Validator.isBuffer(left) || Validator.isArrayBuffer(left) || Validator.isBlob(left) || Validator.isReadableStream(left) || Array.isArray(left) || Array.isArray(right) || typeof left !== "object" && left !== void 0 || typeof right !== "object") return Array.isArray(right) ? [...right] : right;
1137
- const result = left || {};
1138
- if (Validator.isUrlSearchParams(right)) {
1139
- const keys = right.keys();
1140
- for (const key of keys) {
1141
- const values = right.getAll(key);
1142
- if (values.length === 1) result[key] = values[0];
1143
- else if (values.length > 1) result[key] = values;
1144
- }
1145
- } else if (Validator.isFormData(right)) {
1146
- const keys = right.keys();
1147
- for (const key of keys) {
1148
- const values = right.getAll(key);
1149
- if (values.length === 1) result[key] = values[0];
1150
- else if (values.length > 1) result[key] = values;
1151
- }
1152
- } else if (typeof right === "object") for (const key in right) result[key] = right[key];
1153
- else throw new Exception(`Not support request body type: ${typeof right}`);
1154
- return result;
1155
- }
1156
- //#endregion
1157
- //#region src/request/utils/query-stringify.ts
1158
- function normalize(value, options) {
1159
- if (Array.isArray(value)) return value.map((v) => normalize(v, options));
1160
- if (typeof value === "bigint") return value.toString();
1161
- if (typeof value === "object" && value !== null) {
1162
- const obj = { ...value };
1163
- for (const key of Object.keys(obj)) obj[key] = normalize(obj[key], options);
1164
- return obj;
1165
- }
1166
- return value;
1167
- }
1168
- function queryStringify(query, options) {
1169
- const value = normalize(query, options);
1170
- const opts = {};
1171
- if (options?.allowDots !== void 0) opts.allowDots = options.allowDots;
1172
- if (options?.indices !== void 0) opts.indices = options.indices;
1173
- if (options?.arrayFormat === "pipe") opts.filter = (_, val) => {
1174
- if (Array.isArray(val)) return val.join("|");
1175
- return val;
1176
- };
1177
- else if (options?.arrayFormat === "space") opts.filter = (_, val) => {
1178
- if (Array.isArray(val)) return val.join(" ");
1179
- return val;
1180
- };
1181
- else if (options?.arrayFormat) opts.arrayFormat = options.arrayFormat;
1182
- return qs.default.stringify(value, opts);
1183
- }
1184
- //#endregion
1185
- //#region src/request/core.ts
1186
- let _Symbol$species;
1187
- _Symbol$species = Symbol.species;
1188
- /**
1189
- * Core class that provides the foundational structure for managing middlewares, events, and request execution.
1190
- */
1191
- var Core = class extends Promise {
1192
- /**
1193
- * Ensures `.then()`, `.catch()`, `.finally()` return plain Promise instances instead of Core/Keq instances.
1194
- */
1195
- static get [_Symbol$species]() {
1196
- return Promise;
1197
- }
1198
- get __middlewares__() {
1199
- return [...this.__prepend_middlewares__, ...this.__append_middlewares__];
1200
- }
1201
- constructor(url, options) {
1202
- let resolve;
1203
- let reject;
1204
- super((res, rej) => {
1205
- resolve = res;
1206
- reject = rej;
1207
- });
1208
- _defineProperty(
1209
- this,
1210
- /**
1211
- * The unique identifier of the request's location in the code
1212
- */
1213
- "__locationId__",
1214
- void 0
1215
- );
1216
- _defineProperty(this, "__resolve__", void 0);
1217
- _defineProperty(this, "__reject__", void 0);
1218
- _defineProperty(this, "__triggered__", false);
1219
- _defineProperty(this, "__requestPromise__", void 0);
1220
- _defineProperty(this, "requestInit", void 0);
1221
- _defineProperty(this, "__listeners__", {});
1222
- _defineProperty(this, "__global__", void 0);
1223
- _defineProperty(this, "__prepend_middlewares__", []);
1224
- _defineProperty(this, "__append_middlewares__", []);
1225
- _defineProperty(this, "__qs__", void 0);
1226
- _defineProperty(this, "__options__", {
1227
- resolveWithFullResponse: false,
1228
- resolveWith: "intelligent"
1229
- });
1230
- this.__resolve__ = resolve;
1231
- this.__reject__ = reject;
1232
- this.__global__ = options.global || {};
1233
- this.__locationId__ = options.locationId;
1234
- this.__qs__ = options.qs;
1235
- this.requestInit = new KeqRequestInit({
1236
- method: "get",
1237
- headers: new Headers(),
1238
- pathParameters: {},
1239
- body: void 0,
1240
- ...options,
1241
- url: new URL(url.href)
1242
- });
1243
- if (options.middlewares) this.__append_middlewares__.push(...options.middlewares);
1244
- }
1245
- use(...middlewares) {
1246
- this.__prepend_middlewares__.push(...middlewares);
1247
- return this;
1248
- }
1249
- on(event, listener) {
1250
- this.__listeners__[event] = this.__listeners__[event] || [];
1251
- this.__listeners__[event].push(listener);
1252
- return this;
1253
- }
1254
- option(key, value = true) {
1255
- this.__options__[key] = value;
1256
- return this;
1257
- }
1258
- options(opts) {
1259
- for (const [key, value] of Object.entries(opts)) this.__options__[key] = value;
1260
- return this;
1261
- }
1262
- derive() {
1263
- const derived = new this.constructor(this.requestInit.url, {
1264
- method: this.requestInit.method,
1265
- headers: this.requestInit.headers,
1266
- body: this.requestInit.body,
1267
- pathParameters: this.requestInit.pathParameters,
1268
- cache: this.requestInit.cache,
1269
- credentials: this.requestInit.credentials,
1270
- integrity: this.requestInit.integrity,
1271
- keepalive: this.requestInit.keepalive,
1272
- mode: this.requestInit.mode,
1273
- redirect: this.requestInit.redirect,
1274
- referrer: this.requestInit.referrer,
1275
- referrerPolicy: this.requestInit.referrerPolicy,
1276
- locationId: this.__locationId__,
1277
- global: this.__global__,
1278
- qs: this.__qs__ ? { ...this.__qs__ } : void 0,
1279
- middlewares: [...this.__append_middlewares__]
1280
- });
1281
- derived.__prepend_middlewares__ = [...this.__prepend_middlewares__];
1282
- derived.__listeners__ = {};
1283
- for (const key in this.__listeners__) derived.__listeners__[key] = [...this.__listeners__[key]];
1284
- derived.__options__ = (0, klona_json.klona)(this.__options__);
1285
- return derived;
1286
- }
1287
- buildSharedContext() {
1288
- const coreContext = new KeqSharedContext({
1289
- locationId: this.__locationId__,
1290
- request: this.requestInit,
1291
- global: this.__global__,
1292
- options: this.__options__
1293
- });
1294
- for (const eventName in this.__listeners__) {
1295
- const listeners = this.__listeners__[eventName];
1296
- for (const listener of listeners) coreContext.emitter.on(eventName, listener);
1297
- }
1298
- return coreContext;
1299
- }
1300
- async run() {
1301
- let attempt;
1302
- while (true) {
1303
- const attemptWithDefault = attempt || 0;
1304
- const sharedContext = this.buildSharedContext();
1305
- const orchestrator = new KeqMiddlewareOrchestrator(sharedContext, this.__middlewares__);
1306
- if (attempt !== void 0) sharedContext.data.retry = { attempt };
1307
- if (attempt && attempt >= 1) sharedContext.emitter.emit("retry", { context: sharedContext });
1308
- let error = null;
1309
- try {
1310
- await orchestrator.execute();
1311
- } catch (err) {
1312
- error = err;
1313
- }
1314
- const retryOn = typeof sharedContext.options.retry?.on === "function" ? sharedContext.options.retry.on : (attempt, error) => {
1315
- if (error instanceof RequestException && error.retry === false) return false;
1316
- return !!error;
1317
- };
1318
- let retryTimes = sharedContext.options.retry?.times || 0;
1319
- if (retryTimes) {
1320
- if (retryTimes < 0) retryTimes = 0;
1321
- else if (!Number.isInteger(retryTimes)) retryTimes = Math.floor(retryTimes);
1322
- }
1323
- if (attemptWithDefault >= retryTimes || await retryOn(attemptWithDefault, error, sharedContext) === false) {
1324
- if (error) {
1325
- sharedContext.emitter.emit("error", { context: sharedContext });
1326
- throw error;
1327
- }
1328
- return sharedContext;
1329
- }
1330
- const retryDelay = typeof sharedContext.options.retry?.delay === "function" ? await sharedContext.options.retry.delay(attemptWithDefault, error, sharedContext) : sharedContext.options.retry?.delay || 0;
1331
- if (retryDelay) await sleep(retryDelay);
1332
- attempt = attemptWithDefault + 1;
1333
- }
1334
- }
1335
- __execute__() {
1336
- if (!this.__requestPromise__) this.__requestPromise__ = (async () => {
1337
- const coreContext = await this.run();
1338
- const resolveWithMode = coreContext.options.resolveWith;
1339
- if (resolveWithMode === "response") return coreContext.response?.clone();
1340
- const response = coreContext.response;
1341
- if (!resolveWithMode || resolveWithMode === "intelligent") {
1342
- const output = coreContext.output;
1343
- if (output !== void 0) return output;
1344
- return await intelligentParseResponse(response);
1345
- }
1346
- if (!response) throw new Exception([
1347
- `Unable to process the response with '${resolveWithMode}'. Possible causes:`,
1348
- "1. The request was never initiated or sent",
1349
- "2. The request failed before a response was received."
1350
- ].join("\n"));
1351
- return await resolveWith(response, resolveWithMode);
1352
- })();
1353
- return this.__requestPromise__;
1354
- }
1355
- fire() {
1356
- if (!this.__triggered__) {
1357
- this.__triggered__ = true;
1358
- this.__execute__().then(this.__resolve__, this.__reject__);
1359
- }
1360
- }
1361
- then(onfulfilled, onrejected) {
1362
- if (!this.__triggered__) {
1363
- this.__triggered__ = true;
1364
- this.__execute__().then(this.__resolve__, this.__reject__);
1365
- }
1366
- return super.then(onfulfilled, onrejected);
1367
- }
1368
- };
1369
- //#endregion
1370
- //#region src/request/keq.ts
1371
- /**
1372
- * extends Core to provide a fluent API for building HTTP requests
1373
- */
1374
- var Keq = class extends Core {
1375
- set(headersOrName, value) {
1376
- if (Validator.isHeaders(headersOrName)) headersOrName.forEach((value, key) => {
1377
- this.requestInit.headers.set(key, value);
1378
- });
1379
- else if (typeof headersOrName === "string" && value) {
1380
- if (!Validator.isHeaderValue(value)) throw new Exception(`[Invalid header] Key: ${headersOrName} Value: ${value}`);
1381
- this.requestInit.headers.set(headersOrName, String(value));
1382
- } else if (typeof headersOrName === "object") for (const [key, value] of Object.entries(headersOrName)) {
1383
- if (!Validator.isHeaderValue(value)) throw new Exception(`[Invalid header] Key: ${key} Value: ${String(value)}`);
1384
- this.requestInit.headers.set(key, String(value));
1385
- }
1386
- return this;
1387
- }
1388
- headers(headersOrName, value) {
1389
- return this.set(headersOrName, value);
1390
- }
1391
- query(arg1, arg2, arg3) {
1392
- if (Validator.isObject(arg1)) {
1393
- const str = queryStringify(arg1, arg2 || this.__qs__);
1394
- for (const [k, v] of new URLSearchParams(str).entries()) for (const item of Array.isArray(v) ? v : [v]) this.requestInit.url.searchParams.append(k, item);
1395
- this.requestInit.url.search = this.requestInit.url.searchParams.toString().replace(/\+/g, "%20");
1396
- return this;
1397
- }
1398
- if (typeof arg1 === "string") {
1399
- this.query({ [arg1]: arg2 }, arg3);
1400
- return this;
1401
- }
1402
- throw new TypeException("Invalid Arguments for .query()");
1403
- }
1404
- params(arg1, arg2) {
1405
- if (typeof arg1 === "string" && arg2 !== void 0) this.requestInit.pathParameters[arg1] = arg2;
1406
- else if (typeof arg1 === "object" && arg1 !== null) {
1407
- for (const k of Object.keys(arg1)) if (arg1[k]) this.requestInit.pathParameters[k] = arg1[k];
1408
- } else throw new TypeError("Invalid Arguments for .params()");
1409
- return this;
1410
- }
1411
- /**
1412
- * Set request body
1413
- */
1414
- body(value) {
1415
- this.requestInit.body = value;
1416
- return this;
1417
- }
1418
- type(contentType) {
1419
- const type = fixContentType(contentType);
1420
- this.set("content-type", type);
1421
- return this;
1422
- }
1423
- /**
1424
- * Http Basic Authentication
1425
- */
1426
- auth(username, password) {
1427
- this.set("Authorization", `Basic ${base64Encode(`${username}:${password}`)}`);
1428
- return this;
1429
- }
1430
- setTypeIfEmpty(contentType) {
1431
- if (!this.requestInit.headers.has("Content-Type")) this.type(contentType);
1432
- }
1433
- send(value) {
1434
- this.requestInit.body = mergeKeqRequestBody(this.requestInit.body, value);
1435
- if (Validator.isUrlSearchParams(value)) this.setTypeIfEmpty("form");
1436
- else if (Validator.isFormData(value)) this.setTypeIfEmpty("form-data");
1437
- else if (Validator.isBlob(value) || Validator.isReadableStream(value) || Validator.isArrayBuffer(value)) {} else if (typeof value === "object") this.setTypeIfEmpty("json");
1438
- return this;
1439
- }
1440
- field(arg1, arg2) {
1441
- if (typeof arg1 === "object") this.requestInit.body = mergeKeqRequestBody(this.requestInit.body, arg1);
1442
- else if (arg2) this.requestInit.body = mergeKeqRequestBody(this.requestInit.body, { [arg1]: arg2 });
1443
- else throw new TypeException("Invalid arguments for .field()");
1444
- this.setTypeIfEmpty("form-data");
1445
- return this;
1446
- }
1447
- attach(key, value, arg3 = "file") {
1448
- const formData = new FormData();
1449
- const appendFile = (file) => {
1450
- if (Validator.isBlob(file)) formData.append(key, file, arg3);
1451
- else if (Validator.isFile(file)) formData.append(key, file);
1452
- else if (Validator.isBuffer(file)) formData.append(key, new Blob([file]), arg3);
1453
- else throw new TypeException("Invalid file type for .attach()");
1454
- };
1455
- if (Array.isArray(value)) {
1456
- if (value.length === 0) throw new TypeException("Empty array provided to .attach() is not valid");
1457
- for (const item of value) appendFile(item);
1458
- } else appendFile(value);
1459
- const files = formData.getAll(key);
1460
- this.requestInit.body = mergeKeqRequestBody(this.requestInit.body, { [key]: files.length === 1 ? files[0] : files });
1461
- this.setTypeIfEmpty("form-data");
1462
- return this;
1463
- }
1464
- /**
1465
- *
1466
- * @param retryTimes Max number of retries per call
1467
- * @param retryDelay Initial value used to calculate the retry in milliseconds (This is still randomized following the randomization factor)
1468
- * @param retryCallback Will be called after request failed
1469
- */
1470
- retry(retryTimes, retryDelay = 0, retryOn = (attempt, error) => !!error) {
1471
- this.option("retry", {
1472
- times: retryTimes,
1473
- delay: retryDelay,
1474
- on: retryOn
1475
- });
1476
- return this;
1477
- }
1478
- redirect(mod) {
1479
- this.requestInit.redirect = mod;
1480
- return this;
1481
- }
1482
- credentials(mod) {
1483
- this.requestInit.credentials = mod;
1484
- return this;
1485
- }
1486
- mode(mod) {
1487
- this.requestInit.mode = mod;
1488
- return this;
1489
- }
1490
- flowControl(mode, arg2, arg3) {
1491
- const concurrencyLimit = typeof arg2 === "number" ? arg2 : void 0;
1492
- const sig = typeof arg2 === "function" || typeof arg2 === "string" ? arg2 : arg3 && (typeof arg3 === "function" || typeof arg3 === "string") ? arg3 : this.__locationId__;
1493
- if (!sig) throw new Exception("please set signal to .flowControl()");
1494
- const flowControl = {
1495
- mode,
1496
- concurrencyLimit,
1497
- signal: sig
1498
- };
1499
- this.option("flowControl", flowControl);
1500
- return this;
1501
- }
1502
- timeout(milliseconds) {
1503
- this.option("timeout", { millisecond: milliseconds });
1504
- return this;
1505
- }
1506
- resolveWith(m) {
1507
- this.option("resolveWith", m);
1508
- return this;
1509
- }
1510
- };
1511
- //#endregion
1512
- //#region src/router/utils/compose-route.ts
1513
- function composeRoute(routes) {
1514
- if (!routes.length) throw new Exception("At least one route");
1515
- return async (ctx) => {
1516
- return (await Promise.all(routes.map((route) => route(ctx)))).every((result) => result === true);
1517
- };
1518
- }
1519
- //#endregion
1520
- //#region src/router/keq-host-route.ts
1521
- function keqHostRoute(host) {
1522
- return (ctx) => ctx.request.url.host === host;
1523
- }
1524
- //#endregion
1525
- //#region src/router/keq-location-route.ts
1526
- function keqLocationRoute() {
1527
- return (ctx) => Validator.isBrowser() && ctx.request.url.host === window.location.host;
1528
- }
1529
- //#endregion
1530
- //#region src/router/keq-method-route.ts
1531
- function keqMethodRoute(method) {
1532
- return (ctx) => ctx.request.method.toLowerCase() === method.toLowerCase();
1533
- }
1534
- //#endregion
1535
- //#region src/router/keq-pathname-route.ts
1536
- function keqPathnameRoute(pathname) {
1537
- const isMatch = (0, picomatch.default)(pathname);
1538
- return (ctx) => {
1539
- return isMatch(ctx.request.url.pathname);
1540
- };
1541
- }
1542
- //#endregion
1543
- //#region src/router/keq-router.ts
1544
- var KeqRouter = class KeqRouter {
1545
- constructor(middlewares = []) {
1546
- this.middlewares = middlewares;
1547
- }
1548
- static buildMiddleware(route, middlewares) {
1549
- if (middlewares.length === 0) throw new TypeException("At least one middleware is required to build a route middleware");
1550
- const composedMiddleware = middlewares.length > 1 ? composeMiddleware(middlewares) : middlewares[0];
1551
- return async function router(ctx, next) {
1552
- if (route(ctx)) await composedMiddleware(ctx, next);
1553
- else await next();
1554
- };
1555
- }
1556
- route(route, middleware, ...additionalMiddlewares) {
1557
- const mid = KeqRouter.route(route, middleware, ...additionalMiddlewares);
1558
- this.middlewares.push(mid);
1559
- return this;
1560
- }
1561
- host(host, middleware, ...additionalMiddlewares) {
1562
- const mid = KeqRouter.host(host, middleware, ...additionalMiddlewares);
1563
- this.middlewares.push(mid);
1564
- return this;
1565
- }
1566
- method(method, middleware, ...additionalMiddlewares) {
1567
- const mid = KeqRouter.method(method, middleware, ...additionalMiddlewares);
1568
- this.middlewares.push(mid);
1569
- return this;
1570
- }
1571
- pathname(pathname, middleware, ...additionalMiddlewares) {
1572
- const mid = KeqRouter.pathname(pathname, middleware, ...additionalMiddlewares);
1573
- this.middlewares.push(mid);
1574
- return this;
1575
- }
1576
- location(middleware, ...additionalMiddlewares) {
1577
- const mid = KeqRouter.location(middleware, ...additionalMiddlewares);
1578
- this.middlewares.push(mid);
1579
- return this;
1580
- }
1581
- static route(route, middleware, ...additionalMiddlewares) {
1582
- const list = Array.isArray(middleware) ? middleware : [middleware, ...additionalMiddlewares];
1583
- const mid = KeqRouter.buildMiddleware(route, list);
1584
- mid.__keqMiddlewareName__ = `route(${route.__keqRouteName__ || route.name}, ${list.map(getMiddlewareName).join(", ")})`;
1585
- return mid;
1586
- }
1587
- static host(host, middleware, ...additionalMiddlewares) {
1588
- const list = Array.isArray(middleware) ? middleware : [middleware, ...additionalMiddlewares];
1589
- const mid = KeqRouter.buildMiddleware(keqHostRoute(host), list);
1590
- mid.__keqMiddlewareName__ = `host(${JSON.stringify(host)}, ${list.map(getMiddlewareName).join(", ")})`;
1591
- return mid;
1592
- }
1593
- static method(method, middleware, ...additionalMiddlewares) {
1594
- const list = Array.isArray(middleware) ? middleware : [middleware, ...additionalMiddlewares];
1595
- const mid = KeqRouter.buildMiddleware(keqMethodRoute(method), list);
1596
- mid.__keqMiddlewareName__ = `method(${JSON.stringify(method)}, ${list.map(getMiddlewareName).join(", ")})`;
1597
- return mid;
1598
- }
1599
- static pathname(pathname, middleware, ...additionalMiddlewares) {
1600
- const list = Array.isArray(middleware) ? middleware : [middleware, ...additionalMiddlewares];
1601
- const mid = KeqRouter.buildMiddleware(keqPathnameRoute(pathname), list);
1602
- mid.__keqMiddlewareName__ = `pathname(${JSON.stringify(pathname)}, ${list.map(getMiddlewareName).join(", ")})`;
1603
- return mid;
1604
- }
1605
- static location(middleware, ...additionalMiddlewares) {
1606
- const list = Array.isArray(middleware) ? middleware : [middleware, ...additionalMiddlewares];
1607
- const mid = KeqRouter.buildMiddleware(keqLocationRoute(), list);
1608
- mid.__keqMiddlewareName__ = `location(${list.map(getMiddlewareName).join(", ")})`;
1609
- return mid;
1610
- }
1611
- };
1612
- //#endregion
1613
- //#region src/middlewares/timeout-middleware/index.ts
1614
- function keqTimeoutMiddleware() {
1615
- return async function timeoutMiddleware(ctx, next) {
1616
- if (!ctx.options.timeout || ctx.options.timeout.millisecond <= 0) {
1617
- await next();
1618
- return;
1619
- }
1620
- const millisecond = ctx.options.timeout.millisecond;
1621
- let timer;
1622
- ctx.emitter.on("fetch:before", ({ context }) => {
1623
- timer = setTimeout(() => {
1624
- const err = new TimeoutException(`keq request timeout(${millisecond}ms)`);
1625
- context.request.abort(err);
1626
- context.emitter.emit("timeout", { context });
1627
- }, millisecond);
1628
- });
1629
- ctx.emitter.on("fetch:after", () => {
1630
- if (timer !== void 0) {
1631
- clearTimeout(timer);
1632
- timer = void 0;
1633
- }
1634
- });
1635
- await next();
1636
- };
1637
- }
1638
- //#endregion
1639
- //#region src/middlewares/flow-control-middleware/serial-flow-control-middleware.ts
1640
- function keqSerialFlowControlMiddleware() {
1641
- return async function serialFlowControlMiddleware(ctx, next) {
1642
- if (!ctx.options.flowControl || !["serial", "concurrent"].includes(ctx.options.flowControl.mode)) {
1643
- await next();
1644
- return;
1645
- }
1646
- const { signal } = ctx.options.flowControl;
1647
- const concurrent = ctx.options.flowControl.mode === "serial" ? 1 : !ctx.options.flowControl.concurrencyLimit || ctx.options.flowControl.concurrencyLimit < 1 ? 1 : Math.floor(ctx.options.flowControl.concurrencyLimit);
1648
- const key = typeof signal === "string" ? signal : signal(ctx);
1649
- if (!ctx.global.core) ctx.global.core = {};
1650
- if (!ctx.global.core.serialFlowControl) ctx.global.core.serialFlowControl = {};
1651
- if (!ctx.global.core.serialFlowControl[key]) ctx.global.core.serialFlowControl[key] = fastq.promise(async ({ next }) => {
1652
- await next();
1653
- }, concurrent);
1654
- await ctx.global.core.serialFlowControl[key].push({ next });
1655
- };
1656
- }
1657
- //#endregion
1658
- //#region src/middlewares/flow-control-middleware/abort-flow-control-middleware.ts
1659
- function keqAbortFlowControlMiddleware() {
1660
- return async function abortFlowControlMiddleware(ctx, next) {
1661
- if (!ctx.options.flowControl || ctx.options.flowControl.mode !== "abort") {
1662
- await next();
1663
- return;
1664
- }
1665
- const { signal } = ctx.options.flowControl;
1666
- const key = typeof signal === "string" ? signal : signal(ctx);
1667
- if (!ctx.global.core) ctx.global.core = {};
1668
- if (!ctx.global.core.abortFlowControl) ctx.global.core.abortFlowControl = {};
1669
- const abort = ctx.global.core.abortFlowControl[key];
1670
- if (abort) abort(new AbortException(`Previous request was aborted by AbortFlowControl with key "${key}"`));
1671
- const fn = ctx.request.abort.bind(ctx.request);
1672
- ctx.global.core.abortFlowControl[key] = fn;
1673
- try {
1674
- await next();
1675
- } finally {
1676
- if (ctx.global.core.abortFlowControl[key] === fn) ctx.global.core.abortFlowControl[key] = void 0;
1677
- }
1678
- };
1679
- }
1680
- //#endregion
1681
- //#region src/middlewares/flow-control-middleware/mutex-flow-control-middleware.ts
1682
- function keqMutexFlowControlMiddleware() {
1683
- return async function mutexFlowControlMiddleware(ctx, next) {
1684
- if (!ctx.options.flowControl || ctx.options.flowControl.mode !== "mutex") {
1685
- await next();
1686
- return;
1687
- }
1688
- const { signal } = ctx.options.flowControl;
1689
- const key = typeof signal === "string" ? signal : signal(ctx);
1690
- if (!ctx.global.core) ctx.global.core = {};
1691
- if (!ctx.global.core.mutexFlowControl) ctx.global.core.mutexFlowControl = /* @__PURE__ */ new Set();
1692
- if (ctx.global.core.mutexFlowControl.has(key)) throw new MutexException(`Request rejected by MutexFlowControl: a request with key "${key}" is already in-flight`);
1693
- ctx.global.core.mutexFlowControl.add(key);
1694
- try {
1695
- await next();
1696
- } finally {
1697
- ctx.global.core.mutexFlowControl.delete(key);
1698
- }
1699
- };
1700
- }
1701
- //#endregion
1702
- //#region src/middlewares/flow-control-middleware/index.ts
1703
- function keqFlowControlMiddleware() {
1704
- return composeMiddleware([
1705
- keqMutexFlowControlMiddleware(),
1706
- keqSerialFlowControlMiddleware(),
1707
- keqAbortFlowControlMiddleware()
1708
- ], { name: "flowControlMiddleware" });
1709
- }
1710
- //#endregion
1711
- //#region src/middlewares/fetch-middleware/index.ts
1712
- /**
1713
- * Send Request
1714
- */
1715
- function keqFetchMiddleware() {
1716
- return async function fetchMiddleware(context) {
1717
- const fetch = context.options.fetchAPI || globalThis.fetch;
1718
- context.emitter.emit("fetch:before", { context });
1719
- const response = await fetch(...context.request.toFetchArguments());
1720
- context.emitter.emit("fetch:after", { context });
1721
- context.res = response;
1722
- };
1723
- }
1724
- //#endregion
1725
- //#region src/request/request.ts
1726
- /**
1727
- * Keq instance factory class,
1728
- * and shares global data and middlewares across requests
1729
- */
1730
- var KeqRequest = class KeqRequest {
1731
- constructor(options) {
1732
- _defineProperty(this, "baseOrigin", void 0);
1733
- _defineProperty(this, "qs", void 0);
1734
- _defineProperty(this, "global", {});
1735
- _defineProperty(this, "middlewares", []);
1736
- _defineProperty(this, "__terminalMiddlewares__", []);
1737
- _defineProperty(this, "__parent__", void 0);
1738
- if (options?.baseOrigin) this.baseOrigin = options.baseOrigin;
1739
- else this.baseOrigin = Validator.isBrowser() ? location.origin : "http://127.0.0.1";
1740
- this.qs = options?.qs;
1741
- this.__terminalMiddlewares__ = options?.terminalMiddlewares || [
1742
- keqFlowControlMiddleware(),
1743
- keqTimeoutMiddleware(),
1744
- keqFetchMiddleware()
1745
- ];
1746
- this.middlewares = options?.middlewares || [];
1747
- }
1748
- __formatUrl__(url) {
1749
- if (typeof url === "string") return new URL(url, this.baseOrigin);
1750
- return new URL(url.href);
1751
- }
1752
- resolveMiddlewares() {
1753
- if (!this.__parent__) return this.middlewares;
1754
- return [...this.__parent__.resolveMiddlewares(), ...this.middlewares];
1755
- }
1756
- __fetch__(url, init, locationId) {
1757
- return new Keq(this.__formatUrl__(url), {
1758
- ...init,
1759
- locationId,
1760
- global: this.global,
1761
- qs: this.qs,
1762
- middlewares: [...this.resolveMiddlewares(), ...this.__terminalMiddlewares__]
1763
- });
1764
- }
1765
- fetch(url, init) {
1766
- return this.__fetch__(url, init, getLocationId(1));
1767
- }
1768
- get(url) {
1769
- return this.__fetch__(url, { method: "get" }, getLocationId(1));
1770
- }
1771
- put(url) {
1772
- return this.__fetch__(url, { method: "put" }, getLocationId(1));
1773
- }
1774
- delete(url) {
1775
- return this.__fetch__(url, { method: "delete" }, getLocationId(1));
1776
- }
1777
- del(url) {
1778
- return this.delete(url);
1779
- }
1780
- post(url) {
1781
- return this.__fetch__(url, { method: "post" }, getLocationId(1));
1782
- }
1783
- head(url) {
1784
- return this.__fetch__(url, { method: "head" }, getLocationId(1));
1785
- }
1786
- patch(url) {
1787
- return this.__fetch__(url, { method: "patch" }, getLocationId(1));
1788
- }
1789
- options(url) {
1790
- return this.__fetch__(url, { method: "options" }, getLocationId(1));
1791
- }
1792
- use(firstMiddleware, ...middleware) {
1793
- this.middlewares.push(firstMiddleware, ...middleware);
1794
- return this;
1795
- }
1796
- useRouter() {
1797
- return new KeqRouter(this.middlewares);
1798
- }
1799
- fork(options) {
1800
- const child = new KeqRequest({
1801
- baseOrigin: options?.baseOrigin ?? this.baseOrigin,
1802
- qs: options?.qs ?? (this.qs ? { ...this.qs } : void 0)
1803
- });
1804
- child.__parent__ = this;
1805
- return child;
1806
- }
1807
- inherit(parent) {
1808
- this.__parent__ = parent;
1809
- return this;
1810
- }
1811
- adopt(child) {
1812
- child.__parent__ = this;
1813
- return this;
1814
- }
1815
- /** @deprecated Use `middlewares` instead */
1816
- get preMiddlewares() {
1817
- return this.middlewares;
1818
- }
1819
- on(event, listener) {
1820
- const middleware = async (context, next) => {
1821
- context.emitter.on(event, listener);
1822
- await next();
1823
- };
1824
- middleware.__keqMiddlewareName__ = `listen(${event}, ${listener.name || "anonymous"})`;
1825
- this.use(middleware);
1826
- return this;
1827
- }
1828
- };
1829
- const request = new KeqRequest();
1830
- //#endregion
1831
- //#region src/request/create-request.ts
1832
- /**
1833
- * @deprecated use new KeqRequest<SCHEMA>(options) instead
1834
- */
1835
- function createRequest(options) {
1836
- return new KeqRequest(options);
1837
- }
1838
- //#endregion
1839
- exports.AbortException = AbortException;
1840
- exports.BadGatewayException = BadGatewayException;
1841
- exports.BadRequestException = BadRequestException;
1842
- exports.ConflictException = ConflictException;
1843
- exports.ContentTooLargeException = ContentTooLargeException;
1844
- exports.Exception = Exception;
1845
- exports.ForbiddenException = ForbiddenException;
1846
- exports.GatewayTimeoutException = GatewayTimeoutException;
1847
- exports.ImATeapotException = ImATeapotException;
1848
- exports.InternalServerErrorException = InternalServerErrorException;
1849
- exports.Keq = Keq;
1850
- exports.KeqExecutionContext = KeqExecutionContext;
1851
- exports.KeqMiddlewareExecutor = KeqMiddlewareExecutor;
1852
- exports.KeqMiddlewareOrchestrator = KeqMiddlewareOrchestrator;
1853
- exports.KeqRequest = KeqRequest;
1854
- exports.KeqSharedContext = KeqSharedContext;
1855
- exports.MethodNotAllowedException = MethodNotAllowedException;
1856
- exports.NotAcceptableException = NotAcceptableException;
1857
- exports.NotFoundedException = NotFoundedException;
1858
- exports.NotImplementedException = NotImplementedException;
1859
- exports.PreconditionFailedException = PreconditionFailedException;
1860
- exports.ProxyAuthenticationRequiredException = ProxyAuthenticationRequiredException;
1861
- exports.RequestException = RequestException;
1862
- exports.RequestTimeoutException = RequestTimeoutException;
1863
- exports.ServiceUnavailableException = ServiceUnavailableException;
1864
- exports.TimeoutException = TimeoutException;
1865
- exports.TooManyRequestsException = TooManyRequestsException;
1866
- exports.TypeException = TypeException;
1867
- exports.UnauthorizedException = UnauthorizedException;
1868
- exports.UnsupportedMediaTypeException = UnsupportedMediaTypeException;
1869
- exports.UriTooLongException = UriTooLongException;
1870
- exports.composeMiddleware = composeMiddleware;
1871
- exports.composeRoute = composeRoute;
1872
- exports.createProxyResponse = createProxyResponse;
1873
- exports.createRequest = createRequest;
1874
- exports.request = request;
1875
-
1876
- //# sourceMappingURL=index.js.map