@seayoo-web/request 1.7.11 → 2.0.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,499 +0,0 @@
1
- var K = Object.defineProperty;
2
- var q = (e, t, n) => t in e ? K(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
- var f = (e, t, n) => (q(e, typeof t != "symbol" ? t + "" : t, n), n);
4
- const m = typeof globalThis < "u" ? globalThis : typeof global < "u" ? global : typeof window < "u" ? window : {}, O = {
5
- fetch: "fetch" in m,
6
- window: "window" in m,
7
- FormData: "FormData" in m,
8
- Blob: "Blob" in m,
9
- wx: "wx" in m,
10
- TextDecoder: "TextDecoder" in m,
11
- AbortController: "AbortController" in m
12
- };
13
- function N(e) {
14
- return e.reduce(
15
- (t, [n, s]) => (n && (t[n] = s || ""), t),
16
- {}
17
- );
18
- }
19
- function G(e) {
20
- return new Promise((t) => setTimeout(t, Math.max(0, e)));
21
- }
22
- function J() {
23
- }
24
- function j(e) {
25
- return e ? e[0].toLowerCase() + e.slice(1) : "";
26
- }
27
- const P = /_\w*/, S = /-\w*/;
28
- function M(e) {
29
- const t = P.test(e) ? e.replace(/(?:^_*|_*$)/g, "").replace(/_+([^_])/g, (n, s) => s.toUpperCase()) : S.test(e) ? e.replace(/(?:^-*|-*$)/g, "").replace(/-+(\w)/g, (n, s) => s.toUpperCase()) : e;
30
- return j(t);
31
- }
32
- function U(e) {
33
- return P.test(e) ? j(e).replace(/(?:^_*|_*$)/g, "").replace(/_+([^_])/g, (t, n) => "_" + n.toLowerCase()) : S.test(e) ? j(e.replace(/(?:^-*|-*$)/g, "")).replace(/-+(\w)/g, (t, n) => "_" + n.toLowerCase()) : j(e).replace(/[A-Z]/g, (t) => `_${t.toLowerCase()}`);
34
- }
35
- const V = /^(?:https?:)?\/\/.+$/i, W = /^https?:\/\/.+$/i, Z = /^\{[\d\D]*\}$/, z = /^\[[\d\D]*\]$/;
36
- function T(e, t = !1) {
37
- return t ? V.test(e) : W.test(e);
38
- }
39
- function Q(e) {
40
- return e == null;
41
- }
42
- function v(e, ...t) {
43
- if (!e || typeof e != "object")
44
- return !1;
45
- const n = Object.getPrototypeOf(e);
46
- return n !== Object.prototype && n !== null ? !1 : t.every((s) => s in e);
47
- }
48
- function H(e) {
49
- return Z.test(e) || z.test(e);
50
- }
51
- function C(e, t) {
52
- try {
53
- const n = JSON.parse(e);
54
- return t ? t(n) ? n : null : n;
55
- } catch {
56
- return null;
57
- }
58
- }
59
- "" + Math.random().toString(32).slice(2);
60
- function R(e, t = !1) {
61
- return typeof e == "string" ? M(e) : Array.isArray(e) ? e.map((n) => !t || typeof n == "string" ? R(n) : typeof n == "object" && n ? R(n, !0) : n) : v(e) ? Object.keys(e).reduce(
62
- (n, s) => {
63
- const r = M(String(s)), a = r.charAt(0).toLowerCase() + r.slice(1);
64
- return n[a] = t ? e[s] : R(e[s]), n;
65
- },
66
- {}
67
- ) : e;
68
- }
69
- function $(e, t = !1) {
70
- return typeof e == "string" ? U(e) : Array.isArray(e) ? e.map((n) => !t || typeof n == "string" ? $(n) : typeof n == "object" && n ? $(n, t) : n) : v(e) ? Object.keys(e).reduce(
71
- (n, s) => {
72
- const r = U(String(s));
73
- return n[r] = t ? e[s] : $(e[s]), n;
74
- },
75
- {}
76
- ) : e;
77
- }
78
- async function ye(e) {
79
- return await new Promise(function(t) {
80
- const n = document.getElementsByTagName("head")[0], s = document.createElement("script");
81
- s.setAttribute("type", "text/javascript"), s.setAttribute("charset", "utf-8"), s.onload = function() {
82
- n.removeChild(s), t(!0);
83
- }, s.onerror = function() {
84
- n.removeChild(s), t(!1);
85
- }, s.setAttribute("src", e), n.appendChild(s);
86
- });
87
- }
88
- function X(e, t = "数据未能正确识别") {
89
- return typeof e == "function" ? {
90
- guard: e,
91
- message: t
92
- } : {
93
- guard: e.guard,
94
- message: e.message || t
95
- };
96
- }
97
- function x(e, t = "") {
98
- return !t || T(e, !0) ? L(e) : (L(t) + "/" + e).replace(/\/{2,}/g, "/").replace(/:\//, "://");
99
- }
100
- function L(e) {
101
- return T(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(/^\/+/, "");
102
- }
103
- function Y(e, t) {
104
- const n = {};
105
- return (e.match(/([^=&#?]+)=[^&#]*/g) || []).forEach(function(s) {
106
- const r = s.split("="), a = r[0], o = decodeURIComponent(r[1] || "");
107
- n[a] !== void 0 ? n[a] += "," + o : n[a] = o;
108
- }), t !== !0 ? n[t] || "" : n;
109
- }
110
- function ee(e, t) {
111
- if (t) {
112
- if (t === !0)
113
- return e.replace(/\?[^#]*/, "");
114
- } else
115
- return e;
116
- const n = e.split("#"), s = n[0].split("?"), r = s[0], a = s.length > 1 ? s[1] : "", o = n.length > 1 ? "#" + n[1] : "", c = typeof t == "string" ? [t] : Array.isArray(t) ? t : [];
117
- return !c.length || !a ? n[0] + o : (c.map((i) => i.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (r + "?" + a.replace(new RegExp("(?:^|&)(?:" + c.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + o);
118
- }
119
- function pe(e, t, n = !1) {
120
- const s = typeof t == "string" ? t : Object.keys(t).map((o) => `${o}=${encodeURIComponent(t[o])}`).join("&");
121
- if (!s)
122
- return e;
123
- const r = e.split("#");
124
- n && (r[0] = ee(
125
- r[0],
126
- (s.match(/([^=&#?]+)=[^&#]+/g) || []).map((o) => o.replace(/=.+$/, ""))
127
- ));
128
- const a = r[0].indexOf("?") + 1 ? "&" : "?";
129
- return (r[0] + a + s + (r.length > 1 ? "#" + r[1] : "")).replace(/\?&/, "?");
130
- }
131
- function te(e) {
132
- const t = e.match(/(?:\?|&)([^=]+)(?:&|$)/g);
133
- return t ? t.join("").replace(/(?:\?|^&+|&+$)/g, "").replace(/&{2}/g, "&").split("&").sort() : [];
134
- }
135
- class se {
136
- constructor(t = 500) {
137
- f(this, "ttl");
138
- f(this, "cache");
139
- this.cache = {}, this.ttl = Math.max(t, 0);
140
- }
141
- getKey(t, n) {
142
- const s = t.replace(/#.+/, ""), r = s.replace(/\?.+/g, ""), a = Object.assign(Y(s, !0), n), o = te(s), c = Object.keys(a).sort().map((i) => `${i}#${a[i]}`);
143
- return `${r}_${c.join(",")}_${o.join(",")}`;
144
- }
145
- updateTTL(t) {
146
- this.ttl = Math.max(t, 0);
147
- }
148
- get(t) {
149
- if (this.ttl === 0)
150
- return null;
151
- const n = this.cache[t];
152
- return n ? n.ttl < Date.now() ? (delete this.cache[t], null) : n.res : null;
153
- }
154
- set(t, n) {
155
- this.ttl !== 0 && (this.cache[t] = {
156
- ttl: Date.now() + this.ttl,
157
- res: n
158
- });
159
- }
160
- }
161
- const D = "UnexpectResponse";
162
- function ne(e, t, n, s) {
163
- if (t.ok && !Q(t.data) && s) {
164
- const r = X(s, "响应数据未能正确识别");
165
- return r.guard(t.data) || (n.showMessage(!0, `${e} ${r.message}`, t.code, t.status), console.error(D, e, t.data), t.data = null, t.code = D, t.message = r.message), t;
166
- }
167
- return t;
168
- }
169
- class ae {
170
- constructor(t) {
171
- // 保存的配置需要部分字段强制设置默认值
172
- f(this, "config", {
173
- baseURL: "",
174
- maxRetry: 0,
175
- retryInterval: 1e3,
176
- retryResolve: "network",
177
- timeout: 1e4,
178
- cacheTTL: 500,
179
- credentials: "same-origin",
180
- responseRule: {
181
- ok: {
182
- resolve: "body"
183
- },
184
- failed: {
185
- resolve: "json",
186
- messageField: "message"
187
- }
188
- }
189
- });
190
- t && this.set(t);
191
- }
192
- set(t) {
193
- if (t.baseURL && !/^\/.+/.test(t.baseURL) && !T(t.baseURL))
194
- throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"), new Error("BaseURLError");
195
- Object.assign(this.config, t);
196
- }
197
- get(t) {
198
- return this.config[t];
199
- }
200
- /** 基于 baseURL 返回完整的 url 地址, 如果 url 地址以 / 开头则表示忽略 baseURL 的值 */
201
- getFullUrl(t) {
202
- return t.startsWith("/") ? x(t) : x(t, this.config.baseURL);
203
- }
204
- /** 提示消息 */
205
- showMessage(t, n, s, r) {
206
- this.config.messageHandler && n && this.config.messageHandler(t, n, s, r);
207
- }
208
- }
209
- class be {
210
- constructor(t, n) {
211
- f(this, "agent");
212
- f(this, "config");
213
- f(this, "cache");
214
- this.config = new ae(n), this.agent = t, this.cache = new se(this.config.get("cacheTTL")), this.setConfig = this.setConfig.bind(this), this.getConfig = this.getConfig.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);
215
- }
216
- /**
217
- * 执行网络请求
218
- */
219
- async exec(t, n) {
220
- try {
221
- return await this.agent(t, this.config, n);
222
- } catch (s) {
223
- return console.error("RequestError", s), {
224
- ok: !1,
225
- status: -9,
226
- code: "Unkonwn",
227
- message: String(s),
228
- headers: {},
229
- data: null
230
- };
231
- }
232
- }
233
- /**
234
- * 检查响应的数据类型
235
- */
236
- async guard(t, n, s) {
237
- return ne(t, n, this.config, s);
238
- }
239
- /**
240
- * 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
241
- */
242
- setConfig(t) {
243
- this.config.set(t), this.cache.updateTTL(this.config.get("cacheTTL"));
244
- }
245
- /**
246
- * 读取默认的请求配置
247
- */
248
- getConfig(t) {
249
- return this.config.get(t);
250
- }
251
- /**
252
- * 发送一个 HEAD 请求,并且不处理响应 body
253
- */
254
- async head(t, n) {
255
- const s = Object.assign({}, n || null);
256
- return s.method = "HEAD", this.guard(t, await this.exec(t, s), null);
257
- }
258
- async get(t, n, s) {
259
- const r = Object.assign({}, s || null);
260
- r.method = "GET";
261
- const a = this.cache.getKey(t, r.params), o = this.cache.get(a);
262
- if (o)
263
- return this.guard(t, await o, n || null);
264
- const c = this.exec(t, r);
265
- return this.cache.set(a, c), this.guard(t, await c, n || null);
266
- }
267
- async post(t, n, s, r) {
268
- const a = Object.assign({}, r || null);
269
- return a.method = "POST", a.body = n, this.guard(t, await this.exec(t, a), s || null);
270
- }
271
- async del(t, n, s) {
272
- const r = Object.assign({}, s || null);
273
- return r.method = "DELETE", this.guard(t, await this.exec(t, r), n || null);
274
- }
275
- async put(t, n, s, r) {
276
- const a = Object.assign({}, r || null);
277
- return a.method = "PUT", a.body = n, this.guard(t, await this.exec(t, a), s || null);
278
- }
279
- async patch(t, n, s, r) {
280
- const a = Object.assign({}, r || null);
281
- return a.method = "PATCH", a.body = n, this.guard(t, await this.exec(t, a), s || null);
282
- }
283
- }
284
- const I = "data", b = "message";
285
- function re(e, t, n, s, r) {
286
- const a = r || s;
287
- return A(e) ? he(a.ok || s.ok, e, t, n) : oe(a.failed || s.failed, t, n);
288
- }
289
- const we = function(e) {
290
- const t = [], n = e.failed || { resolve: "json" };
291
- switch (t.push("- 当http状态码 <200 或者 >=400 时"), n.resolve) {
292
- case "body":
293
- t.push(" 将响应内容格式化为字符串并作为错误消息");
294
- break;
295
- case "json":
296
- t.push(" 将响应解析为json,并读取 " + (n.messageField || b) + " 作为错误消息");
297
- break;
298
- }
299
- const s = e.ok || { resolve: "body" };
300
- switch (t.push("- 当http状态码 >=200 并且 <400 时"), s.resolve) {
301
- case "body":
302
- t.push(" 将响应尝试解析为 json,并作为数据内容返回");
303
- break;
304
- case "json":
305
- t.push(
306
- " 将响应解析为 json,读取 " + (s.dataField || I) + " 作为响应数据,读取 " + (s.messageField || b) + " 作为提示消息"
307
- ), s.statusField && t.push(" 当 " + s.statusField + " 为 " + (s.statusOKValue || "空值") + " 时是成功提示,否则是错误消息"), s.ignoreMessage && t.push(" 并忽略以下消息:" + s.ignoreMessage);
308
- break;
309
- }
310
- return t.join(`
311
- `);
312
- };
313
- function oe(e, t, n) {
314
- const s = e || { resolve: "json", messageField: b }, r = {
315
- ok: !1,
316
- code: t,
317
- message: n,
318
- data: null
319
- };
320
- switch (s.resolve) {
321
- case "body":
322
- r.message = _(n) || n;
323
- break;
324
- case "json":
325
- const { code: a, message: o } = ce(n, s.converter, s.statusField, s.messageField);
326
- r.code = a || t, r.message = _(n) || o;
327
- break;
328
- }
329
- return r;
330
- }
331
- function ce(e, t, n, s = b) {
332
- if (!H(e))
333
- return { message: "" };
334
- const r = k(C(e), t);
335
- return !r || !v(r) ? { message: e } : {
336
- code: n ? F(r, n) : "",
337
- message: F(r, s) || e
338
- };
339
- }
340
- function F(e, t) {
341
- const n = Array.isArray(t) ? t : [t];
342
- for (const s of n)
343
- if (s in e)
344
- return ie(e[s]);
345
- return "";
346
- }
347
- function ie(e) {
348
- return e ? typeof e == "string" ? e : JSON.stringify(e) : "";
349
- }
350
- const ue = /<title>([^<]+)<\/title>/i, le = /<message>([^<]+)<\/message>/i;
351
- function _(e) {
352
- const t = e.match(ue);
353
- if (t)
354
- return t[1];
355
- const n = e.match(le);
356
- return n ? n[1] : "";
357
- }
358
- function he(e, t, n, s) {
359
- const r = e || { resolve: "body" }, a = {
360
- ok: !0,
361
- code: n,
362
- message: "",
363
- data: null
364
- };
365
- if (t === 204 || !s)
366
- return a;
367
- if (r.resolve === "body")
368
- return a.data = H(s) ? k(C(s), e.converter) : s, a;
369
- const o = k(C(s), e.converter);
370
- if (!o || !v(o))
371
- return a.ok = !1, a.code = "ResponseFormatError", a.message = "响应内容无法格式化为 Object", a;
372
- const c = r.statusField, i = r.statusOKValue || "", h = r.dataField || I, l = r.messageField || b, u = r.ignoreMessage || "";
373
- if (c && !(c in o))
374
- return a.ok = !1, a.code = "ResponseFieldMissing", a.message = "响应内容找不到状态字段 " + c, a;
375
- const d = c ? o[c] + "" : "";
376
- return a.ok = c ? d === i : !0, a.code = d || n, a.data = h === !0 ? o : h in o ? o[h] : null, a.message = F(o, l), u && a.message && (Array.isArray(u) && u.includes(a.message) || typeof u == "string" && a.message === u) && (a.message = ""), a;
377
- }
378
- function A(e) {
379
- return e >= 200 && e < 400;
380
- }
381
- function k(e, t) {
382
- return t === "camelize" ? R(e) : t === "snakify" ? $(e) : e;
383
- }
384
- async function de(e, t, n, s, r) {
385
- const a = r || 0, o = Math.max(0, Math.min(10, (s == null ? void 0 : s.maxRetry) ?? n.get("maxRetry") ?? 0)), c = (s == null ? void 0 : s.retryResolve) ?? n.get("retryResolve"), i = n.get("logHandler") || J;
386
- i({
387
- type: "prepear",
388
- url: t,
389
- method: (s == null ? void 0 : s.method) || "GET",
390
- retry: a,
391
- maxRetry: o,
392
- message: a === 0 ? "start" : `retry ${a}/${o} start`,
393
- headers: s == null ? void 0 : s.headers,
394
- options: s
395
- });
396
- const h = Date.now(), l = await e(t, n, s), u = l.status, d = Date.now() - h, y = `[cost ${d}][${u}] ${u < 0 ? l.body : ""}`;
397
- i({
398
- type: "finished",
399
- url: t,
400
- method: l.method,
401
- retry: a,
402
- maxRetry: o,
403
- message: a === 0 ? `finish ${y}` : `retry ${a}/${o} finish ${y}`,
404
- response: l,
405
- headers: l.headers,
406
- cost: d
407
- });
408
- const w = A(u);
409
- if (!o || c === "network" && u > 0 || c === "status" && w || Array.isArray(c) && !c.includes(u) || typeof c == "function" && c(l, a) !== !0 || a >= o)
410
- return l;
411
- const g = (s == null ? void 0 : s.retryInterval) ?? n.get("retryInterval") ?? 1e3;
412
- return await G(
413
- Math.max(
414
- 100,
415
- g === "2EB" ? Math.pow(2, a) * 1e3 : typeof g == "function" ? g(a + 1) || 0 : g
416
- )
417
- ), await de(e, t, n, s, a + 1);
418
- }
419
- async function je(e, t, n) {
420
- var g;
421
- const s = Object.assign({ method: "GET" }, n), r = O.FormData ? s.body instanceof FormData : !1, a = r && s.method !== "POST" && s.method !== "PUT" ? "POST" : s.method, o = a === "GET" || a === "HEAD" || a === "DELETE";
422
- o && s.body !== void 0 && (console.warn("request body is invalid with method get, head, delete"), delete s.body);
423
- const c = Object.assign(
424
- r || o ? {} : {
425
- "Content-Type": O.Blob && s.body instanceof Blob ? s.body.type || "application/octet-stream" : "application/json;charset=utf-8"
426
- },
427
- s.headers
428
- ), i = s.params || {}, h = {};
429
- Object.keys(i).forEach((p) => {
430
- i[p] !== void 0 && (h[p] = ge(i[p]));
431
- });
432
- const l = t.getFullUrl(e), u = fe(s.body), d = s.timeout || t.get("timeout"), y = await async function() {
433
- var E;
434
- const p = t.get("requestTransformer");
435
- return p ? await p({ headers: c, params: h, method: a, url: l, body: u }) : await ((E = t.get("requestHandler")) == null ? void 0 : E(c, h, a, e));
436
- }(), w = typeof y == "string" && y ? y : l;
437
- return (g = t.get("logHandler")) == null || g({ type: "ready", url: w, method: a, headers: c, timeout: d, body: u }), {
438
- url: w,
439
- method: a,
440
- body: u,
441
- params: h,
442
- headers: c,
443
- timeout: d,
444
- abort: s.abort,
445
- credentials: s.credentials || t.get("credentials")
446
- };
447
- }
448
- function ge(e) {
449
- return typeof e == "string" ? e : Array.isArray(e) ? e.join(",") : e + "";
450
- }
451
- function fe(e) {
452
- if (e)
453
- return typeof e == "string" || e instanceof URLSearchParams || e instanceof ArrayBuffer || O.Blob && e instanceof Blob || O.FormData && e instanceof FormData ? e : JSON.stringify(e);
454
- }
455
- function Re(e, t, n, s) {
456
- var c, i;
457
- if (e.status < 0)
458
- return B(
459
- { ok: !1, status: e.status, code: e.statusText, headers: {}, message: "", data: null },
460
- `${e.method} ${t} ${e.statusText}`,
461
- e.method,
462
- t,
463
- n,
464
- s
465
- );
466
- const r = N(Object.entries(e.headers || {}).map(([h, l]) => [h.toLowerCase(), l]));
467
- A(e.status) || (c = n.get("errorHandler")) == null || c(e.status, e.method, t, r, e.rawError, e.body);
468
- const a = {
469
- ...re(e.status, e.statusText, e.body, n.get("responseRule"), s == null ? void 0 : s.responseRule),
470
- status: e.status,
471
- headers: r
472
- };
473
- (i = n.get("responseHandler")) == null || i({ ...a }, e.method, t);
474
- const o = a.ok ? a.message : a.message || e.statusText;
475
- return B(a, o, e.method, t, n, s);
476
- }
477
- function B(e, t, n, s, r, a) {
478
- const o = r.get("message"), c = o === !1 || (a == null ? void 0 : a.message) === !1 ? !1 : (a == null ? void 0 : a.message) || o;
479
- if (c !== !1) {
480
- const i = typeof c == "function" ? c(e, n, s, t) : t;
481
- i instanceof Error ? r.showMessage(!0, i.message, e.code, e.status) : i && typeof i == "object" && "message" in i ? r.showMessage(!1, i.message, e.code, e.status) : r.showMessage(!e.ok, i, e.code, e.status);
482
- }
483
- return e;
484
- }
485
- const $e = "1.7.11";
486
- export {
487
- T as G,
488
- be as N,
489
- ae as R,
490
- O as S,
491
- pe as W,
492
- je as c,
493
- N as f,
494
- we as g,
495
- Re as h,
496
- de as r,
497
- $e as v,
498
- ye as x
499
- };