@seayoo-web/request 4.0.1 → 4.0.3

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-b0Etywu_.js";
2
- import { g as W } from "./retry-b0Etywu_.js";
3
- import { f as S } from "./request.fetch-U2PiTmEn.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-CQEDKWe8.js";
2
+ import { g as W } from "./retry-CQEDKWe8.js";
3
+ import { f as S } from "./request.fetch-D-T4XbBr.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-b0Etywu_.js";
2
- import { g as S } from "./retry-b0Etywu_.js";
3
- import { f as x } from "./request.fetch-U2PiTmEn.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-CQEDKWe8.js";
2
+ import { g as S } from "./retry-CQEDKWe8.js";
3
+ import { f as x } from "./request.fetch-D-T4XbBr.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-b0Etywu_.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-CQEDKWe8.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
- function O(e) {
8
+ function U(e) {
9
9
  return typeof e == "object" && e !== null;
10
10
  }
11
11
  function P() {
12
- return "wx" in f && O(f.wx) && "getSystemInfo" in f.wx && m(f.wx.getSystemInfo);
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 && O(f.window) && !P();
18
+ return "window" in f && U(f.window) && !P();
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 U() {
24
- return "FormData" in f && m(f.FormData);
23
+ function O() {
24
+ return "FormData" in f && y(f.FormData);
25
25
  }
26
- function M() {
27
- return "TextDecoder" in f && m(f.TextDecoder);
26
+ function F() {
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 M(e) {
56
56
  return e == null;
57
57
  }
58
58
  function A(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
63
  function S(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 = "数据未能正确识别") {
@@ -91,38 +91,38 @@ function J(e, t = "数据未能正确识别") {
91
91
  };
92
92
  }
93
93
  function V(e, t = "") {
94
- return !t || $(e, !0) ? j(e) : (j(t) + "/" + e).replace(/\/{2,}/g, "/").replace(/:\//, "://");
94
+ return !t || $(e, !0) ? x(e) : (x(t) + "/" + e).replace(/\/{2,}/g, "/").replace(/:\//, "://");
95
95
  }
96
- function j(e) {
96
+ function x(e) {
97
97
  const t = C();
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 && !M(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
340
  function L(e) {
341
- return F(e) ? "" : typeof e == "string" ? e : e instanceof ArrayBuffer && M() ? new TextDecoder().decode(e) : JSON.stringify(e);
341
+ return M(e) ? "" : typeof e == "string" ? e : e instanceof ArrayBuffer && F() ? new TextDecoder().decode(e) : JSON.stringify(e);
342
342
  }
343
- function ne(e) {
343
+ function re(e) {
344
344
  return e instanceof Error ? e : new Error(L(e));
345
345
  }
346
346
  async function Re(e) {
347
- if (M())
347
+ if (F())
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) {
353
+ function ne(e, t) {
354
354
  if ("URL" in C()) {
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,29 +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 = Object.assign({ method: "GET" }, n), r = U() ? 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 = O() ? 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 = Object.assign(
375
- r || a ? {} : {
376
- "Content-Type": R() && s.body instanceof Blob ? s.body.type || "application/octet-stream" : "application/json;charset=utf-8"
377
- },
378
- s.headers
379
- ), c = t.getFullUrl(e), l = se(s.params), u = ie(s.body), h = s.timeout || t.get("timeout"), p = await (async function() {
380
- const g = t.get("requestTransformer");
381
- if (g)
382
- return await g({ headers: i, params: l, method: o, url: c, body: u });
383
- })(), d = re(typeof p == "string" && p ? p : c, l);
384
- return t.get("logHandler")?.({ type: "ready", url: d, method: o, headers: i, timeout: h, body: u }), {
385
- url: d,
374
+ const u = n || a ? { ...s.headers } : {
375
+ "Content-Type": R() && s.body instanceof Blob ? s.body.type || "application/octet-stream" : "application/json;charset=utf-8",
376
+ ...s.headers
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,
386
384
  method: o,
387
- body: u,
388
- headers: i,
385
+ body: i,
386
+ headers: u,
389
387
  timeout: h,
390
388
  abort: s.abort,
391
389
  asBuffer: !!s.asBuffer,
@@ -394,51 +392,65 @@ async function $e(e, t, n) {
394
392
  }
395
393
  function ie(e) {
396
394
  if (e)
397
- return typeof e == "string" || q() && e instanceof URLSearchParams || e instanceof ArrayBuffer || R() && e instanceof Blob || U() && e instanceof FormData ? e : JSON.stringify(e);
395
+ return typeof e == "string" || q() && e instanceof URLSearchParams || e instanceof ArrayBuffer || R() && e instanceof Blob || O() && e instanceof FormData ? e : JSON.stringify(e);
398
396
  }
399
397
  const B = "data", w = "message";
400
- function ue(e, t, n) {
401
- return D(e.status) ? fe(n?.ok || t.ok, e) : he(n?.failed || t.failed, e);
398
+ function ue(e, t, r) {
399
+ return D(e.status) ? fe(r?.ok || t.ok, e) : he(r?.failed || t.failed, e);
402
400
  }
403
- function fe(e, { statusText: t, body: n }) {
401
+ function fe(e, { statusText: t, body: r }) {
404
402
  const s = {
405
403
  ok: !0,
406
404
  code: t,
407
405
  message: "",
408
406
  data: null
409
407
  };
410
- if (!n)
408
+ if (!r)
411
409
  return s;
412
- if (typeof n != "string")
413
- return s.data = n, s;
410
+ if (typeof r != "string")
411
+ return s.data = r, s;
414
412
  if (e.resolve === "body")
415
- return s.data = S(n) ? T(E(n), e.converter) : n, s;
416
- const r = E(n);
417
- if (!r)
413
+ return s.data = S(r) ? k(E(r), e.converter) : r, s;
414
+ const n = E(r);
415
+ if (!n)
418
416
  return s.ok = !1, s.code = "ResponseFormatError", s.message = "响应内容无法解析为 json", s;
419
- const o = T(r, e.converter);
417
+ const o = k(n, e.converter);
420
418
  if (!o || !A(o))
421
419
  return s.ok = !1, s.code = "ResponseFormatError", s.message = "响应内容无法格式化为 object", s;
422
420
  const a = e.statusField;
423
421
  if (a && !(a in o))
424
422
  return s.ok = !1, s.code = "ResponseFieldMissing", s.message = `响应内容找不到状态字段 ${a}`, s;
425
- const i = e.statusOKValue || "", c = e.dataField || B, l = e.messageField || w, u = a ? String(o[a] ?? "") : "";
426
- 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 || B, 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;
427
425
  }
428
- function he(e, { statusText: t, body: n, error: s }) {
429
- 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 = {
430
428
  ok: !1,
431
429
  code: s || t,
432
- message: r,
430
+ message: n,
433
431
  data: null
434
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
+ }
435
447
  switch (e.resolve) {
436
448
  case "body":
437
- o.message = x(r) || r;
449
+ o.message = j(n) || n;
438
450
  break;
439
451
  case "json":
440
- const { code: a, message: i } = le(r, e.converter, e.statusField, e.messageField);
441
- o.code = a || s || t, o.message = x(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;
442
454
  break;
443
455
  }
444
456
  return o;
@@ -446,17 +458,17 @@ function he(e, { statusText: t, body: n, error: s }) {
446
458
  function D(e) {
447
459
  return e >= 200 && e < 400;
448
460
  }
449
- function T(e, t) {
461
+ function k(e, t) {
450
462
  return t && typeof t == "function" ? t(e) : e;
451
463
  }
452
- const je = function(e) {
453
- const t = [], n = e.failed || { resolve: "json" };
454
- switch (t.push("- 当http状态码 <200 或者 >=400 时"), n.resolve) {
464
+ const xe = function(e) {
465
+ const t = [], r = e.failed || { resolve: "json" };
466
+ switch (t.push("- 当http状态码 <200 或者 >=400 时"), r.resolve) {
455
467
  case "body":
456
468
  t.push(" 将响应内容格式化为字符串并作为错误消息");
457
469
  break;
458
470
  case "json":
459
- t.push(" 将响应解析为json,并读取 " + (n.messageField || w) + " 作为错误消息");
471
+ t.push(" 将响应解析为json,并读取 " + (r.messageField || w) + " 作为错误消息");
460
472
  break;
461
473
  }
462
474
  const s = e.ok || { resolve: "body" };
@@ -475,39 +487,39 @@ const je = function(e) {
475
487
  return t.join(`
476
488
  `);
477
489
  };
478
- function le(e, t, n, s = w) {
490
+ function le(e, t, r, s = w) {
479
491
  if (!S(e))
480
492
  return { message: "" };
481
- const r = T(E(e), t);
482
- return !r || !A(r) ? { message: e } : {
483
- code: n ? k(r, n) : "",
484
- message: k(r, s) || e
493
+ const n = k(E(e), t);
494
+ return !n || !A(n) ? { message: e } : {
495
+ code: r ? T(n, r) : "",
496
+ message: T(n, s) || e
485
497
  };
486
498
  }
487
- function k(e, t) {
488
- const n = Array.isArray(t) ? t : [t];
489
- for (const s of n)
499
+ function T(e, t) {
500
+ const r = Array.isArray(t) ? t : [t];
501
+ for (const s of r)
490
502
  if (s in e)
491
503
  return L(e[s]);
492
504
  return "";
493
505
  }
494
506
  const de = [/<title>([^<]+)<\/title>/i, /<message>([^<]+)<\/message>/i];
495
- function x(e) {
507
+ function j(e) {
496
508
  for (const t of de) {
497
- const n = e.match(t);
498
- if (n)
499
- return n[1];
509
+ const r = e.match(t);
510
+ if (r)
511
+ return r[1];
500
512
  }
501
513
  return "";
502
514
  }
503
515
  const ge = /* @__PURE__ */ N("APIError");
504
- function pe(e) {
516
+ function me(e) {
505
517
  const t = {};
506
- for (const r in e.headers)
507
- (r.startsWith("x-") || r.includes("trace") || r.includes("server") || r.includes("status") || /\b(?:id|uuid)\b/.test(r)) && (t[r] = e.headers[r]);
508
- 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;
509
521
  return {
510
- sentryError: new ge(`${n}${s === "unknown" ? "" : ` | ${s}`} | ${e.code}`),
522
+ sentryError: new ge(`${r}${s === "unknown" ? "" : ` | ${s}`} | ${e.code}`),
511
523
  sentryTags: {
512
524
  ...t,
513
525
  status: s,
@@ -523,75 +535,73 @@ function pe(e) {
523
535
  }
524
536
  };
525
537
  }
526
- async function xe(e, t) {
538
+ async function je(e, t) {
527
539
  if (e.method === "HEAD" || e.status === 204)
528
540
  return e.body = null, e;
529
541
  try {
530
542
  e.body = t.asBuffer ? await t.buffer() : await t.text();
531
- } catch (n) {
532
- 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);
533
545
  }
534
546
  return e;
535
547
  }
536
- function ve(e, t, n, s) {
537
- const r = e.status, o = e.method, a = te(
538
- Object.entries(e.headers || {}).map(([d, g]) => [d.toLowerCase(), g])
539
- ), { ok: i, code: c, data: l, message: u } = ue(e, n.get("responseRule"), s?.responseRule);
540
- if (!D(r)) {
541
- 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 (!D(n)) {
553
+ const d = me({
542
554
  url: e.url,
543
555
  method: e.method,
544
- status: r,
556
+ status: n,
545
557
  code: c,
546
- message: u,
558
+ message: i,
547
559
  body: e.body,
548
560
  headers: a,
549
561
  error: e.rawError
550
562
  });
551
- (n.get("errorHandler") || me)({
563
+ (r.get("errorHandler") || pe)({
552
564
  url: t,
553
565
  method: o,
554
- status: r,
566
+ status: n,
555
567
  code: c,
556
- message: u,
568
+ message: i,
557
569
  headers: a,
558
570
  rawError: e.rawError,
559
571
  ...d
560
572
  });
561
573
  }
562
- if (r < 0)
574
+ if (n < 0)
563
575
  return v(
564
- { ok: !1, status: r, code: e.statusText, headers: {}, message: "", data: null },
565
- `${o} ${t} ${e.statusText}`,
576
+ { ok: !1, status: n, code: e.statusText, headers: {}, message: i, data: null },
577
+ `${o} ${t} ${i || e.statusText}`,
566
578
  o,
567
579
  t,
568
- n,
580
+ r,
569
581
  s
570
582
  );
571
- const h = { ok: i, data: l, code: c, message: u, status: r, headers: a };
572
- n.get("responseHandler")?.({ ...h }, o, t);
573
- const p = i ? u : u || e.statusText;
574
- 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);
575
585
  }
576
- function v(e, t, n, s, r, o) {
577
- const a = r.get("message"), i = a === !1 || o?.message === !1 ? !1 : o?.message || a;
578
- if (i !== !1) {
579
- const c = typeof i == "function" ? i(e, n, s, t) : t;
580
- 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);
581
591
  }
582
592
  return e;
583
593
  }
584
- function me(e) {
594
+ function pe(e) {
585
595
  const t = {};
586
- for (const n in e)
587
- n.startsWith("sentry") || (t[n] = e[n]);
596
+ for (const r in e)
597
+ r.startsWith("sentry") || (t[r] = e[r]);
588
598
  console.error("RequestError", t);
589
599
  }
590
600
  function b(e) {
591
601
  return e.replace(/<script[\s\S]*?>[\s\S]*?<\/script>/gi, "").replace(/<[^>]+>/g, "").trim();
592
602
  }
593
- async function ye(e, t, n, s, r) {
594
- 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");
595
605
  c?.({
596
606
  type: "prepare",
597
607
  url: t,
@@ -602,44 +612,44 @@ async function ye(e, t, n, s, r) {
602
612
  headers: s?.headers,
603
613
  options: s
604
614
  });
605
- 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 : ""}`;
606
616
  if (c?.({
607
617
  type: "finished",
608
618
  url: t,
609
- method: u.method,
619
+ method: i.method,
610
620
  retry: o,
611
621
  maxRetry: a,
612
- message: o === 0 ? `finish ${d}` : `retry ${o}/${a} finish ${d}`,
613
- response: u,
614
- headers: u.headers,
615
- cost: p
616
- }), !a || o >= a || i(u, o) !== !0)
617
- return u;
618
- 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;
619
629
  return await H(
620
630
  Math.max(
621
631
  100,
622
- 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
623
633
  )
624
- ), await ye(e, t, n, s, o + 1);
634
+ ), await ye(e, t, r, s, o + 1);
625
635
  }
626
636
  export {
627
637
  P as E,
628
638
  Z as G,
629
639
  z as H,
630
- ke as N,
631
- y as R,
640
+ Te as N,
641
+ g as R,
632
642
  we as X,
633
643
  Re as a,
634
644
  se as b,
635
645
  $e as c,
636
646
  be as d,
637
647
  te as e,
638
- xe as f,
639
- je as g,
648
+ je as f,
649
+ xe as g,
640
650
  ve as h,
641
651
  Ee as i,
642
652
  ye as r,
643
653
  L as t,
644
- Te as v
654
+ ke as v
645
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-b0Etywu_.js";
2
- import { g as O } from "./retry-b0Etywu_.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-CQEDKWe8.js";
2
+ import { g as O } from "./retry-CQEDKWe8.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.1",
3
+ "version": "4.0.3",
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