@seayoo-web/request 3.2.0 → 3.3.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.
@@ -1,1106 +0,0 @@
1
- var rt = Object.defineProperty;
2
- var nt = (e, t, s) => t in e ? rt(e, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : e[t] = s;
3
- var v = (e, t, s) => nt(e, typeof t != "symbol" ? t + "" : t, s);
4
- var it = Object.defineProperty, ot = (e, t, s) => t in e ? it(e, t, { enumerable: !0, configurable: !0, writable: !0, value: s }) : e[t] = s, o = (e, t, s) => ot(e, typeof t != "symbol" ? t + "" : t, s);
5
- const u = typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : typeof window < "u" ? window : Function("return this")(), j = {
6
- wx: "wx" in u && x(u.wx) && "getSystemInfo" in u.wx && m(u.wx.getSystemInfo),
7
- fetch: "fetch" in u && m(u.fetch),
8
- window: "window" in u && x(u.window),
9
- requestAnimationFrame: "requestAnimationFrame" in u && m(u.requestAnimationFrame),
10
- localStorage: "localStorage" in u && x(u.localStorage) && "getItem" in u.localStorage && m(u.localStorage.getItem),
11
- sessionStorage: "sessionStorage" in u && x(u.sessionStorage) && "getItem" in u.sessionStorage && m(u.sessionStorage.getItem),
12
- File: "File" in u && m(u.File),
13
- Blob: "Blob" in u && m(u.Blob),
14
- Proxy: "Proxy" in u && m(u.Proxy),
15
- Request: "Request" in u && m(u.Request),
16
- FormData: "FormData" in u && m(u.FormData),
17
- TextDecoder: "TextDecoder" in u && m(u.TextDecoder),
18
- ResizeObserver: "ResizeObserver" in u && m(u.ResizeObserver),
19
- AbortController: "AbortController" in u && m(u.AbortController),
20
- URLSearchParams: "URLSearchParams" in u && m(u.URLSearchParams)
21
- };
22
- function m(e) {
23
- return typeof e == "function";
24
- }
25
- function x(e) {
26
- return typeof e == "object" && e !== null;
27
- }
28
- function at(e) {
29
- return new Promise((t) => setTimeout(t, Math.max(0, e)));
30
- }
31
- function X() {
32
- }
33
- function Q(e, t) {
34
- const s = {
35
- log: console.log.bind(console),
36
- error: console.error.bind(console),
37
- warn: console.warn.bind(console)
38
- }, r = `[${e}]`;
39
- return ["log", "error", "warn"].forEach((n) => {
40
- const i = console[n];
41
- s[n] = (...a) => {
42
- i.apply(console, [r, ...a]);
43
- };
44
- }), s;
45
- }
46
- function lt(e) {
47
- const t = e || "CustomError";
48
- return class extends Error {
49
- constructor(s) {
50
- super(s), Object.defineProperty(this, "name", {
51
- value: t,
52
- enumerable: !1,
53
- configurable: !0
54
- }), "setPrototypeOf" in Object && Object.setPrototypeOf(this, new.target.prototype), "captureStackTrace" in Error && typeof Error.captureStackTrace == "function" && Error.captureStackTrace(this, this.constructor);
55
- }
56
- };
57
- }
58
- const ut = /^(?:https?:)?\/\/.+$/i, ht = /^https?:\/\/.+$/i, ct = /^\{[\d\D]*\}$/, ft = /^\[[\d\D]*\]$/;
59
- function dt(e) {
60
- return typeof e == "string";
61
- }
62
- function P(e, t = !1) {
63
- return t ? ut.test(e) : ht.test(e);
64
- }
65
- function mt(e) {
66
- return e == null;
67
- }
68
- function Y(e, ...t) {
69
- return e !== null && typeof e == "object" && !(e instanceof Map) && !(e instanceof Set) && !(e instanceof WeakMap) && !(e instanceof WeakSet) && !Array.isArray(e) && t.every((s) => s in e);
70
- }
71
- function k(e, ...t) {
72
- if (!e || typeof e != "object") return !1;
73
- const s = Object.getPrototypeOf(e);
74
- return s !== Object.prototype && s !== null ? !1 : t.every((r) => r in e);
75
- }
76
- function I(e, t) {
77
- return Array.isArray(e) && e.every((s) => t(s));
78
- }
79
- function F(e) {
80
- if (typeof e != "number" || Number.isNaN(e) || !Number.isFinite(e) || Number.isInteger(e) && !Number.isSafeInteger(e))
81
- return !1;
82
- if (e === 0)
83
- return !0;
84
- const t = Math.abs(e);
85
- return t >= Number.EPSILON && t <= Number.MAX_SAFE_INTEGER;
86
- }
87
- function tt(e) {
88
- return ct.test(e) || ft.test(e);
89
- }
90
- function _t(e, t = 20) {
91
- const s = Math.max(t, 10), r = [...e];
92
- return r.length <= s ? e : r.slice(0, s - 3).join("") + "...";
93
- }
94
- function S(e, t) {
95
- try {
96
- const s = JSON.parse(e);
97
- return t ? t(s) ? s : null : s;
98
- } catch {
99
- return null;
100
- }
101
- }
102
- "" + Math.random().toString(32).slice(2);
103
- Q("LoadUtils");
104
- async function Bt(e) {
105
- return await new Promise(function(t) {
106
- const s = document.getElementsByTagName("head")[0], r = document.createElement("script");
107
- r.setAttribute("type", "text/javascript"), r.setAttribute("charset", "utf-8"), r.onload = function() {
108
- s.removeChild(r), t(!0);
109
- }, r.onerror = function() {
110
- s.removeChild(r), t(!1);
111
- }, r.setAttribute("src", e), s.appendChild(r);
112
- });
113
- }
114
- function W(e) {
115
- return Object.getOwnPropertyNames(e).forEach(function(t) {
116
- delete e[t];
117
- }), e;
118
- }
119
- const g = Q("Validator");
120
- function E(e) {
121
- return e ? `"${_t(e).replace(/"/g, '\\"')}"` : "empty string";
122
- }
123
- function U(e) {
124
- return typeof e == "object" && e && "constructor" in e && typeof e.constructor == "function" ? e.constructor.name || "ClassInstance" : Object.prototype.toString.call(e).replace(/(?:.+ |]$)/g, "");
125
- }
126
- function A(e) {
127
- return typeof e == "bigint";
128
- }
129
- function l(e) {
130
- return new Error(`${e ? `${e}()` : "method"} is not allowed after locked`);
131
- }
132
- class L {
133
- constructor() {
134
- o(this, "_ps", {}), o(this, "_allow", []), o(this, "_reject", []), o(this, "_locked", !1), o(this, "_opt", !1), o(this, "_null", !1);
135
- }
136
- /**
137
- * 设置一个自定义正则校验,设置 name 以用以日志输出
138
- */
139
- pattern(t, s) {
140
- if (this._locked) throw l("pattern");
141
- return this._ps[`#${t || "custom"}`] = s, this;
142
- }
143
- /**
144
- * 允许 url 格式,设置 allowFlexProto 以允许动态协议前缀格式,比如 `//some.site.com`
145
- */
146
- url(t = !1) {
147
- if (this._locked) throw l("url");
148
- return this._ps.url = t ? /^(?:https?:)?\/\/.+$/i : /^https?:\/\/.+$/i, this;
149
- }
150
- /**
151
- * 允许 dataUri 格式,正则为 `^data:[a-z]+\/[a-z]+;base64,[\w+/=]+$`
152
- */
153
- dataUri() {
154
- if (this._locked) throw l("dataUri");
155
- return this._ps.dataUri = /^data:[a-z]+\/[a-z]+;base64,[\w+/=]+$/, this;
156
- }
157
- enum(...t) {
158
- if (this._locked) throw l("enum");
159
- const s = t[0];
160
- return I(t, dt) ? (this._allow = t, W(this._ps)) : k(s) && (this._allow = Object.values(s).map((r) => `${r}`), W(this._ps)), this;
161
- }
162
- disallow(...t) {
163
- return this._reject.push(...t), this;
164
- }
165
- optional() {
166
- if (this._locked) throw l("optional");
167
- return this._opt = !0, this;
168
- }
169
- maybeNull() {
170
- if (this._locked) throw l("maybeNull");
171
- return this._null = !0, this;
172
- }
173
- lock() {
174
- return this._locked = !0, this;
175
- }
176
- clone() {
177
- const t = new L();
178
- return t._ps = { ...this._ps }, t._allow = [...this._allow], t._reject = [...this._reject], t._locked = !1, t;
179
- }
180
- validate(t, s = g.warn) {
181
- if (t === void 0)
182
- return this._opt || (s("should be a string, but got undefined"), !1);
183
- if (t === null)
184
- return this._null || (s("should be a string, but got null"), !1);
185
- if (typeof t != "string")
186
- return s(`should be a string, but got ${typeof t}`), !1;
187
- if (this._allow.length > 0)
188
- return this._allow.includes(t) || (s(`${E(t)} is not allowed, just support ${this._allow.map(E).join(", ")}`), !1);
189
- if (this._reject.length > 0 && this._reject.some((n) => typeof n == "string" ? n === t : n.test(t)))
190
- return s(`${E(t)} is not allowed`), !1;
191
- const r = Object.keys(this._ps);
192
- return r.length > 0 && !r.some((n) => {
193
- const i = this._ps[n];
194
- return i instanceof RegExp ? i.test(t) : i(t);
195
- }) ? (s(`${E(t)} is not match pattern ${r.join(" | ")}`), !1) : !0;
196
- }
197
- }
198
- class C {
199
- constructor() {
200
- o(this, "_int", !1), o(this, "_min", -1 / 0), o(this, "_max", 1 / 0), o(this, "_allow", []), o(this, "_reject", []), o(this, "_infinite", !1), o(this, "_unsafe", !1), o(this, "_nan", !1), o(this, "_locked", !1), o(this, "_opt", !1), o(this, "_null", !1);
201
- }
202
- int() {
203
- if (this._locked) throw l("int");
204
- return this._int = !0, this;
205
- }
206
- min(t) {
207
- if (this._locked) throw l("min");
208
- return Number.isNaN(t) || (this._min = t), this;
209
- }
210
- max(t) {
211
- if (this._locked) throw l("max");
212
- return Number.isNaN(t) || (this._max = t), this;
213
- }
214
- /** 允许 NaN */
215
- allowNaN() {
216
- if (this._locked) throw l("allowNaN");
217
- return this._nan = !0, this;
218
- }
219
- /** 允许无限大或无限小,同时会 allowUnsafe */
220
- allowInfinity() {
221
- if (this._locked) throw l("allowInfinity");
222
- return this._infinite = !0, this._unsafe = !0, this;
223
- }
224
- /** 允许精度不安全的数字,安全精度在 [-2^53 + 1 到 2^53 - 1] */
225
- unsafe() {
226
- if (this._locked) throw l("unsafe");
227
- return this._unsafe = !0, this;
228
- }
229
- enum(...t) {
230
- if (this._locked) throw l("enum");
231
- const s = t[0];
232
- return I(t, F) ? (this._allow = t, this._reject = []) : k(s) && (this._allow = Object.values(s).map((r) => F(r) ? r : null).filter((r) => r !== null), this._reject = []), this;
233
- }
234
- disallow(...t) {
235
- if (this._locked) throw l("disallow");
236
- return this._reject.push(...t), this;
237
- }
238
- optional() {
239
- if (this._locked) throw l("optional");
240
- return this._opt = !0, this;
241
- }
242
- maybeNull() {
243
- if (this._locked) throw l("maybeNull");
244
- return this._null = !0, this;
245
- }
246
- lock() {
247
- return this._locked = !0, this;
248
- }
249
- clone() {
250
- const t = new C();
251
- return t._int = this._int, t._min = this._min, t._max = this._max, t._allow = [...this._allow], t._reject = [...this._reject], t._infinite = this._infinite, t._unsafe = this._unsafe, t._nan = this._nan, t._locked = !1, t;
252
- }
253
- validate(t, s = g.warn) {
254
- return t === void 0 ? this._opt || (s("should be a number, but got undefined"), !1) : t === null ? this._null || (s("should be a number, but got null"), !1) : typeof t != "number" ? (s(`should be a number, but got ${typeof t}`), !1) : Number.isNaN(t) ? this._nan || (s("should be a number, but got NaN"), !1) : !Number.isFinite(t) && !this._infinite ? (s("should be a number, but got Infinity"), !1) : this._allow.length > 0 ? this._allow.includes(t) || (s(`${t} is not allowed, just support ${this._allow.join(", ")}`), !1) : this._reject.length > 0 && this._reject.includes(t) ? (s(`${t} is not allowed`), !1) : this._int && Math.ceil(t) !== t ? (s(`${t} is not an integer`), !1) : !F(t) && !this._unsafe ? (s(`${t} is not a safe number`), !1) : t >= this._min && t <= this._max || (s(`${t} is not in range [${this._min}, ${this._max}]`), !1);
255
- }
256
- }
257
- class D {
258
- constructor() {
259
- o(this, "_min", null), o(this, "_max", null), o(this, "_allow", []), o(this, "_reject", []), o(this, "_locked", !1), o(this, "_opt", !1), o(this, "_null", !1);
260
- }
261
- min(t) {
262
- if (this._locked) throw l("min");
263
- return this._min = t, this;
264
- }
265
- max(t) {
266
- if (this._locked) throw l("max");
267
- return this._max = t, this;
268
- }
269
- enum(...t) {
270
- if (this._locked) throw l("enum");
271
- const s = t[0];
272
- return I(t, A) ? (this._allow = t, this._reject = []) : k(s) && (this._allow = Object.values(s).map((r) => A(r) ? r : null).filter((r) => r !== null), this._reject = []), this;
273
- }
274
- disallow(...t) {
275
- if (this._locked) throw l("disallow");
276
- return this._reject.push(...t), this;
277
- }
278
- optional() {
279
- if (this._locked) throw l("optional");
280
- return this._opt = !0, this;
281
- }
282
- maybeNull() {
283
- if (this._locked) throw l("maybeNull");
284
- return this._null = !0, this;
285
- }
286
- lock() {
287
- return this._locked = !0, this;
288
- }
289
- clone() {
290
- const t = new D();
291
- return t._min = this._min, t._max = this._max, t._allow = [...this._allow], t._reject = [...this._reject], t._locked = !1, t;
292
- }
293
- validate(t, s = g.warn) {
294
- return t === void 0 ? this._opt || (s("should be a bigint, but got undefined"), !1) : t === null ? this._null || (s("should be a bigint, but got null"), !1) : A(t) ? this._allow.length > 0 ? this._allow.includes(t) || (s(`${t} is not allowed, just support ${this._allow.join(", ")}`), !1) : this._reject.length > 0 && this._reject.includes(t) ? (s(`${t} is not allowed`), !1) : (this._min !== null ? t >= this._min : !0) && (this._max !== null ? t <= this._max : !0) || (s(
295
- `${t} is not in range [${this._min === null ? -1 / 0 : this._min}, ${this._max === null ? 1 / 0 : this._max}]`
296
- ), !1) : (s(`should be a bigint, but got ${typeof t}`), !1);
297
- }
298
- }
299
- class q {
300
- constructor() {
301
- o(this, "_locked", !1), o(this, "_opt", !1), o(this, "_null", !1);
302
- }
303
- optional() {
304
- if (this._locked) throw l("optional");
305
- return this._opt = !0, this;
306
- }
307
- maybeNull() {
308
- if (this._locked) throw l("maybeNull");
309
- return this._null = !0, this;
310
- }
311
- lock() {
312
- return this._locked = !0, this;
313
- }
314
- clone() {
315
- return new q();
316
- }
317
- validate(t, s = g.warn) {
318
- return t === void 0 ? this._opt || (s("should be a boolean, but got undefined"), !1) : t === null ? this._null || (s("should be a boolean, but got null"), !1) : typeof t != "boolean" ? (s(`should be a boolean, but got ${typeof t}`), !1) : !0;
319
- }
320
- }
321
- class R {
322
- constructor(t) {
323
- o(this, "_shape"), o(this, "_plain", !1), o(this, "_locked", !1), o(this, "_opt", !1), o(this, "_null", !1), this._shape = t;
324
- }
325
- plain() {
326
- if (this._locked) throw l("plain");
327
- return this._plain = !0, this;
328
- }
329
- optional() {
330
- if (this._locked) throw l("optional");
331
- return this._opt = !0, this;
332
- }
333
- maybeNull() {
334
- if (this._locked) throw l("maybeNull");
335
- return this._null = !0, this;
336
- }
337
- lock() {
338
- return this._locked = !0, this;
339
- }
340
- /**
341
- * 返回初始时的 ObjectShape 配置对象的浅层副本
342
- */
343
- get shape() {
344
- return { ...this._shape };
345
- }
346
- clone() {
347
- const t = new R(this._shape);
348
- return t._plain = this._plain, t._locked = !1, t;
349
- }
350
- /**
351
- * 检查指定的 field / value 是否可以通过校验
352
- */
353
- match(t, s) {
354
- return t in this._shape ? this._shape[t].validate(s, X) : !1;
355
- }
356
- validate(t, s = g.warn) {
357
- return t === void 0 ? this._opt || (s("should be a object, but got undefined"), !1) : t === null ? this._null || (s("should be a object, but got null"), !1) : Y(t) ? this._plain && !k(t) ? (s(`should be a plain object, but got ${U(t)}`), !1) : Object.keys(this._shape).every((r) => this._shape[r].validate(t[r], (...n) => {
358
- s(`[.${String(r)}]`, ...n);
359
- })) : (s(`should be a object, but got ${U(t)}`), !1);
360
- }
361
- }
362
- class B {
363
- constructor(t) {
364
- o(this, "_val"), o(this, "_locked", !1), o(this, "_opt", !1), o(this, "_null", !1), this._val = t;
365
- }
366
- optional() {
367
- if (this._locked) throw l("optional");
368
- return this._opt = !0, this;
369
- }
370
- maybeNull() {
371
- if (this._locked) throw l("maybeNull");
372
- return this._null = !0, this;
373
- }
374
- lock() {
375
- return this._locked = !0, this;
376
- }
377
- clone() {
378
- return new B(this._val);
379
- }
380
- validate(t, s = g.warn) {
381
- return t === void 0 ? this._opt || (s("should be a record, but got undefined"), !1) : t === null ? this._null || (s("should be a record, but got null"), !1) : k(t) ? Object.keys(t).every(
382
- (r) => this._val.validate(t[r], (...n) => {
383
- s(`[:${r}]`, ...n);
384
- })
385
- ) : (s(`should be a record, but got ${U(t)}`), !1);
386
- }
387
- }
388
- class H {
389
- constructor(t) {
390
- o(this, "_val"), o(this, "_min", 0), o(this, "_max", 1 / 0), o(this, "_locked", !1), o(this, "_opt", !1), o(this, "_null", !1), this._val = t;
391
- }
392
- min(t) {
393
- if (this._locked) throw l("min");
394
- return this._min = t, this;
395
- }
396
- max(t) {
397
- if (this._locked) throw l("max");
398
- return this._max = t, this;
399
- }
400
- optional() {
401
- if (this._locked) throw l("optional");
402
- return this._opt = !0, this;
403
- }
404
- maybeNull() {
405
- if (this._locked) throw l("maybeNull");
406
- return this._null = !0, this;
407
- }
408
- lock() {
409
- return this._locked = !0, this;
410
- }
411
- clone() {
412
- const t = new H(this._val);
413
- return t._min = this._min, t._max = this._max, t._locked = !1, t;
414
- }
415
- validate(t, s = g.warn) {
416
- return t === void 0 ? this._opt || (s("should be a array, but got undefined"), !1) : t === null ? this._null || (s("should be a array, but got null"), !1) : Array.isArray(t) ? t.length < this._min || t.length > this._max ? (this._min === this._max ? s(`should be a array with length ${this._min}`) : s(`should be a array with length between ${this._min} and ${this._max}`), !1) : t.every(
417
- (r, n) => this._val.validate(r, (...i) => {
418
- s(`[${n}]`, ...i);
419
- })
420
- ) : (s(`should be a array, but got ${typeof t}`), !1);
421
- }
422
- }
423
- class z {
424
- constructor(...t) {
425
- o(this, "_vs"), o(this, "_locked", !1), o(this, "_opt", !1), o(this, "_null", !1), this._vs = t;
426
- }
427
- optional() {
428
- if (this._locked) throw l("optional");
429
- return this._opt = !0, this;
430
- }
431
- maybeNull() {
432
- if (this._locked) throw l("maybeNull");
433
- return this._null = !0, this;
434
- }
435
- lock() {
436
- return this._locked = !0, this;
437
- }
438
- clone() {
439
- return new z(...this._vs);
440
- }
441
- validate(t, s = g.warn) {
442
- return t === void 0 ? this._opt || (s("should be a tuple, but got undefined"), !1) : t === null ? this._null || (s("should be a tuple, but got null"), !1) : Array.isArray(t) ? t.length !== this._vs.length ? (s(`should be a tuple with length ${this._vs.length}, but got ${t.length}`), !1) : this._vs.every(
443
- (r, n) => r.validate(t[n], (...i) => {
444
- s(`[idx:${n}]`, ...i);
445
- })
446
- ) : (s(`should be a tuple, but got ${typeof t}`), !1);
447
- }
448
- }
449
- class K {
450
- constructor(...t) {
451
- o(this, "_vs"), o(this, "_key", ""), o(this, "_locked", !1), o(this, "_opt", !1), o(this, "_null", !1), this._vs = t;
452
- }
453
- optional() {
454
- if (this._locked) throw l("optional");
455
- return this._opt = !0, this;
456
- }
457
- maybeNull() {
458
- if (this._locked) throw l("maybeNull");
459
- return this._null = !0, this;
460
- }
461
- /**
462
- * 设置联合类型中的关键字段判断,用以提高联合类型校验的效率
463
- *
464
- * 仅仅对于所有联合类型元素都是 object 时有效,指定的 key 对应的值应该具有唯一性
465
- */
466
- key(t) {
467
- if (this._locked) throw l("key");
468
- return this._vs.every((s) => s instanceof R) ? this._key = t : g.warn("union type key can only be used when all validators are ObjectValidator"), this;
469
- }
470
- satisfies() {
471
- return this;
472
- }
473
- lock() {
474
- return this._locked = !0, this;
475
- }
476
- get validators() {
477
- return [...this._vs];
478
- }
479
- clone() {
480
- const t = new K(...this._vs);
481
- return t._key = this._key, t._locked = !1, t;
482
- }
483
- validate(t, s = g.warn) {
484
- if (t === void 0)
485
- return this._opt || (s("should be a union, but got undefined"), !1);
486
- if (t === null)
487
- return this._null || (s("should be a union, but got null"), !1);
488
- if (this._key && Y(t) && t) {
489
- const n = t[this._key];
490
- if (n === void 0)
491
- return s(`key field "${this._key}" is not found`, t), !1;
492
- const i = this._vs.find(
493
- (a) => a instanceof R && a.match(this._key, n)
494
- );
495
- return i ? i.validate(t, s) : (s(`key field "${this._key}" value is match union definition`, n), !1);
496
- }
497
- const r = this._vs.some((n) => n.validate(t, X));
498
- return r || s("value is not match union definition", t), r;
499
- }
500
- }
501
- class O {
502
- constructor(t, s) {
503
- o(this, "_name", ""), o(this, "_guard"), o(this, "_locked", !1), o(this, "_opt", !1), o(this, "_null", !1), this._name = t, this._guard = s;
504
- }
505
- optional() {
506
- if (this._locked) throw l("optional");
507
- return this._opt = !0, this;
508
- }
509
- maybeNull() {
510
- if (this._locked) throw l("maybeNull");
511
- return this._null = !0, this;
512
- }
513
- lock() {
514
- return this._locked = !0, this;
515
- }
516
- clone() {
517
- return new O(this._name, this._guard);
518
- }
519
- validate(t, s = g.warn) {
520
- const r = this._name || "custom type";
521
- return t === void 0 ? this._opt || (s(`should be ${r}, but got undefined`), !1) : t === null ? this._null || (s(`should be ${r}, but got null`), !1) : this._guard(t) || (s(`custom validation${this._name ? `(${this._name})` : ""} failed`), !1);
522
- }
523
- }
524
- function gt(e, t) {
525
- if (typeof e == "string") {
526
- if (!t)
527
- throw new Error("custom type guard must be defined");
528
- return new O(e, t);
529
- }
530
- return new O("", e);
531
- }
532
- const pt = {
533
- /**
534
- * object shape 的定义辅助函数
535
- */
536
- shape(e) {
537
- return e;
538
- },
539
- /**
540
- * validator 定义辅助函数
541
- */
542
- define(e) {
543
- return e;
544
- },
545
- /**
546
- * 按照类型定义生成一个类型守卫
547
- */
548
- guard(e) {
549
- return function(t) {
550
- return e.validate(t);
551
- };
552
- },
553
- /** 对象结构验证 */
554
- object(e) {
555
- return new R(e);
556
- },
557
- /**
558
- * record 数据验证,不指定 key 即 string Record。
559
- *
560
- * 如果需要指定 key 类型,使用 define 辅助工具
561
- */
562
- record(e) {
563
- return new B(e);
564
- },
565
- /** 数组类型验证 */
566
- array(e) {
567
- return new H(e);
568
- },
569
- /** 元组类型验证 */
570
- tuple(...e) {
571
- return new z(...e);
572
- },
573
- /** 联合类型验证 */
574
- union(...e) {
575
- return new K(...e);
576
- },
577
- /** 字符串类型验证 */
578
- string() {
579
- return new L();
580
- },
581
- /** 布尔型类型验证 */
582
- bool() {
583
- return new q();
584
- },
585
- /** 数字验证 */
586
- number() {
587
- return new C();
588
- },
589
- /** bigint 验证 */
590
- bigint() {
591
- return new D();
592
- },
593
- /** 自定义验证 */
594
- custom: gt,
595
- /**
596
- * 允许一个 unknown 类型,validate 总是返回 true
597
- */
598
- unknown() {
599
- return {
600
- validate(e) {
601
- return !0;
602
- }
603
- };
604
- },
605
- /**
606
- * 检测一个 never 类型,validate 总是返回 false
607
- */
608
- never() {
609
- return {
610
- validate(e) {
611
- return !1;
612
- }
613
- };
614
- }
615
- }, bt = (e) => k(e) && Object.keys(e).length === 0;
616
- pt.custom("EmptyObject", bt);
617
- function yt(e, t = "数据未能正确识别") {
618
- return typeof e == "function" ? {
619
- guard: e,
620
- message: t
621
- } : {
622
- guard: e.guard,
623
- message: e.message || t
624
- };
625
- }
626
- function wt(e, t = "") {
627
- return !t || P(e, !0) ? J(e) : (J(t) + "/" + e).replace(/\/{2,}/g, "/").replace(/:\//, "://");
628
- }
629
- function J(e) {
630
- return P(e, !0) ? e.startsWith("http") ? e : ("location" in globalThis ? location.protocol : "https:") + e : ("location" in globalThis ? location.origin : "http://127.0.0.1") + "/" + e.replace(/^\/+/, "");
631
- }
632
- function kt(e, t) {
633
- const s = {};
634
- return (e.match(/([^=&#?]+)=[^&#]*/g) || []).forEach(function(r) {
635
- const n = r.split("="), i = n[0], a = decodeURIComponent(n[1] || "");
636
- s[i] !== void 0 ? s[i] += "," + a : s[i] = a;
637
- }), t !== !0 ? s[t] || "" : s;
638
- }
639
- function vt(e, t) {
640
- if (t) {
641
- if (t === !0)
642
- return e.replace(/\?[^#]*/, "");
643
- } else return e;
644
- const s = e.split("#"), r = s[0].split("?"), n = r[0], i = r.length > 1 ? r[1] : "", a = s.length > 1 ? "#" + s[1] : "", h = typeof t == "string" ? [t] : Array.isArray(t) ? t : [];
645
- return !h.length || !i ? s[0] + a : (h.map((c) => c.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (n + "?" + i.replace(new RegExp("(?:^|&)(?:" + h.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + a);
646
- }
647
- function Ht(e, t, s = !1) {
648
- const r = typeof t == "string" ? t : Object.keys(t).map((a) => `${a}=${encodeURIComponent(t[a])}`).join("&");
649
- if (!r)
650
- return e;
651
- const n = e.split("#");
652
- s && (n[0] = vt(
653
- n[0],
654
- (r.match(/([^=&#?]+)=[^&#]+/g) || []).map((a) => a.replace(/=.+$/, ""))
655
- ));
656
- const i = n[0].indexOf("?") + 1 ? "&" : "?";
657
- return (n[0] + i + r + (n.length > 1 ? "#" + n[1] : "")).replace(/\?&/, "?");
658
- }
659
- function $t(e) {
660
- const t = e.match(/(?:\?|&)([^=]+)(?:&|$)/g);
661
- return t ? t.join("").replace(/(?:\?|^&+|&+$)/g, "").replace(/&{2}/g, "&").split("&").sort() : [];
662
- }
663
- class jt {
664
- constructor(t = 500) {
665
- v(this, "ttl");
666
- v(this, "cache");
667
- this.cache = {}, this.ttl = Math.max(t, 0);
668
- }
669
- getKey(t, s) {
670
- const r = t.replace(/#.+/, ""), n = r.replace(/\?.+/g, ""), i = Object.assign(kt(r, !0), s), a = $t(r), h = Object.keys(i).sort().map((c) => `${c}#${i[c]}`);
671
- return `${n}_${h.join(",")}_${a.join(",")}`;
672
- }
673
- updateTTL(t) {
674
- this.ttl = Math.max(t, 0);
675
- }
676
- get(t) {
677
- if (this.ttl === 0)
678
- return null;
679
- const s = this.cache[t];
680
- return s ? s.ttl < Date.now() ? (delete this.cache[t], null) : s.res : null;
681
- }
682
- set(t, s) {
683
- this.ttl !== 0 && (this.cache[t] = {
684
- ttl: Date.now() + this.ttl,
685
- res: s
686
- });
687
- }
688
- }
689
- class Rt {
690
- constructor(t) {
691
- // 保存的配置需要部分字段强制设置默认值
692
- v(this, "config", {
693
- baseURL: "/",
694
- maxRetry: 0,
695
- retryInterval: 100,
696
- retryResolve: "network",
697
- timeout: 1e4,
698
- cacheTTL: 500,
699
- credentials: "same-origin",
700
- defaultTypeGuardMessage: "响应数据未能正确识别",
701
- responseRule: {
702
- ok: {
703
- resolve: "body"
704
- },
705
- failed: {
706
- resolve: "json",
707
- messageField: "message"
708
- }
709
- }
710
- });
711
- t && this.set(t);
712
- }
713
- set(t) {
714
- if (t.baseURL && !/^\/.+/.test(t.baseURL) && !P(t.baseURL))
715
- throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"), new Error("BaseURLError");
716
- Object.assign(this.config, t);
717
- }
718
- get(t) {
719
- return this.config[t];
720
- }
721
- /** 基于 baseURL 返回完整的 url 地址 */
722
- getFullUrl(t) {
723
- return wt(t, this.config.baseURL);
724
- }
725
- /** 提示消息 */
726
- showMessage(t, s, r, n) {
727
- this.config.messageHandler && s && this.config.messageHandler(t, s, r, n);
728
- }
729
- }
730
- const et = {
731
- /** 响应数据校验失败 */
732
- UnexpectResponse: "UnexpectResponse",
733
- /** 请求被取消 */
734
- Aborted: "Aborted",
735
- /** 未知错误 */
736
- Unknown: "Unknown",
737
- /** 网络错误 */
738
- NetworkError: "NetworkError",
739
- /** 超时 */
740
- Timeout: "Timeout",
741
- /** 请求方法不被支持,在微信小程序环境下有效 */
742
- NotSupport: "NotSupport",
743
- /** url 格式错误 */
744
- URLFormatError: "URLFormatError"
745
- };
746
- function Nt(e, t, s, r) {
747
- if (t.ok && !mt(t.data) && r) {
748
- const n = yt(r, s.get("defaultTypeGuardMessage"));
749
- return n.guard(t.data) || (t.code = et.UnexpectResponse, s.showMessage(!0, `${e} ${n.message}`, t.code, t.status), console.error(t.code, e, t.data), t.data = null, t.message = n.message), t;
750
- }
751
- return t;
752
- }
753
- class zt {
754
- constructor(t, s) {
755
- v(this, "agent");
756
- v(this, "config");
757
- v(this, "cache");
758
- this.config = new Rt(s), this.agent = t, this.cache = new jt(this.config.get("cacheTTL")), this.setConfig = this.setConfig.bind(this), this.getConfig = this.getConfig.bind(this), this.request = this.request.bind(this), this.get = this.get.bind(this), this.post = this.post.bind(this), this.del = this.del.bind(this), this.patch = this.patch.bind(this), this.put = this.put.bind(this), this.head = this.head.bind(this);
759
- }
760
- /**
761
- * 执行网络请求
762
- */
763
- async request(t, s) {
764
- try {
765
- return await this.agent(t, this.config, s);
766
- } catch (r) {
767
- return console.error("RequestError", r), {
768
- ok: !1,
769
- status: -9,
770
- code: et.Unknown,
771
- message: r instanceof Error ? `${r.message}
772
- ${r.stack || ""}` : String(r),
773
- headers: {},
774
- data: null
775
- };
776
- }
777
- }
778
- /**
779
- * 检查响应的数据类型
780
- */
781
- async guard(t, s, r) {
782
- return Nt(t, s, this.config, r);
783
- }
784
- /**
785
- * 修改默认请求配置: baseURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
786
- */
787
- setConfig(t) {
788
- this.config.set(t), this.cache.updateTTL(this.config.get("cacheTTL"));
789
- }
790
- /**
791
- * 读取默认的请求配置
792
- */
793
- getConfig(t) {
794
- return this.config.get(t);
795
- }
796
- /**
797
- * 发送一个 HEAD 请求,并且不处理响应 body
798
- */
799
- async head(t, s) {
800
- const r = Object.assign({}, s || null);
801
- return r.method = "HEAD", this.guard(t, await this.request(t, r), null);
802
- }
803
- async get(t, s, r) {
804
- const n = Object.assign({}, r || null);
805
- n.method = "GET";
806
- const i = this.cache.getKey(t, n.params), a = this.cache.get(i);
807
- if (a)
808
- return this.guard(t, await a, s || null);
809
- const h = this.request(t, n);
810
- return this.cache.set(i, h), this.guard(t, await h, s || null);
811
- }
812
- async post(t, s, r, n) {
813
- const i = Object.assign({}, n || null);
814
- return i.method = "POST", i.body = s || {}, this.guard(t, await this.request(t, i), r || null);
815
- }
816
- async del(t, s, r) {
817
- const n = Object.assign({}, r || null);
818
- return n.method = "DELETE", this.guard(t, await this.request(t, n), s || null);
819
- }
820
- async put(t, s, r, n) {
821
- const i = Object.assign({}, n || null);
822
- return i.method = "PUT", i.body = s || {}, this.guard(t, await this.request(t, i), r || null);
823
- }
824
- async patch(t, s, r, n) {
825
- const i = Object.assign({}, n || null);
826
- return i.method = "PATCH", i.body = s || {}, this.guard(t, await this.request(t, i), r || null);
827
- }
828
- }
829
- async function Kt(e, t, s) {
830
- var y;
831
- const r = Object.assign({ method: "GET" }, s), n = j.FormData ? r.body instanceof FormData : !1, i = n && r.method !== "POST" && r.method !== "PUT" ? "POST" : r.method, a = i === "GET" || i === "HEAD" || i === "DELETE";
832
- a && r.body !== void 0 && (console.warn("request body is invalid with method get, head, delete"), delete r.body);
833
- const h = Object.assign(
834
- n || a ? {} : {
835
- "Content-Type": j.Blob && r.body instanceof Blob ? r.body.type || "application/octet-stream" : "application/json;charset=utf-8"
836
- },
837
- r.headers
838
- ), c = r.params || {}, _ = {};
839
- Object.keys(c).forEach(($) => {
840
- c[$] !== void 0 && (_[$] = xt(c[$]));
841
- });
842
- const f = t.getFullUrl(e), d = Et(r.body), p = r.timeout || t.get("timeout"), b = await async function() {
843
- const $ = t.get("requestTransformer");
844
- if ($)
845
- return await $({ headers: h, params: _, method: i, url: f, body: d });
846
- }(), w = typeof b == "string" && b ? b : f;
847
- return (y = t.get("logHandler")) == null || y({ type: "ready", url: w, method: i, headers: h, timeout: p, body: d }), {
848
- url: w,
849
- method: i,
850
- body: d,
851
- params: _,
852
- headers: h,
853
- timeout: p,
854
- abort: r.abort,
855
- credentials: r.credentials || t.get("credentials")
856
- };
857
- }
858
- function xt(e) {
859
- return typeof e == "string" ? e : Array.isArray(e) ? e.join(",") : e + "";
860
- }
861
- function Et(e) {
862
- if (e)
863
- return typeof e == "string" || j.URLSearchParams && e instanceof URLSearchParams || e instanceof ArrayBuffer || j.Blob && e instanceof Blob || j.FormData && e instanceof FormData ? e : JSON.stringify(e);
864
- }
865
- const st = "data", N = "message";
866
- function Ot(e, t, s, r, n) {
867
- const i = n || r;
868
- return G(e) ? Mt(i.ok || r.ok, e, t, s) : Ft(i.failed || r.failed, t, s);
869
- }
870
- const Gt = function(e) {
871
- const t = [], s = e.failed || { resolve: "json" };
872
- switch (t.push("- 当http状态码 <200 或者 >=400 时"), s.resolve) {
873
- case "body":
874
- t.push(" 将响应内容格式化为字符串并作为错误消息");
875
- break;
876
- case "json":
877
- t.push(" 将响应解析为json,并读取 " + (s.messageField || N) + " 作为错误消息");
878
- break;
879
- }
880
- const r = e.ok || { resolve: "body" };
881
- switch (t.push("- 当http状态码 >=200 并且 <400 时"), r.resolve) {
882
- case "body":
883
- t.push(" 将响应尝试解析为 json,并作为数据内容返回");
884
- break;
885
- case "json":
886
- t.push(
887
- " 将响应解析为 json,读取 " + (r.dataField || st) + " 作为响应数据,读取 " + (r.messageField || N) + " 作为提示消息"
888
- ), r.statusField && t.push(
889
- " 当 " + r.statusField + " 为 " + (r.statusOKValue || "空值") + " 时是成功提示,否则是错误消息"
890
- ), r.ignoreMessage && t.push(" 并忽略以下消息:" + r.ignoreMessage);
891
- break;
892
- }
893
- return t.join(`
894
- `);
895
- };
896
- function Ft(e, t, s) {
897
- const r = e || { resolve: "json", messageField: N }, n = {
898
- ok: !1,
899
- code: t,
900
- message: s,
901
- data: null
902
- };
903
- switch (r.resolve) {
904
- case "body":
905
- n.message = V(s) || s;
906
- break;
907
- case "json":
908
- const { code: i, message: a } = At(s, r.converter, r.statusField, r.messageField);
909
- n.code = i || t, n.message = V(s) || a;
910
- break;
911
- }
912
- return n;
913
- }
914
- function At(e, t, s, r = N) {
915
- if (!tt(e))
916
- return { message: "" };
917
- const n = M(S(e), t);
918
- return !n || !k(n) ? { message: e } : {
919
- code: s ? T(n, s) : "",
920
- message: T(n, r) || e
921
- };
922
- }
923
- function T(e, t) {
924
- const s = Array.isArray(t) ? t : [t];
925
- for (const r of s)
926
- if (r in e)
927
- return St(e[r]);
928
- return "";
929
- }
930
- function St(e) {
931
- return e ? typeof e == "string" ? e : JSON.stringify(e) : "";
932
- }
933
- const Ut = /<title>([^<]+)<\/title>/i, Tt = /<message>([^<]+)<\/message>/i;
934
- function V(e) {
935
- const t = e.match(Ut);
936
- if (t)
937
- return t[1];
938
- const s = e.match(Tt);
939
- return s ? s[1] : "";
940
- }
941
- function Mt(e, t, s, r) {
942
- const n = e || { resolve: "body" }, i = {
943
- ok: !0,
944
- code: s,
945
- message: "",
946
- data: null
947
- };
948
- if (t === 204 || !r)
949
- return i;
950
- if (n.resolve === "body")
951
- return i.data = tt(r) ? M(S(r), e.converter) : r, i;
952
- const a = M(S(r), e.converter);
953
- if (!a || !k(a))
954
- return i.ok = !1, i.code = "ResponseFormatError", i.message = "响应内容无法格式化为 Object", i;
955
- const h = n.statusField, c = n.statusOKValue || "", _ = n.dataField || st, f = n.messageField || N, d = n.ignoreMessage || "";
956
- if (h && !(h in a))
957
- return i.ok = !1, i.code = "ResponseFieldMissing", i.message = "响应内容找不到状态字段 " + h, i;
958
- const p = h ? a[h] + "" : "";
959
- return i.ok = h ? p === c : !0, i.code = p || s, i.data = _ === !0 ? a : _ in a ? a[_] : null, i.message = T(a, f), d && i.message && (Array.isArray(d) && d.includes(i.message) || typeof d == "string" && i.message === d) && (i.message = ""), i;
960
- }
961
- function G(e) {
962
- return e >= 200 && e < 400;
963
- }
964
- function M(e, t) {
965
- return t ? typeof t == "function" ? t(e) : (console.warn('工具不再支持 "camelize", "snakify" 参数,请自行提供函数来转化 body 内容'), e) : e;
966
- }
967
- const Pt = lt("APIError");
968
- function It(e) {
969
- const t = {};
970
- for (const n in e.headers)
971
- (n.startsWith("x-") || n.includes("trace") || n.includes("server") || /\b(?:id|uuid)\b/.test(n)) && (t[n] = e.headers[n]);
972
- const s = e.url.replace(/^(?:https?:)?\/*/i, "").replace(/\?.+/, ""), r = e.status < 0 ? "unknown" : e.status;
973
- return {
974
- sentryError: new Pt(`${s} | ${r}${e.code ? ` | ${e.code}` : ""}`),
975
- sentryTags: {
976
- ...t,
977
- status: r,
978
- method: e.method,
979
- code: e.code || "unknown",
980
- message: e.message || "empty"
981
- },
982
- sentryExtra: {
983
- url: e.url,
984
- responseBody: e.body || "empty",
985
- responseHeaders: e.headers,
986
- rawError: e.error
987
- }
988
- };
989
- }
990
- function Lt(e) {
991
- return e.reduce(
992
- (t, [s, r]) => (s && (t[s] = r || ""), t),
993
- {}
994
- );
995
- }
996
- function Wt(e, t, s, r) {
997
- var b;
998
- const n = e.status, i = e.method, a = Lt(
999
- Object.entries(e.headers || {}).map(([w, y]) => [w.toLowerCase(), y])
1000
- ), { ok: h, code: c, data: _, message: f } = Ot(
1001
- n,
1002
- e.statusText,
1003
- e.body,
1004
- s.get("responseRule"),
1005
- r == null ? void 0 : r.responseRule
1006
- );
1007
- if (!G(n)) {
1008
- const w = It({
1009
- url: e.url,
1010
- method: e.method,
1011
- status: n,
1012
- code: c,
1013
- message: f,
1014
- body: e.body,
1015
- headers: a,
1016
- error: e.rawError
1017
- });
1018
- (s.get("errorHandler") || Ct)({
1019
- url: t,
1020
- method: i,
1021
- status: n,
1022
- code: c,
1023
- message: f,
1024
- headers: a,
1025
- rawError: e.rawError,
1026
- responseBody: e.body,
1027
- ...w
1028
- });
1029
- }
1030
- if (n < 0)
1031
- return Z(
1032
- { ok: !1, status: n, code: e.statusText, headers: {}, message: "", data: null },
1033
- `${i} ${t} ${e.statusText}`,
1034
- i,
1035
- t,
1036
- s,
1037
- r
1038
- );
1039
- const d = { ok: h, data: _, code: c, message: f, status: n, headers: a };
1040
- (b = s.get("responseHandler")) == null || b({ ...d }, i, t);
1041
- const p = h ? f : f || e.statusText;
1042
- return Z(d, p, i, t, s, r);
1043
- }
1044
- function Z(e, t, s, r, n, i) {
1045
- const a = n.get("message"), h = a === !1 || (i == null ? void 0 : i.message) === !1 ? !1 : (i == null ? void 0 : i.message) || a;
1046
- if (h !== !1) {
1047
- const c = typeof h == "function" ? h(e, s, r, t) : t;
1048
- c instanceof Error ? n.showMessage(!0, c.message, e.code, e.status) : c && typeof c == "object" && "message" in c ? n.showMessage(!1, c.message, e.code, e.status) : n.showMessage(!e.ok, c, e.code, e.status);
1049
- }
1050
- return e;
1051
- }
1052
- function Ct(e) {
1053
- const t = {};
1054
- for (const s in e)
1055
- s.startsWith("sentry") || (t[s] = e[s]);
1056
- console.error("RequestError", t);
1057
- }
1058
- async function Dt(e, t, s, r, n) {
1059
- const i = n || 0, a = Math.max(0, Math.min(10, (r == null ? void 0 : r.maxRetry) ?? s.get("maxRetry") ?? 0)), h = (r == null ? void 0 : r.retryResolve) ?? s.get("retryResolve"), c = s.get("logHandler");
1060
- c == null || c({
1061
- type: "prepare",
1062
- url: t,
1063
- method: (r == null ? void 0 : r.method) || "GET",
1064
- retry: i,
1065
- maxRetry: a,
1066
- message: i === 0 ? "start" : `retry ${i}/${a} start`,
1067
- headers: r == null ? void 0 : r.headers,
1068
- options: r
1069
- });
1070
- const _ = Date.now(), f = await e(t, s, r), d = f.status, p = Date.now() - _, b = `[cost ${p}][${d}] ${d < 0 ? f.body : ""}`;
1071
- c == null || c({
1072
- type: "finished",
1073
- url: t,
1074
- method: f.method,
1075
- retry: i,
1076
- maxRetry: a,
1077
- message: i === 0 ? `finish ${b}` : `retry ${i}/${a} finish ${b}`,
1078
- response: f,
1079
- headers: f.headers,
1080
- cost: p
1081
- });
1082
- const w = G(d);
1083
- if (!a || i >= a || h === "network" && d > 0 || h === "status" && w || Array.isArray(h) && !h.includes(d) || typeof h == "function" && h(f, i) !== !0)
1084
- return f;
1085
- const y = (r == null ? void 0 : r.retryInterval) ?? s.get("retryInterval") ?? 100;
1086
- return await at(
1087
- Math.max(
1088
- 100,
1089
- y === "2EB" ? Math.pow(2, i) * 100 : typeof y == "function" ? y(i + 1, { url: t, status: d, method: f.method }) || 0 : y
1090
- )
1091
- ), await Dt(e, t, s, r, i + 1);
1092
- }
1093
- export {
1094
- P as A,
1095
- zt as N,
1096
- Rt as R,
1097
- et as a,
1098
- Bt as b,
1099
- Kt as c,
1100
- Gt as d,
1101
- Lt as f,
1102
- Ht as g,
1103
- Wt as h,
1104
- j,
1105
- Dt as r
1106
- };