@seayoo-web/request 4.0.2 → 4.0.4

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.
package/README.md CHANGED
@@ -12,11 +12,11 @@
12
12
  ## 特性
13
13
 
14
14
  1. 默认基于 fetch,请求和响应解析默认基于 json
15
- 2. 支持重试配置 maxRetry / retryResolve / retryInterval
15
+ 2. 支持重试配置 maxRetry / retryResolve / retryInterval,并默认合理的重试策略
16
16
  3. 支持响应结果处理策略 responseRule 和通用提示配置
17
17
  4. 支持类型守卫 typeGuard
18
18
  5. 支持多实例,多端(浏览器,nodejs,微信小程序)
19
- 6. get 请求支持并发缓存(默认缓存 500ms
19
+ 6. 默认 get 请求支持并发缓存(默认缓存 500ms)亦可自定义缓存策略
20
20
  7. 函数永不抛错,返回固定解析结构 { ok, data, status, headers, code, message }
21
21
  8. 提供格式化良好的 sentry 信息用于错误上报
22
22
  9. 提供 jsonp / jsonx 函数,支持带上传进度的 upload 函数
@@ -232,7 +232,7 @@ defaultMessage: string
232
232
 
233
233
  - `default`: 在 `network` 基础之上,如果是 Tencent EO 响应的 552/522 错误码,则重试;
234
234
 
235
- - `network`: 表示仅仅当网络错误时(不含 aborted/timeout)才重试;
235
+ - `network`: 表示仅仅当网络错误时(不含 aborted/timeout)重试;
236
236
 
237
237
  - `number[]`:当设置为 number[] 时,将检查 http 状态码,匹配则重试;
238
238
 
@@ -312,7 +312,7 @@ sentryExtra: Record<string, unknown>
312
312
 
313
313
  ### params
314
314
 
315
- 类型:Record<string, string | number | boolean>
315
+ 类型:Record<string, string | number | boolean | null | undefined>
316
316
 
317
317
  ### headers
318
318
 
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { h, r as E, G as y, c as q, f as v, a as C, R as w, H as R, b as H, v as x, d as L, N as T, X as k } from "./retry--akoKQtX.js";
2
- import { g as W } from "./retry--akoKQtX.js";
3
- import { f as S } from "./request.fetch-U42cahT4.js";
1
+ import { h, r as E, G as y, c as q, f as v, a as C, R as w, H as R, b as H, v as x, d as L, N as T, X as k } from "./retry-LYfsjIVg.js";
2
+ import { g as W } from "./retry-LYfsjIVg.js";
3
+ import { f as S } from "./request.fetch-zzHMZXfR.js";
4
4
  const j = async function(n, a, t) {
5
5
  return h(await E(m, n, a, t), n, a, t);
6
6
  };
package/dist/node.js CHANGED
@@ -1,6 +1,6 @@
1
- import { h as w, r as R, c as y, e as b, f as q, R as s, N as h, X as g } from "./retry--akoKQtX.js";
2
- import { g as S } from "./retry--akoKQtX.js";
3
- import { f as x } from "./request.fetch-U42cahT4.js";
1
+ import { h as w, r as R, c as y, e as b, f as q, R as s, N as h, X as g } from "./retry-LYfsjIVg.js";
2
+ import { g as S } from "./retry-LYfsjIVg.js";
3
+ import { f as x } from "./request.fetch-zzHMZXfR.js";
4
4
  import N from "node:http";
5
5
  import C from "node:https";
6
6
  const E = async function(o, n, a) {
@@ -1,4 +1,4 @@
1
- import { h as f, r as h, c as m, i as b, f as y, e as T, R as u } from "./retry--akoKQtX.js";
1
+ import { h as f, r as h, c as m, i as b, f as y, e as T, R as u } from "./retry-LYfsjIVg.js";
2
2
  const x = async function(o, a, s) {
3
3
  return f(await h(w, o, a, s), o, a, s);
4
4
  }, w = async function(o, a, s) {
@@ -2,35 +2,35 @@ const f = typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : type
2
2
  function C() {
3
3
  return f;
4
4
  }
5
- function m(e) {
5
+ function y(e) {
6
6
  return typeof e == "function";
7
7
  }
8
8
  function U(e) {
9
9
  return typeof e == "object" && e !== null;
10
10
  }
11
- function P() {
12
- return "wx" in f && U(f.wx) && "getSystemInfo" in f.wx && m(f.wx.getSystemInfo);
11
+ function O() {
12
+ return "wx" in f && U(f.wx) && "getSystemInfo" in f.wx && y(f.wx.getSystemInfo);
13
13
  }
14
14
  function we() {
15
- return "fetch" in f && m(f.fetch);
15
+ return "fetch" in f && y(f.fetch);
16
16
  }
17
17
  function be() {
18
- return "window" in f && U(f.window) && !P();
18
+ return "window" in f && U(f.window) && !O();
19
19
  }
20
20
  function R() {
21
- return "Blob" in f && m(f.Blob);
21
+ return "Blob" in f && y(f.Blob);
22
22
  }
23
- function M() {
24
- return "FormData" in f && m(f.FormData);
23
+ function F() {
24
+ return "FormData" in f && y(f.FormData);
25
25
  }
26
- function O() {
27
- return "TextDecoder" in f && m(f.TextDecoder);
26
+ function M() {
27
+ return "TextDecoder" in f && y(f.TextDecoder);
28
28
  }
29
29
  function Ee() {
30
- return "AbortController" in f && m(f.AbortController);
30
+ return "AbortController" in f && y(f.AbortController);
31
31
  }
32
32
  function q() {
33
- return "URLSearchParams" in f && m(f.URLSearchParams);
33
+ return "URLSearchParams" in f && y(f.URLSearchParams);
34
34
  }
35
35
  function H(e) {
36
36
  return new Promise((t) => setTimeout(t, Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, e))));
@@ -39,8 +39,8 @@ function H(e) {
39
39
  function N(e) {
40
40
  const t = e || "CustomError";
41
41
  return class extends Error {
42
- constructor(n) {
43
- super(n), Object.defineProperty(this, "name", {
42
+ constructor(r) {
43
+ super(r), Object.defineProperty(this, "name", {
44
44
  value: t,
45
45
  enumerable: !1,
46
46
  configurable: !0
@@ -52,33 +52,33 @@ const I = /^(?:https?:)?\/\/.+$/i, G = /^https?:\/\/.+$/i, K = /^\{[\d\D]*\}$/,
52
52
  function $(e, t = !1) {
53
53
  return t ? I.test(e) : G.test(e);
54
54
  }
55
- function F(e) {
55
+ function A(e) {
56
56
  return e == null;
57
57
  }
58
- function A(e, ...t) {
58
+ function S(e, ...t) {
59
59
  if (!e || typeof e != "object") return !1;
60
- const n = Object.getPrototypeOf(e);
61
- return n !== Object.prototype && n !== null ? !1 : t.every((s) => s in e);
60
+ const r = Object.getPrototypeOf(e);
61
+ return r !== Object.prototype && r !== null ? !1 : t.every((s) => s in e);
62
62
  }
63
- function S(e) {
63
+ function L(e) {
64
64
  return K.test(e) || _.test(e);
65
65
  }
66
66
  function E(e, t) {
67
67
  try {
68
- const n = JSON.parse(e);
69
- return t ? t(n) ? n : null : n;
68
+ const r = JSON.parse(e);
69
+ return t ? t(r) ? r : null : r;
70
70
  } catch {
71
71
  return null;
72
72
  }
73
73
  }
74
- async function Te(e) {
74
+ async function ke(e) {
75
75
  return await new Promise(function(t) {
76
- const n = document.getElementsByTagName("head")[0], s = document.createElement("script");
76
+ const r = document.getElementsByTagName("head")[0], s = document.createElement("script");
77
77
  s.setAttribute("type", "text/javascript"), s.setAttribute("charset", "utf-8"), s.onload = function() {
78
- n.removeChild(s), t(!0);
78
+ r.removeChild(s), t(!0);
79
79
  }, s.onerror = function() {
80
- n.removeChild(s), t(!1);
81
- }, s.setAttribute("src", e), n.appendChild(s);
80
+ r.removeChild(s), t(!1);
81
+ }, s.setAttribute("src", e), r.appendChild(s);
82
82
  });
83
83
  }
84
84
  function J(e, t = "数据未能正确识别") {
@@ -98,31 +98,31 @@ function x(e) {
98
98
  return $(e, !0) ? e.startsWith("http") ? e : ("location" in t ? location.protocol : "https:") + e : ("location" in t ? location.origin : "http://127.0.0.1") + "/" + e.replace(/^\/+/, "");
99
99
  }
100
100
  function W(e, t) {
101
- const n = {};
101
+ const r = {};
102
102
  return (e.match(/([^=&#?]+)=[^&#]*/g) || []).forEach(function(s) {
103
- const r = s.split("="), o = r[0], a = decodeURIComponent(r[1] || "");
104
- n[o] !== void 0 ? n[o] += "," + a : n[o] = a;
105
- }), t !== !0 ? n[t] || "" : n;
103
+ const n = s.split("="), o = n[0], a = decodeURIComponent(n[1] || "");
104
+ r[o] !== void 0 ? r[o] += "," + a : r[o] = a;
105
+ }), t !== !0 ? r[t] || "" : r;
106
106
  }
107
107
  function X(e, t) {
108
108
  if (t) {
109
109
  if (t === !0)
110
110
  return e.replace(/\?[^#]*/, "");
111
111
  } else return e;
112
- const n = e.split("#"), s = n[0].split("?"), r = s[0], o = s.length > 1 ? s[1] : "", a = n.length > 1 ? "#" + n[1] : "", i = typeof t == "string" ? [t] : Array.isArray(t) ? t : [];
113
- return !i.length || !o ? n[0] + a : (i.map((c) => c.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (r + "?" + o.replace(new RegExp("(?:^|&)(?:" + i.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + a);
112
+ const r = e.split("#"), s = r[0].split("?"), n = s[0], o = s.length > 1 ? s[1] : "", a = r.length > 1 ? "#" + r[1] : "", u = typeof t == "string" ? [t] : Array.isArray(t) ? t : [];
113
+ return !u.length || !o ? r[0] + a : (u.map((c) => c.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (n + "?" + o.replace(new RegExp("(?:^|&)(?:" + u.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + a);
114
114
  }
115
- function z(e, t, n = !1) {
115
+ function z(e, t, r = !1) {
116
116
  const s = typeof t == "string" ? t : Object.keys(t).map((a) => `${a}=${encodeURIComponent(t[a])}`).join("&");
117
117
  if (!s)
118
118
  return e;
119
- const r = e.split("#");
120
- n && (r[0] = X(
121
- r[0],
119
+ const n = e.split("#");
120
+ r && (n[0] = X(
121
+ n[0],
122
122
  (s.match(/([^=&#?]+)=[^&#]+/g) || []).map((a) => a.replace(/=.+$/, ""))
123
123
  ));
124
- const o = r[0].indexOf("?") + 1 ? "&" : "?";
125
- return (r[0] + o + s + (r.length > 1 ? "#" + r[1] : "")).replace(/\?&/, "?");
124
+ const o = n[0].indexOf("?") + 1 ? "&" : "?";
125
+ return (n[0] + o + s + (n.length > 1 ? "#" + n[1] : "")).replace(/\?&/, "?");
126
126
  }
127
127
  function Q(e) {
128
128
  const t = e.match(/(?:\?|&)([^=]+)(?:&|$)/g);
@@ -134,8 +134,8 @@ class Y {
134
134
  timer = null;
135
135
  // 定时循环以清理缓存
136
136
  loopCheck() {
137
- if (Object.keys(this.cache).forEach((n) => {
138
- this.cache[n].ttl < Date.now() && delete this.cache[n];
137
+ if (Object.keys(this.cache).forEach((r) => {
138
+ this.cache[r].ttl < Date.now() && delete this.cache[r];
139
139
  }), Object.keys(this.cache).length === 0) {
140
140
  this.timer = null;
141
141
  return;
@@ -145,34 +145,34 @@ class Y {
145
145
  constructor(t = 500) {
146
146
  this.cache = {}, this.ttl = Math.max(t, 0), this.loopCheck = this.loopCheck.bind(this);
147
147
  }
148
- getKey(t, n, s, r) {
149
- if (t.toLowerCase() !== "get" && !r)
148
+ getKey(t, r, s, n) {
149
+ if (t.toLowerCase() !== "get" && !n)
150
150
  return "";
151
- const o = t.toLowerCase(), a = n.replace(/#.+/, ""), i = a.replace(/\?.+/g, "");
152
- if (r)
151
+ const o = t.toLowerCase(), a = r.replace(/#.+/, ""), u = a.replace(/\?.+/g, "");
152
+ if (n)
153
153
  try {
154
- const h = r() || "";
155
- return h ? `${i}_${o}_${h}` : "";
154
+ const h = n() || "";
155
+ return h ? `${u}_${o}_${h}` : "";
156
156
  } catch (h) {
157
- return console.warn("[RequestCache] cacheResolve error", n, s, h), "";
157
+ return console.warn("[RequestCache] cacheResolve error", r, s, h), "";
158
158
  }
159
- const c = Object.assign(W(a, !0), s), l = Q(a), u = Object.keys(c).sort().map((h) => `${h}#${c[h]}`);
160
- return `${i}_${o}_${u.join(",")}_${l.join(",")}`;
159
+ const c = Object.assign(W(a, !0), s), l = Q(a), i = Object.keys(c).sort().map((h) => `${h}#${c[h]}`);
160
+ return `${u}_${o}_${i.join(",")}_${l.join(",")}`;
161
161
  }
162
162
  updateTTL(t) {
163
163
  this.ttl = Math.max(t, 0);
164
164
  }
165
- get(t, n) {
166
- if (Math.max(n ?? this.ttl, 0) === 0)
165
+ get(t, r) {
166
+ if (Math.max(r ?? this.ttl, 0) === 0)
167
167
  return null;
168
- const r = this.cache[t];
169
- return r ? r.ttl < Date.now() ? (delete this.cache[t], null) : r.res : null;
170
- }
171
- set(t, n, s) {
172
- const r = Math.max(s ?? this.ttl, 0);
173
- r !== 0 && (this.cache[t] = {
174
- ttl: Date.now() + r,
175
- res: n
168
+ const n = this.cache[t];
169
+ return n ? n.ttl < Date.now() ? (delete this.cache[t], null) : n.res : null;
170
+ }
171
+ set(t, r, s) {
172
+ const n = Math.max(s ?? this.ttl, 0);
173
+ n !== 0 && (this.cache[t] = {
174
+ ttl: Date.now() + n,
175
+ res: r
176
176
  }, this.timer === null && (this.timer = setTimeout(this.loopCheck, 5e3)));
177
177
  }
178
178
  del(t) {
@@ -216,11 +216,11 @@ class Z {
216
216
  return V(t, this.config.baseURL);
217
217
  }
218
218
  /** 提示消息 */
219
- showMessage(t, n, s, r) {
220
- this.config.messageHandler && n && this.config.messageHandler(t, n, s, r);
219
+ showMessage(t, r, s, n) {
220
+ this.config.messageHandler && r && this.config.messageHandler(t, r, s, n);
221
221
  }
222
222
  }
223
- const y = {
223
+ const g = {
224
224
  /** 响应数据校验失败 */
225
225
  UnexpectResponse: "UnexpectResponse",
226
226
  /** 请求被取消 */
@@ -234,53 +234,53 @@ const y = {
234
234
  /** 请求方法不被支持,在微信小程序环境下有效 */
235
235
  NotSupport: "NotSupport"
236
236
  };
237
- function ee(e, t, n, s) {
238
- if (t.ok && !F(t.data) && s) {
239
- const { guard: r, message: o } = J(s, n.get("defaultTypeGuardMessage"));
240
- return r(t.data) || (t.code = y.UnexpectResponse, n.showMessage(!0, `${e} ${o}`, t.code, t.status), console.error(t.code, e, t.data), t.data = null, t.message = o), t;
237
+ function ee(e, t, r, s) {
238
+ if (t.ok && !A(t.data) && s) {
239
+ const { guard: n, message: o } = J(s, r.get("defaultTypeGuardMessage"));
240
+ return n(t.data) || (t.code = g.UnexpectResponse, r.showMessage(!0, `${e} ${o}`, t.code, t.status), console.error(t.code, e, t.data), t.data = null, t.message = o), t;
241
241
  }
242
242
  return t;
243
243
  }
244
- class ke {
244
+ class Te {
245
245
  agent;
246
246
  config;
247
247
  cache;
248
- constructor(t, n) {
249
- this.config = new Z(n), this.agent = t, this.cache = new Y(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);
248
+ constructor(t, r) {
249
+ this.config = new Z(r), this.agent = t, this.cache = new Y(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);
250
250
  }
251
251
  /** 发送网络请求,含有缓存控制逻辑,不含有 guard 逻辑 */
252
- async send(t, n) {
253
- const s = this.cache.getKey(n?.method || "GET", t, n?.params, n?.cacheResolve);
252
+ async send(t, r) {
253
+ const s = this.cache.getKey(r?.method || "GET", t, r?.params, r?.cacheResolve);
254
254
  if (s) {
255
- const r = this.cache.get(s, n?.cacheTTL);
256
- if (r)
257
- return await r;
255
+ const n = this.cache.get(s, r?.cacheTTL);
256
+ if (n)
257
+ return await n;
258
258
  }
259
259
  try {
260
- const r = this.agent(t, this.config, n);
261
- s && this.cache.set(s, r, n?.cacheTTL);
262
- const o = await r;
260
+ const n = this.agent(t, this.config, r);
261
+ s && this.cache.set(s, n, r?.cacheTTL);
262
+ const o = await n;
263
263
  return (!o.ok || o.status < 0) && this.cache.del(s), o;
264
- } catch (r) {
265
- return console.error("RequestError", r), {
264
+ } catch (n) {
265
+ return console.error("RequestError", n), {
266
266
  ok: !1,
267
267
  status: -1,
268
- code: y.Unknown,
269
- message: r instanceof Error ? r.message : String(r),
268
+ code: g.Unknown,
269
+ message: n instanceof Error ? n.message : String(n),
270
270
  headers: {},
271
271
  data: null
272
272
  };
273
273
  }
274
274
  }
275
275
  async request(t) {
276
- const n = await this.send(t.url, t.options);
277
- return ee(t.url, n, this.config, t.guard ?? null);
276
+ const r = await this.send(t.url, t.options);
277
+ return ee(t.url, r, this.config, t.guard ?? null);
278
278
  }
279
279
  /** 整理合并通用参数 */
280
- gen(t, n, s, r, o) {
280
+ gen(t, r, s, n, o) {
281
281
  const a = Object.assign(
282
- o ? { ...o, method: n } : { method: n },
283
- r ? { body: r } : null,
282
+ o ? { ...o, method: r } : { method: r },
283
+ n ? { body: n } : null,
284
284
  s ? { params: s } : null
285
285
  );
286
286
  return typeof t == "object" ? (a.params = t.params, { options: a, url: t.url }) : { options: a, url: t };
@@ -300,60 +300,60 @@ class ke {
300
300
  /**
301
301
  * 发送一个 HEAD 请求,并且不处理响应 body
302
302
  */
303
- async head(t, n, s) {
304
- return this.request(this.gen(t, "HEAD", n, null, s));
303
+ async head(t, r, s) {
304
+ return this.request(this.gen(t, "HEAD", r, null, s));
305
305
  }
306
- async get(t, n, s, r) {
307
- const o = this.gen(t, "GET", n, null, r);
306
+ async get(t, r, s, n) {
307
+ const o = this.gen(t, "GET", r, null, n);
308
308
  return s ? this.request({ ...o, guard: s }) : this.request(o);
309
309
  }
310
- async post(t, n, s, r) {
311
- const o = this.gen(t, "POST", null, n || {}, r);
310
+ async post(t, r, s, n) {
311
+ const o = this.gen(t, "POST", null, r || {}, n);
312
312
  return s ? this.request({ ...o, guard: s }) : this.request(o);
313
313
  }
314
- async del(t, n, s, r) {
315
- const o = this.gen(t, "DELETE", n, null, r);
314
+ async del(t, r, s, n) {
315
+ const o = this.gen(t, "DELETE", r, null, n);
316
316
  return s ? this.request({ ...o, guard: s }) : this.request(o);
317
317
  }
318
- async put(t, n, s, r) {
319
- const o = this.gen(t, "PUT", null, n || {}, r);
318
+ async put(t, r, s, n) {
319
+ const o = this.gen(t, "PUT", null, r || {}, n);
320
320
  return s ? this.request({ ...o, guard: s }) : this.request(o);
321
321
  }
322
- async patch(t, n, s, r) {
323
- const o = this.gen(t, "PATCH", null, n || {}, r);
322
+ async patch(t, r, s, n) {
323
+ const o = this.gen(t, "PATCH", null, r || {}, n);
324
324
  return s ? this.request({ ...o, guard: s }) : this.request(o);
325
325
  }
326
326
  }
327
327
  function te(e) {
328
328
  const t = {};
329
- for (const [n, s] of e)
330
- n && typeof n == "string" && (t[n] = s || "");
329
+ for (const [r, s] of e)
330
+ r && typeof r == "string" && (t[r] = s || "");
331
331
  return t;
332
332
  }
333
333
  function se(e) {
334
334
  const t = {};
335
- return e && Object.keys(e).forEach((n) => {
336
- const s = e[n], r = s == null ? "" : typeof s == "boolean" || typeof s == "number" ? String(s) : s;
337
- r && (t[n] = r);
335
+ return e && Object.keys(e).forEach((r) => {
336
+ const s = e[r], n = s == null ? "" : typeof s == "boolean" || typeof s == "number" ? String(s) : s;
337
+ n && (t[r] = n);
338
338
  }), t;
339
339
  }
340
- function L(e) {
341
- return F(e) ? "" : typeof e == "string" ? e : e instanceof ArrayBuffer && O() ? new TextDecoder().decode(e) : JSON.stringify(e);
340
+ function B(e) {
341
+ return A(e) ? "" : typeof e == "string" ? e : e instanceof ArrayBuffer && M() ? new TextDecoder().decode(e) : JSON.stringify(e);
342
342
  }
343
- function ne(e) {
344
- return e instanceof Error ? e : new Error(L(e));
343
+ function re(e) {
344
+ return e instanceof Error ? e : new Error(B(e));
345
345
  }
346
346
  async function Re(e) {
347
- if (O())
347
+ if (M())
348
348
  return new TextEncoder().encode(e).buffer;
349
349
  if (R())
350
350
  return await new Blob([e]).arrayBuffer();
351
351
  throw new Error("cannot convert string to ArrayBuffer");
352
352
  }
353
- function re(e, t) {
354
- if ("URL" in C()) {
353
+ function ne(e, t) {
354
+ if ("URL" in C() && !O()) {
355
355
  const s = new URL(e);
356
- return Object.keys(t).forEach((r) => s.searchParams.set(r, t[r])), s.toString();
356
+ return Object.keys(t).forEach((n) => s.searchParams.set(n, t[n])), s.toString();
357
357
  }
358
358
  return z(e, t);
359
359
  }
@@ -363,27 +363,27 @@ function oe(e) {
363
363
  } : e === "network" ? ae : ce;
364
364
  }
365
365
  function ae({ error: e }) {
366
- return e === y.NetworkError;
366
+ return e === g.NetworkError;
367
367
  }
368
- function ce({ status: e, headers: t, error: n }) {
369
- return n === y.NetworkError ? !0 : t?.server === "TencentEdgeOne" ? e === 522 || e === 552 : !1;
368
+ function ce({ status: e, headers: t, error: r }) {
369
+ return r === g.NetworkError ? !0 : t?.server === "TencentEdgeOne" ? e === 522 || e === 552 : !1;
370
370
  }
371
- async function $e(e, t, n) {
372
- const s = { ...n, method: n?.method || "GET" }, r = M() ? s.body instanceof FormData : !1, o = r && s.method !== "POST" && s.method !== "PUT" ? "POST" : s.method, a = o === "GET" || o === "HEAD" || o === "DELETE";
371
+ async function $e(e, t, r) {
372
+ const s = { ...r, method: r?.method || "GET" }, n = F() ? s.body instanceof FormData : !1, o = n && s.method !== "POST" && s.method !== "PUT" ? "POST" : s.method, a = o === "GET" || o === "HEAD" || o === "DELETE";
373
373
  a && s.body !== void 0 && (console.warn("request body is invalid with method get, head, delete"), delete s.body);
374
- const i = r || a ? { ...s.headers } : {
374
+ const u = n || a ? { ...s.headers } : {
375
375
  "Content-Type": R() && s.body instanceof Blob ? s.body.type || "application/octet-stream" : "application/json;charset=utf-8",
376
376
  ...s.headers
377
- }, c = t.getFullUrl(e), l = se(s.params), u = ie(s.body), h = s.timeout || t.get("timeout"), p = await (async function() {
378
- const g = t.get("requestTransformer");
379
- if (g)
380
- return await g({ headers: i, params: l, method: o, url: c, body: u });
381
- })(), d = re(typeof p == "string" && p ? p : c, l);
382
- return t.get("logHandler")?.({ type: "ready", url: d, method: o, headers: i, timeout: h, body: u }), {
383
- url: d,
377
+ }, c = t.getFullUrl(e), l = se(s.params), i = ie(s.body), h = s.timeout || t.get("timeout"), d = await (async function() {
378
+ const p = t.get("requestTransformer");
379
+ if (p)
380
+ return await p({ headers: u, params: l, method: o, url: c, body: i });
381
+ })(), m = ne(typeof d == "string" && d ? d : c, l);
382
+ return t.get("logHandler")?.({ type: "ready", url: m, method: o, headers: u, timeout: h, body: i }), {
383
+ url: m,
384
384
  method: o,
385
- body: u,
386
- headers: i,
385
+ body: i,
386
+ headers: u,
387
387
  timeout: h,
388
388
  abort: s.abort,
389
389
  asBuffer: !!s.asBuffer,
@@ -392,69 +392,83 @@ async function $e(e, t, n) {
392
392
  }
393
393
  function ie(e) {
394
394
  if (e)
395
- return typeof e == "string" || q() && e instanceof URLSearchParams || e instanceof ArrayBuffer || R() && e instanceof Blob || M() && e instanceof FormData ? e : JSON.stringify(e);
395
+ return typeof e == "string" || q() && e instanceof URLSearchParams || e instanceof ArrayBuffer || R() && e instanceof Blob || F() && e instanceof FormData ? e : JSON.stringify(e);
396
396
  }
397
- const B = "data", w = "message";
398
- function ue(e, t, n) {
399
- return D(e.status) ? fe(n?.ok || t.ok, e) : he(n?.failed || t.failed, e);
397
+ const D = "data", w = "message";
398
+ function ue(e, t, r) {
399
+ return P(e.status) ? fe(r?.ok || t.ok, e) : he(r?.failed || t.failed, e);
400
400
  }
401
- function fe(e, { statusText: t, body: n }) {
401
+ function fe(e, { statusText: t, body: r }) {
402
402
  const s = {
403
403
  ok: !0,
404
404
  code: t,
405
405
  message: "",
406
406
  data: null
407
407
  };
408
- if (!n)
408
+ if (!r)
409
409
  return s;
410
- if (typeof n != "string")
411
- return s.data = n, s;
410
+ if (typeof r != "string")
411
+ return s.data = r, s;
412
412
  if (e.resolve === "body")
413
- return s.data = S(n) ? T(E(n), e.converter) : n, s;
414
- const r = E(n);
415
- if (!r)
413
+ return s.data = L(r) ? k(E(r), e.converter) : r, s;
414
+ const n = E(r);
415
+ if (!n)
416
416
  return s.ok = !1, s.code = "ResponseFormatError", s.message = "响应内容无法解析为 json", s;
417
- const o = T(r, e.converter);
418
- if (!o || !A(o))
417
+ const o = k(n, e.converter);
418
+ if (!o || !S(o))
419
419
  return s.ok = !1, s.code = "ResponseFormatError", s.message = "响应内容无法格式化为 object", s;
420
420
  const a = e.statusField;
421
421
  if (a && !(a in o))
422
422
  return s.ok = !1, s.code = "ResponseFieldMissing", s.message = `响应内容找不到状态字段 ${a}`, s;
423
- const i = e.statusOKValue || "", c = e.dataField || B, l = e.messageField || w, u = a ? String(o[a] ?? "") : "";
424
- return s.ok = a ? u === i : !0, s.code = u || s.code, s.data = c === !0 ? o : c in o ? o[c] : null, s.message = k(o, l), e.ignoreMessage && s.message && (Array.isArray(e.ignoreMessage) ? e.ignoreMessage.includes(s.message) : e.ignoreMessage === s.message) && (s.message = ""), s;
423
+ const u = e.statusOKValue || "", c = e.dataField || D, l = e.messageField || w, i = a ? String(o[a] ?? "") : "";
424
+ return s.ok = a ? i === u : !0, s.code = i || s.code, s.data = c === !0 ? o : c in o ? o[c] : null, s.message = T(o, l), e.ignoreMessage && s.message && (Array.isArray(e.ignoreMessage) ? e.ignoreMessage.includes(s.message) : e.ignoreMessage === s.message) && (s.message = ""), s;
425
425
  }
426
- function he(e, { statusText: t, body: n, error: s }) {
427
- const r = typeof n == "string" ? n : "", o = {
426
+ function he(e, { statusText: t, body: r, error: s }) {
427
+ const n = typeof r == "string" ? r : "", o = {
428
428
  ok: !1,
429
429
  code: s || t,
430
- message: r,
430
+ message: n,
431
431
  data: null
432
432
  };
433
+ switch (s) {
434
+ case g.NetworkError:
435
+ o.message = "网络错误";
436
+ break;
437
+ case g.Timeout:
438
+ o.message = "请求超时";
439
+ break;
440
+ case g.Aborted:
441
+ o.message = "请求被取消";
442
+ break;
443
+ case g.Unknown:
444
+ o.message = "发生未知错误";
445
+ break;
446
+ }
433
447
  switch (e.resolve) {
434
448
  case "body":
435
- o.message = j(r) || r;
449
+ o.message = j(n) || n;
436
450
  break;
437
451
  case "json":
438
- const { code: a, message: i } = le(r, e.converter, e.statusField, e.messageField);
439
- o.code = a || s || t, o.message = j(r) || i;
452
+ const { code: a, message: u } = le(n, e.converter, e.statusField, e.messageField);
453
+ o.code = a || s || t, o.message = j(n) || u;
440
454
  break;
441
455
  }
442
456
  return o;
443
457
  }
444
- function D(e) {
458
+ function P(e) {
445
459
  return e >= 200 && e < 400;
446
460
  }
447
- function T(e, t) {
461
+ function k(e, t) {
448
462
  return t && typeof t == "function" ? t(e) : e;
449
463
  }
450
464
  const xe = function(e) {
451
- const t = [], n = e.failed || { resolve: "json" };
452
- switch (t.push("- 当http状态码 <200 或者 >=400 时"), n.resolve) {
465
+ const t = [], r = e.failed || { resolve: "json" };
466
+ switch (t.push("- 当http状态码 <200 或者 >=400 时"), r.resolve) {
453
467
  case "body":
454
468
  t.push(" 将响应内容格式化为字符串并作为错误消息");
455
469
  break;
456
470
  case "json":
457
- t.push(" 将响应解析为json,并读取 " + (n.messageField || w) + " 作为错误消息");
471
+ t.push(" 将响应解析为json,并读取 " + (r.messageField || w) + " 作为错误消息");
458
472
  break;
459
473
  }
460
474
  const s = e.ok || { resolve: "body" };
@@ -464,7 +478,7 @@ const xe = function(e) {
464
478
  break;
465
479
  case "json":
466
480
  t.push(
467
- " 将响应解析为 json,读取 " + (s.dataField || B) + " 作为响应数据,读取 " + (s.messageField || w) + " 作为提示消息"
481
+ " 将响应解析为 json,读取 " + (s.dataField || D) + " 作为响应数据,读取 " + (s.messageField || w) + " 作为提示消息"
468
482
  ), s.statusField && t.push(
469
483
  " 当 " + s.statusField + " 为 " + (s.statusOKValue || "空值") + " 时是成功提示,否则是错误消息"
470
484
  ), s.ignoreMessage && t.push(" 并忽略以下消息:" + s.ignoreMessage);
@@ -473,39 +487,39 @@ const xe = function(e) {
473
487
  return t.join(`
474
488
  `);
475
489
  };
476
- function le(e, t, n, s = w) {
477
- if (!S(e))
490
+ function le(e, t, r, s = w) {
491
+ if (!L(e))
478
492
  return { message: "" };
479
- const r = T(E(e), t);
480
- return !r || !A(r) ? { message: e } : {
481
- code: n ? k(r, n) : "",
482
- message: k(r, s) || e
493
+ const n = k(E(e), t);
494
+ return !n || !S(n) ? { message: e } : {
495
+ code: r ? T(n, r) : "",
496
+ message: T(n, s) || e
483
497
  };
484
498
  }
485
- function k(e, t) {
486
- const n = Array.isArray(t) ? t : [t];
487
- for (const s of n)
499
+ function T(e, t) {
500
+ const r = Array.isArray(t) ? t : [t];
501
+ for (const s of r)
488
502
  if (s in e)
489
- return L(e[s]);
503
+ return B(e[s]);
490
504
  return "";
491
505
  }
492
506
  const de = [/<title>([^<]+)<\/title>/i, /<message>([^<]+)<\/message>/i];
493
507
  function j(e) {
494
508
  for (const t of de) {
495
- const n = e.match(t);
496
- if (n)
497
- return n[1];
509
+ const r = e.match(t);
510
+ if (r)
511
+ return r[1];
498
512
  }
499
513
  return "";
500
514
  }
501
515
  const ge = /* @__PURE__ */ N("APIError");
502
- function pe(e) {
516
+ function me(e) {
503
517
  const t = {};
504
- for (const r in e.headers)
505
- (r.startsWith("x-") || r.includes("trace") || r.includes("server") || r.includes("status") || /\b(?:id|uuid)\b/.test(r)) && (t[r] = e.headers[r]);
506
- const n = e.url.replace(/^(?:https?:)?\/*/i, "").replace(/\?.+/, ""), s = e.status < 0 ? "unknown" : e.status;
518
+ for (const n in e.headers)
519
+ (n.startsWith("x-") || n.includes("trace") || n.includes("server") || n.includes("status") || /\b(?:id|uuid)\b/.test(n)) && (t[n] = e.headers[n]);
520
+ const r = e.url.replace(/^(?:https?:)?\/*/i, "").replace(/\?.+/, ""), s = e.status < 0 ? "unknown" : e.status;
507
521
  return {
508
- sentryError: new ge(`${n}${s === "unknown" ? "" : ` | ${s}`} | ${e.code}`),
522
+ sentryError: new ge(`${r}${s === "unknown" ? "" : ` | ${s}`} | ${e.code}`),
509
523
  sentryTags: {
510
524
  ...t,
511
525
  status: s,
@@ -526,70 +540,68 @@ async function je(e, t) {
526
540
  return e.body = null, e;
527
541
  try {
528
542
  e.body = t.asBuffer ? await t.buffer() : await t.text();
529
- } catch (n) {
530
- e.body = null, e.error = y.Unknown, e.rawError = ne(n);
543
+ } catch (r) {
544
+ e.body = null, e.error = g.Unknown, e.rawError = re(r);
531
545
  }
532
546
  return e;
533
547
  }
534
- function ve(e, t, n, s) {
535
- const r = e.status, o = e.method, a = te(
536
- Object.entries(e.headers || {}).map(([d, g]) => [d.toLowerCase(), g])
537
- ), { ok: i, code: c, data: l, message: u } = ue(e, n.get("responseRule"), s?.responseRule);
538
- if (!D(r)) {
539
- const d = pe({
548
+ function ve(e, t, r, s) {
549
+ const n = e.status, o = e.method, a = te(
550
+ Object.entries(e.headers || {}).map(([d, m]) => [d.toLowerCase(), m])
551
+ ), { ok: u, code: c, data: l, message: i } = ue(e, r.get("responseRule"), s?.responseRule);
552
+ if (!P(n)) {
553
+ const d = me({
540
554
  url: e.url,
541
555
  method: e.method,
542
- status: r,
556
+ status: n,
543
557
  code: c,
544
- message: u,
558
+ message: i,
545
559
  body: e.body,
546
560
  headers: a,
547
561
  error: e.rawError
548
562
  });
549
- (n.get("errorHandler") || me)({
563
+ (r.get("errorHandler") || pe)({
550
564
  url: t,
551
565
  method: o,
552
- status: r,
566
+ status: n,
553
567
  code: c,
554
- message: u,
568
+ message: i,
555
569
  headers: a,
556
570
  rawError: e.rawError,
557
571
  ...d
558
572
  });
559
573
  }
560
- if (r < 0)
574
+ if (n < 0)
561
575
  return v(
562
- { ok: !1, status: r, code: e.statusText, headers: {}, message: "", data: null },
563
- `${o} ${t} ${e.statusText}`,
576
+ { ok: !1, status: n, code: e.statusText, headers: {}, message: i, data: null },
577
+ `${o} ${t} ${i || e.statusText}`,
564
578
  o,
565
579
  t,
566
- n,
580
+ r,
567
581
  s
568
582
  );
569
- const h = { ok: i, data: l, code: c, message: u, status: r, headers: a };
570
- n.get("responseHandler")?.({ ...h }, o, t);
571
- const p = i ? u : u || e.statusText;
572
- return v(h, p, o, t, n, s);
583
+ const h = { ok: u, data: l, code: c, message: i, status: n, headers: a };
584
+ return r.get("responseHandler")?.({ ...h }, o, t), v(h, u ? i : i || e.statusText, o, t, r, s);
573
585
  }
574
- function v(e, t, n, s, r, o) {
575
- const a = r.get("message"), i = a === !1 || o?.message === !1 ? !1 : o?.message || a;
576
- if (i !== !1) {
577
- const c = typeof i == "function" ? i(e, n, s, t) : t;
578
- c instanceof Error ? r.showMessage(!0, b(c.message), e.code, e.status) : c && typeof c == "object" && "message" in c && typeof c.message == "string" ? r.showMessage(!1, b(c.message), e.code, e.status) : c && r.showMessage(!e.ok, b(String(c)), e.code, e.status);
586
+ function v(e, t, r, s, n, o) {
587
+ const a = n.get("message"), u = a === !1 || o?.message === !1 ? !1 : o?.message || a;
588
+ if (u !== !1) {
589
+ const c = typeof u == "function" ? u(e, r, s, t) : t;
590
+ c instanceof Error ? n.showMessage(!0, b(c.message), e.code, e.status) : c && typeof c == "object" && "message" in c && typeof c.message == "string" ? n.showMessage(!1, b(c.message), e.code, e.status) : c && n.showMessage(!e.ok, b(String(c)), e.code, e.status);
579
591
  }
580
592
  return e;
581
593
  }
582
- function me(e) {
594
+ function pe(e) {
583
595
  const t = {};
584
- for (const n in e)
585
- n.startsWith("sentry") || (t[n] = e[n]);
596
+ for (const r in e)
597
+ r.startsWith("sentry") || (t[r] = e[r]);
586
598
  console.error("RequestError", t);
587
599
  }
588
600
  function b(e) {
589
601
  return e.replace(/<script[\s\S]*?>[\s\S]*?<\/script>/gi, "").replace(/<[^>]+>/g, "").trim();
590
602
  }
591
- async function ye(e, t, n, s, r) {
592
- const o = r || 0, a = Math.max(0, Math.min(10, s?.maxRetry ?? n.get("maxRetry") ?? 0)), i = oe(s?.retryResolve ?? n.get("retryResolve")), c = n.get("logHandler");
603
+ async function ye(e, t, r, s, n) {
604
+ const o = n || 0, a = Math.max(0, Math.min(10, s?.maxRetry ?? r.get("maxRetry") ?? 0)), u = oe(s?.retryResolve ?? r.get("retryResolve")), c = r.get("logHandler");
593
605
  c?.({
594
606
  type: "prepare",
595
607
  url: t,
@@ -600,33 +612,33 @@ async function ye(e, t, n, s, r) {
600
612
  headers: s?.headers,
601
613
  options: s
602
614
  });
603
- const l = Date.now(), u = await e(t, n, s), h = u.status, p = Date.now() - l, d = `[cost ${p}][${h}] ${h < 0 ? u.body : ""}`;
615
+ const l = Date.now(), i = await e(t, r, s), h = i.status, d = Date.now() - l, m = `[cost ${d}][${h}] ${h < 0 ? i.body : ""}`;
604
616
  if (c?.({
605
617
  type: "finished",
606
618
  url: t,
607
- method: u.method,
619
+ method: i.method,
608
620
  retry: o,
609
621
  maxRetry: a,
610
- message: o === 0 ? `finish ${d}` : `retry ${o}/${a} finish ${d}`,
611
- response: u,
612
- headers: u.headers,
613
- cost: p
614
- }), !a || o >= a || i(u, o) !== !0)
615
- return u;
616
- const g = s?.retryInterval ?? n.get("retryInterval") ?? 100;
622
+ message: o === 0 ? `finish ${m}` : `retry ${o}/${a} finish ${m}`,
623
+ response: i,
624
+ headers: i.headers,
625
+ cost: d
626
+ }), !a || o >= a || u(i, o) !== !0)
627
+ return i;
628
+ const p = s?.retryInterval ?? r.get("retryInterval") ?? 100;
617
629
  return await H(
618
630
  Math.max(
619
631
  100,
620
- g === "2EB" ? Math.pow(2, o) * 100 : typeof g == "function" ? g(o + 1, { url: t, status: h, method: u.method }) || 0 : g
632
+ p === "2EB" ? Math.pow(2, o) * 100 : typeof p == "function" ? p(o + 1, { url: t, status: h, method: i.method }) || 0 : p
621
633
  )
622
- ), await ye(e, t, n, s, o + 1);
634
+ ), await ye(e, t, r, s, o + 1);
623
635
  }
624
636
  export {
625
- P as E,
637
+ O as E,
626
638
  Z as G,
627
639
  z as H,
628
- ke as N,
629
- y as R,
640
+ Te as N,
641
+ g as R,
630
642
  we as X,
631
643
  Re as a,
632
644
  se as b,
@@ -638,6 +650,6 @@ export {
638
650
  ve as h,
639
651
  Ee as i,
640
652
  ye as r,
641
- L as t,
642
- Te as v
653
+ B as t,
654
+ ke as v
643
655
  };
package/dist/wx.js CHANGED
@@ -1,5 +1,5 @@
1
- import { h as l, r as p, c as y, E as R, R as u, f as x, a as h, t as c, N as w } from "./retry--akoKQtX.js";
2
- import { g as O } from "./retry--akoKQtX.js";
1
+ import { h as l, r as p, c as y, E as R, R as u, f as x, a as h, t as c, N as w } from "./retry-LYfsjIVg.js";
2
+ import { g as O } from "./retry-LYfsjIVg.js";
3
3
  const m = async function(s, o, n) {
4
4
  return l(await p(q, s, o, n), s, o, n);
5
5
  }, q = async function(s, o, n) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-web/request",
3
- "version": "4.0.2",
3
+ "version": "4.0.4",
4
4
  "description": "request tools for seayoo web",
5
5
  "type": "module",
6
6
  "source": "./src/index.ts",
@@ -51,7 +51,7 @@ export interface BaseRequestOptions {
51
51
  }
52
52
  /** 重试请求的配置参数,暂不支持全局配置 */
53
53
  export interface RetryRequestOptions {
54
- /** 错误时重试的次数,不能超过 10 次,默认不重试 */
54
+ /** 错误时重试的次数,不能超过 10 次,默认重试 1 次 */
55
55
  maxRetry?: number;
56
56
  /**
57
57
  * 重试策略:默认 `default`
@@ -59,10 +59,16 @@ export interface RetryRequestOptions {
59
59
  * `default` 在 `network` 基础之上,当状态码为 Tencent EO 专属错误码 552 / 522 时重试;
60
60
  *
61
61
  * `network` 仅仅网络错误时重试,但忽略 aborted / timeout 状态;
62
+ *
63
+ * `number[]` 可以设置 http status,匹配时重试
64
+ *
65
+ * `function` 自定义函数来返回是否重试
62
66
  */
63
67
  retryResolve?: RetryResolve;
64
68
  /**
65
- * 两次重试的间隔,如果设置时间,则单位 ms,或者设置函数返回等待的时间(单位ms),默认 100,最小 100,函数参数 retryIndex 从 1 开始
69
+ * 两次重试的间隔。
70
+ *
71
+ * 可设置为数字或返回数字的函数,表示等待的时间(单位ms),默认 200,最小 100,函数参数 retryIndex 从 1 开始
66
72
  *
67
73
  * 特殊值 2EB 表示以 2 为底的指数退避,首次延迟为 100ms,第二次为 200ms,第三次为 400ms,第四次为 800ms...
68
74
  *
@@ -151,17 +157,9 @@ export type RequestGlobalConfig = {
151
157
  /** 全局日志打印函数 */
152
158
  logHandler?: null | ((log: RequestLog) => void);
153
159
  } & Pick<BaseRequestOptions, "credentials" | "timeout"> & RetryRequestOptions & OtherRequestOptions;
154
- /**
155
- * 自定义重试检测方法
156
- */
160
+ /** 自定义重试检测方法 */
157
161
  export type RetryResolveFunc = (response: RequestBaseResponse, count: number) => boolean;
158
- /**
159
- * 失败重试策略:
160
- *
161
- * `default` 在 `network` 基础之上,当状态码为 Tencent EO 专属错误码 521 / 522 时重试;
162
- *
163
- * `network` 仅仅网络错误时重试,但忽略 aborted / timeout 状态;
164
- */
162
+ /** 失败重试策略 */
165
163
  export type RetryResolve = "default" | "network" | number[] | RetryResolveFunc;
166
164
  /** 响应内容转化器 */
167
165
  export type ResponseBodyConverter = (body: unknown) => unknown;
@@ -171,7 +169,7 @@ export interface ResponseRule {
171
169
  failed: {
172
170
  /** 解析方式,如果解析方式为 json,则可以进一步指定错误消息字段 */
173
171
  resolve: "json" | "body";
174
- /** 将响应内容进行转化 */
172
+ /** 将响应内容进行转化,此过程优先于内部解析逻辑 */
175
173
  converter?: ResponseBodyConverter;
176
174
  /** 解析错误消息的状态字段,比如 error 或 code,仅在 resolve 为 json 时有效,有值的话会替换 response 的 code */
177
175
  statusField?: string;
@@ -188,7 +186,7 @@ export interface ResponseRule {
188
186
  * - `body` 此时 response body 被格式化为 json 并作为接口返回的数据使用,如果格式化失败,则返回 body 本身的字符串
189
187
  */
190
188
  resolve: "json" | "body";
191
- /** 将响应内容进行转化 */
189
+ /** 将响应内容进行转化,此过程优先于内部解析逻辑 */
192
190
  converter?: ResponseBodyConverter;
193
191
  /** 表示自定义状态的字段名 */
194
192
  statusField?: string;
@@ -233,7 +231,7 @@ export interface ResponseResult<T = unknown> {
233
231
  code: string;
234
232
  /** 从响应体中分析出的提示信息 */
235
233
  message: string;
236
- /** 响应的 headers 信息 */
234
+ /** 响应的 headers 信息,key 均被转为小写字母 */
237
235
  headers: Record<string, string | undefined>;
238
236
  /**
239
237
  * 成功时返回的数据,如果网络错误/服务器没有响应内容(比如 http status 202/204)/类型守卫检查失败则是 null