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