@seayoo-web/request 3.3.3 → 3.4.2

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