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