@seayoo-web/request 3.1.5 → 3.3.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.
- package/README.md +21 -12
- package/dist/index.cjs +2 -2
- package/dist/index.js +71 -71
- package/dist/node.cjs +1 -1
- package/dist/node.js +13 -13
- package/dist/request.fetch-BqSnA_jT.cjs +1 -0
- package/dist/{request.fetch-1poQOlEV.js → request.fetch-CLcd8XUK.js} +16 -16
- package/dist/retry-BltIjZ1L.cjs +3 -0
- package/dist/retry-D8V8lDdS.js +1159 -0
- package/dist/wx.cjs +1 -1
- package/dist/wx.js +2 -2
- package/package.json +2 -2
- package/types/inc/cache.d.ts +3 -2
- package/types/inc/type.d.ts +18 -4
- package/dist/request.fetch-hlpQxV81.cjs +0 -1
- package/dist/retry-8pExkGke.cjs +0 -3
- package/dist/retry-_AqXIa5P.js +0 -1135
package/README.md
CHANGED
|
@@ -15,12 +15,11 @@
|
|
|
15
15
|
2. 支持重试配置 maxRetry / retryResolve / retryInterval
|
|
16
16
|
3. 支持响应结果处理策略 responseRule 和通用提示配置
|
|
17
17
|
4. 支持类型守卫 typeGuard
|
|
18
|
-
5.
|
|
19
|
-
6.
|
|
20
|
-
7.
|
|
21
|
-
8.
|
|
22
|
-
9.
|
|
23
|
-
10. 提供 jsonp / jsonx 函数,支持带上传进度的 upload 函数
|
|
18
|
+
5. 支持多实例,多端(浏览器,nodejs,微信小程序)
|
|
19
|
+
6. get 请求函数支持并发缓存(默认缓存 500ms)
|
|
20
|
+
7. 函数永不抛错,返回固定解析结构 { ok, data, status, headers, code, message }
|
|
21
|
+
8. 提供格式化良好的 sentry 信息用于错误上报
|
|
22
|
+
9. 提供 jsonp / jsonx 函数,支持带上传进度的 upload 函数
|
|
24
23
|
|
|
25
24
|
## 示例
|
|
26
25
|
|
|
@@ -122,7 +121,7 @@ setConfig({ timeout: 10000 });
|
|
|
122
121
|
|
|
123
122
|
类型:"omit" | "same-origin" | "include"
|
|
124
123
|
|
|
125
|
-
说明:是否携带用户认证信息(cookie, basic http auth 等),默认 "same-
|
|
124
|
+
说明:是否携带用户认证信息(cookie, basic http auth 等),默认 "same-origin",当需要跨域发送 cookie 时可以设置为 include;当需要明确忽略 cookie(比如认证信息已经放入自定义 header 头)时,可以设置为 omit;
|
|
126
125
|
|
|
127
126
|
仅浏览器环境有效;如果运行环境不支持 fetch 则 omit 无效;
|
|
128
127
|
|
|
@@ -136,7 +135,7 @@ setConfig({ timeout: 10000 });
|
|
|
136
135
|
|
|
137
136
|
类型:number
|
|
138
137
|
|
|
139
|
-
|
|
138
|
+
说明:用于控制全局请求的缓冲时长,单位 ms,默认 500,设置为 0 则全局禁用缓冲。默认仅仅对 get 请求做缓冲处理。
|
|
140
139
|
|
|
141
140
|
### defaultTypeGuardMessage
|
|
142
141
|
|
|
@@ -175,9 +174,9 @@ defaultMessage: string
|
|
|
175
174
|
|
|
176
175
|
解析方式,设置为 json(默认),则可以进一步指定错误消息字段;设置为 body 则将整个 body 解析为错误信息;
|
|
177
176
|
|
|
178
|
-
**converter**:
|
|
177
|
+
**converter**: (body: unknown) => unknown
|
|
179
178
|
|
|
180
|
-
|
|
179
|
+
内容转化方式,默认不转化;可以提供函数进行转化,此时尚未进行类型守卫检查。body内容被 parseJSON 后作为参数传入转化函数。
|
|
181
180
|
|
|
182
181
|
**statusField**: string
|
|
183
182
|
|
|
@@ -195,9 +194,9 @@ defaultMessage: string
|
|
|
195
194
|
|
|
196
195
|
解析方式,若设置为 json,则可以进一步指定更多字段;若设置为 body(默认),则把整个响应体作为接口返回的数据使用,如果格式化失败,则返回响应的字符串;
|
|
197
196
|
|
|
198
|
-
**converter**:
|
|
197
|
+
**converter**: (body: unknown) => unknown
|
|
199
198
|
|
|
200
|
-
|
|
199
|
+
内容转化方式,默认不转化;可以提供函数进行转化,此时尚未进行类型守卫检查。body内容被 parseJSON 后作为参数传入转化函数。
|
|
201
200
|
|
|
202
201
|
**statusField**: string
|
|
203
202
|
|
|
@@ -362,6 +361,16 @@ sentryExtra: Record<string, unknown>
|
|
|
362
361
|
|
|
363
362
|
同全局配置,仅本次请求有效,默认跟随全局设置
|
|
364
363
|
|
|
364
|
+
### cacheTTL
|
|
365
|
+
|
|
366
|
+
同全局配置,仅本次请求有效,默认跟随全局设置
|
|
367
|
+
|
|
368
|
+
### cacheResolve
|
|
369
|
+
|
|
370
|
+
类型:() => string | false
|
|
371
|
+
|
|
372
|
+
说明:用于返回请求缓冲的 key,返回 false 或空字符串则不缓冲,返回非空字符串则作为缓冲 key,默认仅仅对 get 请求做缓冲处理
|
|
373
|
+
|
|
365
374
|
## 响应内容
|
|
366
375
|
|
|
367
376
|
所有请求均返回同样的结构(包括网络错误或状态码错误时)其结构字段如下
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./retry-
|
|
2
|
-
`).forEach(n=>{const o=n.trim();if(!o)return;const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./retry-BltIjZ1L.cjs"),m=require("./request.fetch-BqSnA_jT.cjs"),y=async function(t,s,e){return r.handleResponse(await r.retryRequest(R,t,s,e),t,s,e)};async function E(t,s,e,n){const o=e?.body,u=e?.method==="PUT"?"PUT":"POST";if(s instanceof Blob){const i=new r.RequestGlobalConfig(n),f=await R(t,i,{...e,method:u,body:s});return r.handleResponse(f,t,i,e)}const l=new FormData,d={...s};o instanceof Object&&Object.entries(o).forEach(([i,f])=>{f instanceof Blob?d[i]=f:Array.isArray(f)?f.forEach((a,p)=>{l.append(`${i}[${p}]`,String(a))}):l.append(i,String(f))});for(const i in d)l.append(i,d[i]);const b=new r.RequestGlobalConfig(n),w=await R(t,b,{...e,method:u,body:l});return r.handleResponse(w,t,b,e)}const R=async function(t,s,e){const n=await r.convertOptions(t,s,e),o=n.method,u=e?.onUploadProgress,l=r._e(n.url,n.params);return await new Promise(d=>{let b=null,w=!1;const i=function(){w||(a.abort(),w=!0)};function f(){b!==null&&clearTimeout(b),n.abort&&n.abort.removeEventListener("abort",i)}const a=new XMLHttpRequest;let p=!1;if(a.open(o,l,!0),u){let g=1;a.upload.addEventListener("progress",h=>{g=h.total,u({total:h.total,loaded:h.loaded})}),a.addEventListener("load",()=>{u({loaded:g,total:g})})}a.addEventListener("load",()=>{const g=a.status;f(),d({url:l,method:o,status:g,statusText:a.statusText,headers:T(a),body:o==="HEAD"||g===204?"":a.responseText})}),a.addEventListener("error",g=>{f(),d({url:l,method:o,status:a.status||-1,statusText:a.statusText||r.RequestInternalError.NetworkError,body:"",rawError:g})},!0),a.addEventListener("abort",()=>{f(),d({url:l,method:o,status:p?-1:0,statusText:p?r.RequestInternalError.Timeout:r.RequestInternalError.Aborted,body:""})}),Object.entries(n.headers).forEach(([g,h])=>{a.setRequestHeader(g,h)}),n.credentials==="include"&&(a.withCredentials=!0),a.send(n.body||void 0),n.abort&&n.abort.addEventListener("abort",i),n.timeout>0&&(b=setTimeout(function(){p=!0,i()},n.timeout))})};function T(t){const s={};if(!t)return s;const e=t.getAllResponseHeaders();return e&&e!=="null"&&e.replace(/\r/g,"").split(`
|
|
2
|
+
`).forEach(n=>{const o=n.trim();if(!o)return;const u=o.split(":"),l=u[0].trim();l&&(s[l]=(u[1]||"").trim())}),s}async function H(t,s,e={}){const n=window;"callback"in e||(e.callback="jsonxData"+Math.random().toString(16).slice(2));const o=e.callback+"";if(!t)return null;const u=r._e(t,e,!0);return new Promise(l=>{n[o]=function(d){if(o in window&&delete n[o],s(d))return d;console.warn("response type check failed",t,d),l(null)},r.le(u).catch(function(){l(null),delete n[o]})})}async function j(t,s,e={}){const n=window;return"var"in e||(e.var="jsonxData"+Math.random().toString(16).slice(2)),t?await r.le(r._e(t,e,!0)).then(()=>{const o=n[e.var+""];return s(o)?o:(console.warn("response type check failed",t,o),null)}).catch(()=>null):null}const x=async function(t,s,e){return await E(t,s,e,{baseURL:c.getConfig("baseURL"),logHandler:c.getConfig("logHandler"),errorHandler:c.getConfig("errorHandler"),requestTransformer:c.getConfig("requestTransformer"),messageHandler:c.getConfig("messageHandler"),responseHandler:c.getConfig("responseHandler")})};function q(t){if(!r.jt.window)throw new Error("Default Module Only Support In Browser");return r.jt.fetch?new r.NetRequestHandler(m.fetchRequest,t):new r.NetRequestHandler(y,t)}const c=q(),C=c.setConfig,L=c.request,S=c.head,k=c.get,v=c.post,D=c.del,U=c.put,O=c.patch;exports.RequestInternalError=r.RequestInternalError;exports.getResponseRulesDescription=r.getResponseRulesDescription;exports.NetRequest=q;exports.del=D;exports.get=k;exports.head=S;exports.jsonp=H;exports.jsonx=j;exports.patch=O;exports.post=v;exports.put=U;exports.request=L;exports.setGlobalConfig=C;exports.upload=x;
|
package/dist/index.js
CHANGED
|
@@ -1,133 +1,133 @@
|
|
|
1
|
-
import { h as
|
|
2
|
-
import {
|
|
3
|
-
import { f as L } from "./request.fetch-
|
|
4
|
-
const j = async function(t,
|
|
5
|
-
return
|
|
1
|
+
import { h as m, r as x, R as T, c as C, _ as R, a as w, l as q, j as E, N as H } from "./retry-D8V8lDdS.js";
|
|
2
|
+
import { g as J } from "./retry-D8V8lDdS.js";
|
|
3
|
+
import { f as L } from "./request.fetch-CLcd8XUK.js";
|
|
4
|
+
const j = async function(t, o, e) {
|
|
5
|
+
return m(await x(y, t, o, e), t, o, e);
|
|
6
6
|
};
|
|
7
|
-
async function k(t,
|
|
8
|
-
const r = e
|
|
9
|
-
if (
|
|
10
|
-
const
|
|
7
|
+
async function k(t, o, e, n) {
|
|
8
|
+
const r = e?.body, l = e?.method === "PUT" ? "PUT" : "POST";
|
|
9
|
+
if (o instanceof Blob) {
|
|
10
|
+
const i = new T(n), u = await y(t, i, {
|
|
11
11
|
...e,
|
|
12
|
-
method:
|
|
13
|
-
body:
|
|
12
|
+
method: l,
|
|
13
|
+
body: o
|
|
14
14
|
});
|
|
15
|
-
return
|
|
15
|
+
return m(u, t, i, e);
|
|
16
16
|
}
|
|
17
|
-
const
|
|
18
|
-
r instanceof Object && Object.entries(r).forEach(([
|
|
19
|
-
u instanceof Blob ? d[
|
|
20
|
-
|
|
21
|
-
}) :
|
|
17
|
+
const a = new FormData(), d = { ...o };
|
|
18
|
+
r instanceof Object && Object.entries(r).forEach(([i, u]) => {
|
|
19
|
+
u instanceof Blob ? d[i] = u : Array.isArray(u) ? u.forEach((s, g) => {
|
|
20
|
+
a.append(`${i}[${g}]`, String(s));
|
|
21
|
+
}) : a.append(i, String(u));
|
|
22
22
|
});
|
|
23
|
-
for (const
|
|
24
|
-
|
|
25
|
-
const b = new T(n),
|
|
23
|
+
for (const i in d)
|
|
24
|
+
a.append(i, d[i]);
|
|
25
|
+
const b = new T(n), p = await y(t, b, {
|
|
26
26
|
...e,
|
|
27
|
-
method:
|
|
28
|
-
body:
|
|
27
|
+
method: l,
|
|
28
|
+
body: a
|
|
29
29
|
});
|
|
30
|
-
return p
|
|
30
|
+
return m(p, t, b, e);
|
|
31
31
|
}
|
|
32
|
-
const y = async function(t,
|
|
33
|
-
const n = await C(t,
|
|
32
|
+
const y = async function(t, o, e) {
|
|
33
|
+
const n = await C(t, o, e), r = n.method, l = e?.onUploadProgress, a = R(n.url, n.params);
|
|
34
34
|
return await new Promise((d) => {
|
|
35
|
-
let b = null,
|
|
36
|
-
const
|
|
37
|
-
|
|
35
|
+
let b = null, p = !1;
|
|
36
|
+
const i = function() {
|
|
37
|
+
p || (s.abort(), p = !0);
|
|
38
38
|
};
|
|
39
39
|
function u() {
|
|
40
|
-
b !== null && clearTimeout(b), n.abort && n.abort.removeEventListener("abort",
|
|
40
|
+
b !== null && clearTimeout(b), n.abort && n.abort.removeEventListener("abort", i);
|
|
41
41
|
}
|
|
42
|
-
const
|
|
42
|
+
const s = new XMLHttpRequest();
|
|
43
43
|
let g = !1;
|
|
44
|
-
if (
|
|
44
|
+
if (s.open(r, a, !0), l) {
|
|
45
45
|
let f = 1;
|
|
46
|
-
|
|
47
|
-
f = h.total,
|
|
48
|
-
}),
|
|
49
|
-
|
|
46
|
+
s.upload.addEventListener("progress", (h) => {
|
|
47
|
+
f = h.total, l({ total: h.total, loaded: h.loaded });
|
|
48
|
+
}), s.addEventListener("load", () => {
|
|
49
|
+
l({ loaded: f, total: f });
|
|
50
50
|
});
|
|
51
51
|
}
|
|
52
|
-
|
|
53
|
-
const f =
|
|
52
|
+
s.addEventListener("load", () => {
|
|
53
|
+
const f = s.status;
|
|
54
54
|
u(), d({
|
|
55
|
-
url:
|
|
55
|
+
url: a,
|
|
56
56
|
method: r,
|
|
57
57
|
status: f,
|
|
58
|
-
statusText:
|
|
59
|
-
headers: S(
|
|
60
|
-
body: r === "HEAD" || f === 204 ? "" :
|
|
58
|
+
statusText: s.statusText,
|
|
59
|
+
headers: S(s),
|
|
60
|
+
body: r === "HEAD" || f === 204 ? "" : s.responseText
|
|
61
61
|
});
|
|
62
|
-
}),
|
|
62
|
+
}), s.addEventListener(
|
|
63
63
|
"error",
|
|
64
64
|
(f) => {
|
|
65
65
|
u(), d({
|
|
66
|
-
url:
|
|
66
|
+
url: a,
|
|
67
67
|
method: r,
|
|
68
|
-
status:
|
|
69
|
-
statusText:
|
|
68
|
+
status: s.status || -1,
|
|
69
|
+
statusText: s.statusText || w.NetworkError,
|
|
70
70
|
body: "",
|
|
71
71
|
rawError: f
|
|
72
72
|
});
|
|
73
73
|
},
|
|
74
74
|
!0
|
|
75
|
-
),
|
|
75
|
+
), s.addEventListener("abort", () => {
|
|
76
76
|
u(), d({
|
|
77
|
-
url:
|
|
77
|
+
url: a,
|
|
78
78
|
method: r,
|
|
79
79
|
status: g ? -1 : 0,
|
|
80
80
|
// 设置为 0 可以防止自动重试的默认策略
|
|
81
|
-
statusText: g ?
|
|
81
|
+
statusText: g ? w.Timeout : w.Aborted,
|
|
82
82
|
body: ""
|
|
83
83
|
});
|
|
84
84
|
}), Object.entries(n.headers).forEach(([f, h]) => {
|
|
85
|
-
|
|
86
|
-
}), n.credentials === "include" && (
|
|
87
|
-
g = !0,
|
|
85
|
+
s.setRequestHeader(f, h);
|
|
86
|
+
}), n.credentials === "include" && (s.withCredentials = !0), s.send(n.body || void 0), n.abort && n.abort.addEventListener("abort", i), n.timeout > 0 && (b = setTimeout(function() {
|
|
87
|
+
g = !0, i();
|
|
88
88
|
}, n.timeout));
|
|
89
89
|
});
|
|
90
90
|
};
|
|
91
91
|
function S(t) {
|
|
92
|
-
const
|
|
92
|
+
const o = {};
|
|
93
93
|
if (!t)
|
|
94
|
-
return
|
|
94
|
+
return o;
|
|
95
95
|
const e = t.getAllResponseHeaders();
|
|
96
96
|
return e && e !== "null" && e.replace(/\r/g, "").split(`
|
|
97
97
|
`).forEach((n) => {
|
|
98
98
|
const r = n.trim();
|
|
99
99
|
if (!r)
|
|
100
100
|
return;
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
}),
|
|
101
|
+
const l = r.split(":"), a = l[0].trim();
|
|
102
|
+
a && (o[a] = (l[1] || "").trim());
|
|
103
|
+
}), o;
|
|
104
104
|
}
|
|
105
|
-
async function O(t,
|
|
105
|
+
async function O(t, o, e = {}) {
|
|
106
106
|
const n = window;
|
|
107
107
|
"callback" in e || (e.callback = "jsonxData" + Math.random().toString(16).slice(2));
|
|
108
108
|
const r = e.callback + "";
|
|
109
109
|
if (!t)
|
|
110
110
|
return null;
|
|
111
|
-
const
|
|
112
|
-
return new Promise((
|
|
111
|
+
const l = R(t, e, !0);
|
|
112
|
+
return new Promise((a) => {
|
|
113
113
|
n[r] = function(d) {
|
|
114
|
-
if (r in window && delete n[r],
|
|
114
|
+
if (r in window && delete n[r], o(d))
|
|
115
115
|
return d;
|
|
116
|
-
console.warn("response type check failed", t, d),
|
|
117
|
-
}, q(
|
|
118
|
-
|
|
116
|
+
console.warn("response type check failed", t, d), a(null);
|
|
117
|
+
}, q(l).catch(function() {
|
|
118
|
+
a(null), delete n[r];
|
|
119
119
|
});
|
|
120
120
|
});
|
|
121
121
|
}
|
|
122
|
-
async function P(t,
|
|
122
|
+
async function P(t, o, e = {}) {
|
|
123
123
|
const n = window;
|
|
124
124
|
return "var" in e || (e.var = "jsonxData" + Math.random().toString(16).slice(2)), t ? await q(R(t, e, !0)).then(() => {
|
|
125
125
|
const r = n[e.var + ""];
|
|
126
|
-
return
|
|
126
|
+
return o(r) ? r : (console.warn("response type check failed", t, r), null);
|
|
127
127
|
}).catch(() => null) : null;
|
|
128
128
|
}
|
|
129
|
-
const A = async function(t,
|
|
130
|
-
return await k(t,
|
|
129
|
+
const A = async function(t, o, e) {
|
|
130
|
+
return await k(t, o, e, {
|
|
131
131
|
baseURL: c.getConfig("baseURL"),
|
|
132
132
|
logHandler: c.getConfig("logHandler"),
|
|
133
133
|
errorHandler: c.getConfig("errorHandler"),
|
|
@@ -141,17 +141,17 @@ function U(t) {
|
|
|
141
141
|
throw new Error("Default Module Only Support In Browser");
|
|
142
142
|
return E.fetch ? new H(L, t) : new H(j, t);
|
|
143
143
|
}
|
|
144
|
-
const c = U(), M = c.setConfig, N = c.request, B = c.head, X = c.get, F = c.post, G = c.del, I = c.put,
|
|
144
|
+
const c = U(), M = c.setConfig, N = c.request, B = c.head, X = c.get, F = c.post, G = c.del, I = c.put, _ = c.patch;
|
|
145
145
|
export {
|
|
146
146
|
U as NetRequest,
|
|
147
|
-
|
|
147
|
+
w as RequestInternalError,
|
|
148
148
|
G as del,
|
|
149
149
|
X as get,
|
|
150
|
-
|
|
150
|
+
J as getResponseRulesDescription,
|
|
151
151
|
B as head,
|
|
152
152
|
O as jsonp,
|
|
153
153
|
P as jsonx,
|
|
154
|
-
|
|
154
|
+
_ as patch,
|
|
155
155
|
F as post,
|
|
156
156
|
I as put,
|
|
157
157
|
N as request,
|
package/dist/node.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./retry-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./retry-BltIjZ1L.cjs"),y=require("./request.fetch-BqSnA_jT.cjs"),b=require("node:http"),g=require("node:https"),E=async function(r,a,c){return e.handleResponse(await e.retryRequest(w,r,a,c),r,a,c)},w=async function(r,a,c){const t=await e.convertOptions(r,a,c);if(!e.Nt(t.url))return{url:t.url,method:t.method,status:-1,statusText:e.RequestInternalError.URLFormatError,headers:{},body:""};const R=/^https:\/\//i.test(t.url)?g:b,u=new URL(t.url),i=t.params;i instanceof Object&&Object.keys(i).forEach(n=>u.searchParams.set(n,i[n]));const q=t.method==="HEAD";return new Promise(n=>{const d=R.request(u,{headers:t.headers,method:t.method,timeout:t.timeout>0?t.timeout:void 0},function(o){const m=[];o.on("data",h=>m.push(h)),o.on("end",()=>{const h=e.fromEntries(Object.entries(o.headers).map(([f,l])=>[f.toLowerCase(),Array.isArray(l)?l.join(","):l]));n({url:u.toString(),method:t.method,status:o.statusCode||-1,statusText:o.statusMessage||e.RequestInternalError.Unknown,headers:h,body:q||o.statusCode===204?"":Buffer.concat(m).toString("utf-8")})})});d.on("error",o=>{n({url:u.toString(),method:t.method,status:-1,statusText:e.RequestInternalError.NetworkError,body:"",rawError:o})}),d.on("timeout",()=>{n({url:u.toString(),method:t.method,status:-1,statusText:e.RequestInternalError.Timeout,body:""})}),t.body&&d.write(t.body),d.end()})};function p(r){return e.jt.fetch?new e.NetRequestHandler(y.fetchRequest,r):new e.NetRequestHandler(E,r)}const s=p(),N=s.setConfig,j=s.head,C=s.get,I=s.post,S=s.del,T=s.put,O=s.patch;exports.RequestInternalError=e.RequestInternalError;exports.getResponseRulesDescription=e.getResponseRulesDescription;exports.NetRequest=p;exports.del=S;exports.get=C;exports.head=j;exports.patch=O;exports.post=I;exports.put=T;exports.setGlobalConfig=N;
|
package/dist/node.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { h as
|
|
2
|
-
import {
|
|
3
|
-
import { f as x } from "./request.fetch-
|
|
4
|
-
import
|
|
1
|
+
import { h as y, r as q, c as w, b as g, a as d, f as E, N as f, j } from "./retry-D8V8lDdS.js";
|
|
2
|
+
import { g as J } from "./retry-D8V8lDdS.js";
|
|
3
|
+
import { f as x } from "./request.fetch-CLcd8XUK.js";
|
|
4
|
+
import N from "node:http";
|
|
5
5
|
import C from "node:https";
|
|
6
|
-
const
|
|
7
|
-
return
|
|
8
|
-
},
|
|
6
|
+
const T = async function(o, a, u) {
|
|
7
|
+
return y(await q(L, o, a, u), o, a, u);
|
|
8
|
+
}, L = async function(o, a, u) {
|
|
9
9
|
const t = await w(o, a, u);
|
|
10
10
|
if (!g(t.url))
|
|
11
11
|
return {
|
|
@@ -16,7 +16,7 @@ const N = async function(o, a, u) {
|
|
|
16
16
|
headers: {},
|
|
17
17
|
body: ""
|
|
18
18
|
};
|
|
19
|
-
const R = /^https:\/\//i.test(t.url) ? C :
|
|
19
|
+
const R = /^https:\/\//i.test(t.url) ? C : N, n = new URL(t.url), i = t.params;
|
|
20
20
|
i instanceof Object && Object.keys(i).forEach((r) => n.searchParams.set(r, i[r]));
|
|
21
21
|
const l = t.method === "HEAD";
|
|
22
22
|
return new Promise((r) => {
|
|
@@ -31,7 +31,7 @@ const N = async function(o, a, u) {
|
|
|
31
31
|
const p = [];
|
|
32
32
|
e.on("data", (m) => p.push(m)), e.on("end", () => {
|
|
33
33
|
const m = E(
|
|
34
|
-
Object.entries(e.headers).map(([
|
|
34
|
+
Object.entries(e.headers).map(([b, h]) => [b.toLowerCase(), Array.isArray(h) ? h.join(",") : h])
|
|
35
35
|
);
|
|
36
36
|
r({
|
|
37
37
|
url: n.toString(),
|
|
@@ -64,12 +64,12 @@ const N = async function(o, a, u) {
|
|
|
64
64
|
}), t.body && c.write(t.body), c.end();
|
|
65
65
|
});
|
|
66
66
|
};
|
|
67
|
-
function
|
|
68
|
-
return j.fetch ? new f(x, o) : new f(
|
|
67
|
+
function O(o) {
|
|
68
|
+
return j.fetch ? new f(x, o) : new f(T, o);
|
|
69
69
|
}
|
|
70
|
-
const s =
|
|
70
|
+
const s = O(), k = s.setConfig, B = s.head, D = s.get, P = s.post, F = s.del, G = s.put, I = s.patch;
|
|
71
71
|
export {
|
|
72
|
-
|
|
72
|
+
O as NetRequest,
|
|
73
73
|
d as RequestInternalError,
|
|
74
74
|
F as del,
|
|
75
75
|
D as get,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const r=require("./retry-BltIjZ1L.cjs"),E=async function(s,a,i){return r.handleResponse(await r.retryRequest(w,s,a,i),s,a,i)},w=async function(s,a,i){const t=await r.convertOptions(s,a,i),c=new URL(t.url),u=t.params;u instanceof Object&&Object.keys(u).forEach(e=>c.searchParams.set(e,u[e]));const o=r.jt.AbortController?new AbortController:null;function l(){o&&!o.signal.aborted&&o.abort()}t.abort&&t.abort.addEventListener("abort",l);let d=!1;const h=t.timeout>0?setTimeout(function(){d=!0,l()},t.timeout):null,f=t.method==="HEAD";return await fetch(c,{method:t.method,headers:Object.keys(t.headers).length>0?new Headers(t.headers):void 0,body:t.body,credentials:t.credentials,signal:o?.signal,redirect:"follow"}).then(async e=>{const n={url:c.toString(),method:t.method,status:e.status,statusText:e.statusText,headers:r.fromEntries([...e.headers.entries()])},b=f||e.status===204?"":await e.text().catch(m=>m);return b instanceof Error?{...n,body:"",statusText:r.RequestInternalError.Unknown,rawError:b}:{...n,body:b}}).catch(e=>{const n=o?.signal.aborted;return{url:c.toString(),method:t.method,status:n&&!d?0:-1,statusText:d?r.RequestInternalError.Timeout:n?r.RequestInternalError.Aborted:r.RequestInternalError.NetworkError,body:"",rawError:e}}).finally(()=>{h!==null&&clearTimeout(h),t.abort&&t.abort.removeEventListener("abort",l)})};exports.fetchRequest=E;
|
|
@@ -1,47 +1,47 @@
|
|
|
1
|
-
import { h as w, r as y, c as E, j as T, f as R, a as c } from "./retry-
|
|
2
|
-
const x = async function(
|
|
3
|
-
return w(await y(g,
|
|
4
|
-
}, g = async function(
|
|
5
|
-
const t = await E(
|
|
1
|
+
import { h as w, r as y, c as E, j as T, f as R, a as c } from "./retry-D8V8lDdS.js";
|
|
2
|
+
const x = async function(a, s, n) {
|
|
3
|
+
return w(await y(g, a, s, n), a, s, n);
|
|
4
|
+
}, g = async function(a, s, n) {
|
|
5
|
+
const t = await E(a, s, n), i = new URL(t.url), u = t.params;
|
|
6
6
|
u instanceof Object && Object.keys(u).forEach((e) => i.searchParams.set(e, u[e]));
|
|
7
7
|
const r = T.AbortController ? new AbortController() : null;
|
|
8
8
|
function d() {
|
|
9
9
|
r && !r.signal.aborted && r.abort();
|
|
10
10
|
}
|
|
11
11
|
t.abort && t.abort.addEventListener("abort", d);
|
|
12
|
-
let
|
|
13
|
-
const
|
|
14
|
-
|
|
12
|
+
let l = !1;
|
|
13
|
+
const h = t.timeout > 0 ? setTimeout(function() {
|
|
14
|
+
l = !0, d();
|
|
15
15
|
}, t.timeout) : null, f = t.method === "HEAD";
|
|
16
16
|
return await fetch(i, {
|
|
17
17
|
method: t.method,
|
|
18
18
|
headers: Object.keys(t.headers).length > 0 ? new Headers(t.headers) : void 0,
|
|
19
19
|
body: t.body,
|
|
20
20
|
credentials: t.credentials,
|
|
21
|
-
signal: r
|
|
21
|
+
signal: r?.signal,
|
|
22
22
|
redirect: "follow"
|
|
23
23
|
}).then(async (e) => {
|
|
24
|
-
const
|
|
24
|
+
const o = {
|
|
25
25
|
url: i.toString(),
|
|
26
26
|
method: t.method,
|
|
27
27
|
status: e.status,
|
|
28
28
|
statusText: e.statusText,
|
|
29
29
|
headers: R([...e.headers.entries()])
|
|
30
|
-
},
|
|
31
|
-
return
|
|
30
|
+
}, b = f || e.status === 204 ? "" : await e.text().catch((m) => m);
|
|
31
|
+
return b instanceof Error ? { ...o, body: "", statusText: c.Unknown, rawError: b } : { ...o, body: b };
|
|
32
32
|
}).catch((e) => {
|
|
33
|
-
const
|
|
33
|
+
const o = r?.signal.aborted;
|
|
34
34
|
return {
|
|
35
35
|
url: i.toString(),
|
|
36
36
|
method: t.method,
|
|
37
|
-
status:
|
|
37
|
+
status: o && !l ? 0 : -1,
|
|
38
38
|
// 设置为 0 可以防止自动重试的默认策略
|
|
39
|
-
statusText:
|
|
39
|
+
statusText: l ? c.Timeout : o ? c.Aborted : c.NetworkError,
|
|
40
40
|
body: "",
|
|
41
41
|
rawError: e
|
|
42
42
|
};
|
|
43
43
|
}).finally(() => {
|
|
44
|
-
|
|
44
|
+
h !== null && clearTimeout(h), t.abort && t.abort.removeEventListener("abort", d);
|
|
45
45
|
});
|
|
46
46
|
};
|
|
47
47
|
export {
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"use strict";const l=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),K="wx"in l&&R(l.wx)&&"getSystemInfo"in l.wx&&d(l.wx.getSystemInfo),k={wx:K,fetch:"fetch"in l&&d(l.fetch),window:"window"in l&&R(l.window)&&!K,requestAnimationFrame:"requestAnimationFrame"in l&&d(l.requestAnimationFrame),localStorage:"localStorage"in l&&R(l.localStorage)&&"getItem"in l.localStorage&&d(l.localStorage.getItem),sessionStorage:"sessionStorage"in l&&R(l.sessionStorage)&&"getItem"in l.sessionStorage&&d(l.sessionStorage.getItem),File:"File"in l&&d(l.File),Blob:"Blob"in l&&d(l.Blob),Proxy:"Proxy"in l&&d(l.Proxy),Request:"Request"in l&&d(l.Request),FormData:"FormData"in l&&d(l.FormData),TextDecoder:"TextDecoder"in l&&d(l.TextDecoder),ResizeObserver:"ResizeObserver"in l&&d(l.ResizeObserver),AbortController:"AbortController"in l&&d(l.AbortController),URLSearchParams:"URLSearchParams"in l&&d(l.URLSearchParams),EventSource:"EventSource"in l&&d(l.EventSource)};function d(t){return typeof t=="function"}function R(t){return typeof t=="object"&&t!==null}function re(t){return new Promise(e=>setTimeout(e,Math.max(0,t)))}function X(){}function Q(t,e){const s={log:console.log.bind(console),error:console.error.bind(console),warn:console.warn.bind(console)},n=`[${t}]`;return["log","error","warn"].forEach(r=>{const o=console[r];s[r]=(...i)=>{o.apply(console,[n,...i])}}),s}function oe(t){const e=t||"CustomError";return class extends Error{constructor(s){super(s),Object.defineProperty(this,"name",{value:e,enumerable:!1,configurable:!0}),"setPrototypeOf"in Object&&Object.setPrototypeOf(this,new.target.prototype),"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,this.constructor)}}}const ie=/^(?:https?:)?\/\/.+$/i,ae=/^https?:\/\/.+$/i,le=/^\{[\d\D]*\}$/,ue=/^\[[\d\D]*\]$/;function ce(t){return typeof t=="string"}function N(t,e=!1){return e?ie.test(t):ae.test(t)}function he(t){return t==null}function Y(t,...e){return t!==null&&typeof t=="object"&&!(t instanceof Map)&&!(t instanceof Set)&&!(t instanceof WeakMap)&&!(t instanceof WeakSet)&&!Array.isArray(t)&&e.every(s=>s in t)}function y(t,...e){if(!t||typeof t!="object")return!1;const s=Object.getPrototypeOf(t);return s!==Object.prototype&&s!==null?!1:e.every(n=>n in t)}function U(t,e){return Array.isArray(t)&&t.every(s=>e(s))}function x(t){if(typeof t!="number"||Number.isNaN(t)||!Number.isFinite(t))return!1;if(Number.isInteger(t))return Number.isSafeInteger(t);if(t===0)return!0;const e=Math.abs(t);return e>=Number.EPSILON&&e<=Number.MAX_SAFE_INTEGER}function Z(t){return le.test(t)||ue.test(t)}function fe(t,e=20){const s=Math.max(e,10),n=[...t];return n.length<=s?t:n.slice(0,s-3).join("")+"..."}function F(t,e){try{const s=JSON.parse(t);return e?e(s)?s:null:s}catch{return null}}""+Math.random().toString(32).slice(2);Q("LoadUtils");async function de(t){return await new Promise(function(e){const s=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("charset","utf-8"),n.onload=function(){s.removeChild(n),e(!0)},n.onerror=function(){s.removeChild(n),e(!1)},n.setAttribute("src",t),s.appendChild(n)})}function z(t){return Object.getOwnPropertyNames(t).forEach(function(e){delete t[e]}),t}const g=Q("Validator");function j(t){return t?`"${fe(t).replace(/"/g,'\\"')}"`:"empty string"}function S(t){return typeof t=="object"&&t&&"constructor"in t&&typeof t.constructor=="function"?t.constructor.name||"ClassInstance":Object.prototype.toString.call(t).replace(/(?:.+ |]$)/g,"")}function O(t){return typeof t=="bigint"}function a(t){return new Error(`${t?`${t}()`:"method"} is not allowed after locked`)}class M{_ps={};_allow=[];_reject=[];_locked=!1;_opt=!1;_null=!1;pattern(e,s){if(this._locked)throw a("pattern");return this._ps[`#${e||"custom"}`]=s,this}url(e=!1){if(this._locked)throw a("url");return this._ps.url=e?/^(?:https?:)?\/\/.+$/i:/^https?:\/\/.+$/i,this}dataUri(){if(this._locked)throw a("dataUri");return this._ps.dataUri=/^data:[a-z]+\/[a-z]+;base64,[\w+/=]+$/,this}enum(...e){if(this._locked)throw a("enum");const s=e[0];return U(e,ce)?(this._allow=e,z(this._ps)):y(s)&&(this._allow=Object.values(s).map(n=>`${n}`),z(this._ps)),this}disallow(...e){return this._reject.push(...e),this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new M;return e._ps={...this._ps},e._allow=[...this._allow],e._reject=[...this._reject],e._locked=!1,e}validate(e,s=g.warn){if(e===void 0)return this._opt||(s("should be a string, but got undefined"),!1);if(e===null)return this._null||(s("should be a string, but got null"),!1);if(typeof e!="string")return s(`should be a string, but got ${typeof e}`),!1;if(this._allow.length>0)return this._allow.includes(e)||(s(`${j(e)} is not allowed, just support ${this._allow.map(j).join(", ")}`),!1);if(this._reject.length>0&&this._reject.some(r=>typeof r=="string"?r===e:r.test(e)))return s(`${j(e)} is not allowed`),!1;const n=Object.keys(this._ps);return n.length>0&&!n.some(r=>{const o=this._ps[r];return o instanceof RegExp?o.test(e):o(e)})?(s(`${j(e)} is not match pattern ${n.join(" | ")}`),!1):!0}}class P{_int=!1;_min=-1/0;_max=1/0;_allow=[];_reject=[];_infinite=!1;_unsafe=!1;_nan=!1;_locked=!1;_opt=!1;_null=!1;int(){if(this._locked)throw a("int");return this._int=!0,this}min(e){if(this._locked)throw a("min");return Number.isNaN(e)||(this._min=e),this}max(e){if(this._locked)throw a("max");return Number.isNaN(e)||(this._max=e),this}allowNaN(){if(this._locked)throw a("allowNaN");return this._nan=!0,this}allowInfinity(){if(this._locked)throw a("allowInfinity");return this._infinite=!0,this._unsafe=!0,this}unsafe(){if(this._locked)throw a("unsafe");return this._unsafe=!0,this}enum(...e){if(this._locked)throw a("enum");const s=e[0];return U(e,x)?(this._allow=e,this._reject=[]):y(s)&&(this._allow=Object.values(s).map(n=>x(n)?n:null).filter(n=>n!==null),this._reject=[]),this}disallow(...e){if(this._locked)throw a("disallow");return this._reject.push(...e),this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new P;return e._int=this._int,e._min=this._min,e._max=this._max,e._allow=[...this._allow],e._reject=[...this._reject],e._infinite=this._infinite,e._unsafe=this._unsafe,e._nan=this._nan,e._locked=!1,e}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a number, but got undefined"),!1):e===null?this._null||(s("should be a number, but got null"),!1):typeof e!="number"?(s(`should be a number, but got ${typeof e}`),!1):Number.isNaN(e)?this._nan||(s("should be a number, but got NaN"),!1):!Number.isFinite(e)&&!this._infinite?(s("should be a number, but got Infinity"),!1):this._allow.length>0?this._allow.includes(e)||(s(`${e} is not allowed, just support ${this._allow.join(", ")}`),!1):this._reject.length>0&&this._reject.includes(e)?(s(`${e} is not allowed`),!1):this._int&&Math.ceil(e)!==e?(s(`${e} is not an integer`),!1):!x(e)&&!this._unsafe?(s(`${e} is not a safe number`),!1):e>=this._min&&e<=this._max||(s(`${e} is not in range [${this._min}, ${this._max}]`),!1)}}class C{_min=null;_max=null;_allow=[];_reject=[];_locked=!1;_opt=!1;_null=!1;min(e){if(this._locked)throw a("min");return this._min=e,this}max(e){if(this._locked)throw a("max");return this._max=e,this}enum(...e){if(this._locked)throw a("enum");const s=e[0];return U(e,O)?(this._allow=e,this._reject=[]):y(s)&&(this._allow=Object.values(s).map(n=>O(n)?n:null).filter(n=>n!==null),this._reject=[]),this}disallow(...e){if(this._locked)throw a("disallow");return this._reject.push(...e),this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new C;return e._min=this._min,e._max=this._max,e._allow=[...this._allow],e._reject=[...this._reject],e._locked=!1,e}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a bigint, but got undefined"),!1):e===null?this._null||(s("should be a bigint, but got null"),!1):O(e)?this._allow.length>0?this._allow.includes(e)||(s(`${e} is not allowed, just support ${this._allow.join(", ")}`),!1):this._reject.length>0&&this._reject.includes(e)?(s(`${e} is not allowed`),!1):(this._min!==null?e>=this._min:!0)&&(this._max!==null?e<=this._max:!0)||(s(`${e} is not in range [${this._min===null?-1/0:this._min}, ${this._max===null?1/0:this._max}]`),!1):(s(`should be a bigint, but got ${typeof e}`),!1)}}class I{_locked=!1;_opt=!1;_null=!1;optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new I}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a boolean, but got undefined"),!1):e===null?this._null||(s("should be a boolean, but got null"),!1):typeof e!="boolean"?(s(`should be a boolean, but got ${typeof e}`),!1):!0}}class v{_shape;_plain=!1;_locked=!1;_opt=!1;_null=!1;constructor(e){this._shape=e}plain(){if(this._locked)throw a("plain");return this._plain=!0,this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}get shape(){return{...this._shape}}clone(){const e=new v(this._shape);return e._plain=this._plain,e._locked=!1,e}match(e,s){return e in this._shape?this._shape[e].validate(s,X):!1}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a object, but got undefined"),!1):e===null?this._null||(s("should be a object, but got null"),!1):Y(e)?this._plain&&!y(e)?(s(`should be a plain object, but got ${S(e)}`),!1):Object.keys(this._shape).every(n=>this._shape[n].validate(e[n],(...r)=>{s(`[.${String(n)}]`,...r)})):(s(`should be a object, but got ${S(e)}`),!1)}}class q{_val;_locked=!1;_opt=!1;_null=!1;constructor(e){this._val=e}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new q(this._val)}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a record, but got undefined"),!1):e===null?this._null||(s("should be a record, but got null"),!1):y(e)?Object.keys(e).every(n=>this._val.validate(e[n],(...r)=>{s(`[:${n}]`,...r)})):(s(`should be a record, but got ${S(e)}`),!1)}}class D{_val;_min=0;_max=1/0;_locked=!1;_opt=!1;_null=!1;constructor(e){this._val=e}min(e){if(this._locked)throw a("min");return this._min=e,this}max(e){if(this._locked)throw a("max");return this._max=e,this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new D(this._val);return e._min=this._min,e._max=this._max,e._locked=!1,e}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a array, but got undefined"),!1):e===null?this._null||(s("should be a array, but got null"),!1):Array.isArray(e)?e.length<this._min||e.length>this._max?(this._min===this._max?s(`should be a array with length ${this._min}`):s(`should be a array with length between ${this._min} and ${this._max}`),!1):e.every((n,r)=>this._val.validate(n,(...o)=>{s(`[${r}]`,...o)})):(s(`should be a array, but got ${typeof e}`),!1)}}class L{_vs;_locked=!1;_opt=!1;_null=!1;constructor(...e){this._vs=e}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new L(...this._vs)}validate(e,s=g.warn){return e===void 0?this._opt||(s("should be a tuple, but got undefined"),!1):e===null?this._null||(s("should be a tuple, but got null"),!1):Array.isArray(e)?e.length!==this._vs.length?(s(`should be a tuple with length ${this._vs.length}, but got ${e.length}`),!1):this._vs.every((n,r)=>n.validate(e[r],(...o)=>{s(`[idx:${r}]`,...o)})):(s(`should be a tuple, but got ${typeof e}`),!1)}}class B{_vs;_key="";_locked=!1;_opt=!1;_null=!1;constructor(...e){this._vs=e}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}key(e){if(this._locked)throw a("key");return this._vs.every(s=>s instanceof v)?this._key=e:g.warn("union type key can only be used when all validators are ObjectValidator"),this}satisfies(){return this}lock(){return this._locked=!0,this}get validators(){return[...this._vs]}clone(){const e=new B(...this._vs);return e._key=this._key,e._locked=!1,e}validate(e,s=g.warn){if(e===void 0)return this._opt||(s("should be a union, but got undefined"),!1);if(e===null)return this._null||(s("should be a union, but got null"),!1);if(this._key&&Y(e)&&e){const r=e[this._key];if(r===void 0)return s(`key field "${this._key}" is not found`,e),!1;const o=this._vs.find(i=>i instanceof v&&i.match(this._key,r));return o?o.validate(e,s):(s(`key field "${this._key}" value is match union definition`,r),!1)}const n=this._vs.some(r=>r.validate(e,X));return n||s("value is not match union definition",e),n}}class E{_name="";_guard;_locked=!1;_opt=!1;_null=!1;constructor(e,s){this._name=e,this._guard=s}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new E(this._name,this._guard)}validate(e,s=g.warn){const n=this._name||"custom type";return e===void 0?this._opt||(s(`should be ${n}, but got undefined`),!1):e===null?this._null||(s(`should be ${n}, but got null`),!1):this._guard(e)||(s(`custom validation${this._name?`(${this._name})`:""} failed`),!1)}}function _e(t,e){if(typeof t=="string"){if(!e)throw new Error("custom type guard must be defined");return new E(t,e)}return new E("",t)}const me={shape(t){return t},define(t){return t},guard(t){return function(e){return t.validate(e)}},object(t){return new v(t)},record(t){return new q(t)},array(t){return new D(t)},tuple(...t){return new L(...t)},union(...t){return new B(...t)},string(){return new M},bool(){return new I},number(){return new P},bigint(){return new C},custom:_e,unknown(){return{validate(t){return!0}}},never(){return{validate(t){return!1}}}},ge=t=>y(t)&&Object.keys(t).length===0;me.custom("EmptyObject",ge);function pe(t,e="数据未能正确识别"){return typeof t=="function"?{guard:t,message:e}:{guard:t.guard,message:t.message||e}}function be(t,e=""){return!e||N(t,!0)?W(t):(W(e)+"/"+t).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function W(t){return N(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 ye(t,e){const s={};return(t.match(/([^=&#?]+)=[^&#]*/g)||[]).forEach(function(n){const r=n.split("="),o=r[0],i=decodeURIComponent(r[1]||"");s[o]!==void 0?s[o]+=","+i:s[o]=i}),e!==!0?s[e]||"":s}function we(t,e){if(e){if(e===!0)return t.replace(/\?[^#]*/,"")}else return t;const s=t.split("#"),n=s[0].split("?"),r=n[0],o=n.length>1?n[1]:"",i=s.length>1?"#"+s[1]:"",u=typeof e=="string"?[e]:Array.isArray(e)?e:[];return!u.length||!o?s[0]+i:(u.map(c=>c.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(r+"?"+o.replace(new RegExp("(?:^|&)(?:"+u.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+i)}function ke(t,e,s=!1){const n=typeof e=="string"?e:Object.keys(e).map(i=>`${i}=${encodeURIComponent(e[i])}`).join("&");if(!n)return t;const r=t.split("#");s&&(r[0]=we(r[0],(n.match(/([^=&#?]+)=[^&#]+/g)||[]).map(i=>i.replace(/=.+$/,""))));const o=r[0].indexOf("?")+1?"&":"?";return(r[0]+o+n+(r.length>1?"#"+r[1]:"")).replace(/\?&/,"?")}function ve(t){const e=t.match(/(?:\?|&)([^=]+)(?:&|$)/g);return e?e.join("").replace(/(?:\?|^&+|&+$)/g,"").replace(/&{2}/g,"&").split("&").sort():[]}class $e{ttl;cache;constructor(e=500){this.cache={},this.ttl=Math.max(e,0)}getKey(e,s,n,r){if(e.toLowerCase()!=="get"&&!r)return"";const o=e.toLowerCase(),i=s.replace(/#.+/,""),u=i.replace(/\?.+/g,"");if(r){const h=r()||"";return h?`${u}_${o}_${h}`:""}const c=Object.assign(ye(i,!0),n),_=ve(i),f=Object.keys(c).sort().map(h=>`${h}#${c[h]}`);return`${u}_${o}_${f.join(",")}_${_.join(",")}`}updateTTL(e){this.ttl=Math.max(e,0)}get(e){if(this.ttl===0)return null;const s=this.cache[e];return s?s.ttl<Date.now()?(delete this.cache[e],null):s.res:null}set(e,s,n){const r=n??this.ttl;r<=0||(this.cache[e]={ttl:Date.now()+r,res:s})}}class ee{config={baseURL:"/",maxRetry:0,retryInterval:100,retryResolve:"network",timeout:1e4,cacheTTL:500,credentials:"same-origin",defaultTypeGuardMessage:"响应数据未能正确识别",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}};constructor(e){e&&this.set(e)}set(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!N(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)}get(e){return this.config[e]}getFullUrl(e){return be(e,this.config.baseURL)}showMessage(e,s,n,r){this.config.messageHandler&&s&&this.config.messageHandler(e,s,n,r)}}const H={UnexpectResponse:"UnexpectResponse",Aborted:"Aborted",Unknown:"Unknown",NetworkError:"NetworkError",Timeout:"Timeout",NotSupport:"NotSupport",URLFormatError:"URLFormatError"};function je(t,e,s,n){if(e.ok&&!he(e.data)&&n){const r=pe(n,s.get("defaultTypeGuardMessage"));return r.guard(e.data)||(e.code=H.UnexpectResponse,s.showMessage(!0,`${t} ${r.message}`,e.code,e.status),console.error(e.code,t,e.data),e.data=null,e.message=r.message),e}return e}class Re{agent;config;cache;constructor(e,s){this.config=new ee(s),this.agent=e,this.cache=new $e(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)}async request(e,s){const n=this.cache.getKey(s?.method||"GET",e,s?.params,s?.cacheResolve);if(n){const r=this.cache.get(n);if(r)return await r}try{const r=this.agent(e,this.config,s);return n&&this.cache.set(n,r),await r}catch(r){return console.error("RequestError",r),{ok:!1,status:-9,code:H.Unknown,message:r instanceof Error?`${r.message}
|
|
2
|
+
${r.stack||""}`:String(r),headers:{},data:null}}}async guard(e,s,n){return je(e,s,this.config,n)}setConfig(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(e){return this.config.get(e)}async head(e,s){const n=Object.assign({},s||null);return n.method="HEAD",this.guard(e,await this.request(e,n),null)}async get(e,s,n){const r=Object.assign({},n||null);r.method="GET";const o=this.request(e,r);return this.guard(e,await o,s||null)}async post(e,s,n,r){const o=Object.assign({},r||null);return o.method="POST",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}async del(e,s,n){const r=Object.assign({},n||null);return r.method="DELETE",this.guard(e,await this.request(e,r),s||null)}async put(e,s,n,r){const o=Object.assign({},r||null);return o.method="PUT",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}async patch(e,s,n,r){const o=Object.assign({},r||null);return o.method="PATCH",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}}async function Ee(t,e,s){const n=Object.assign({method:"GET"},s),r=k.FormData?n.body instanceof FormData:!1,o=r&&n.method!=="POST"&&n.method!=="PUT"?"POST":n.method,i=o==="GET"||o==="HEAD"||o==="DELETE";i&&n.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);const u=Object.assign(r||i?{}:{"Content-Type":k.Blob&&n.body instanceof Blob?n.body.type||"application/octet-stream":"application/json;charset=utf-8"},n.headers),c=n.params||{},_={};Object.keys(c).forEach(m=>{c[m]!==void 0&&(_[m]=Ne(c[m]))});const f=e.getFullUrl(t),h=xe(n.body),p=n.timeout||e.get("timeout"),b=await async function(){const m=e.get("requestTransformer");if(m)return await m({headers:u,params:_,method:o,url:f,body:h})}(),w=typeof b=="string"&&b?b:f;return e.get("logHandler")?.({type:"ready",url:w,method:o,headers:u,timeout:p,body:h}),{url:w,method:o,body:h,params:_,headers:u,timeout:p,abort:n.abort,credentials:n.credentials||e.get("credentials")}}function Ne(t){return typeof t=="string"?t:Array.isArray(t)?t.join(","):t+""}function xe(t){if(t)return typeof t=="string"||k.URLSearchParams&&t instanceof URLSearchParams||t instanceof ArrayBuffer||k.Blob&&t instanceof Blob||k.FormData&&t instanceof FormData?t:JSON.stringify(t)}const te="data",$="message";function Oe(t,e,s,n,r){const o=r||n;return G(t)?Pe(o.ok||n.ok,t,e,s):Se(o.failed||n.failed,e,s)}const Fe=function(t){const e=[],s=t.failed||{resolve:"json"};switch(e.push("- 当http状态码 <200 或者 >=400 时"),s.resolve){case"body":e.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":e.push(" 将响应解析为json,并读取 "+(s.messageField||$)+" 作为错误消息");break}const n=t.ok||{resolve:"body"};switch(e.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":e.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":e.push(" 将响应解析为 json,读取 "+(n.dataField||te)+" 作为响应数据,读取 "+(n.messageField||$)+" 作为提示消息"),n.statusField&&e.push(" 当 "+n.statusField+" 为 "+(n.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&e.push(" 并忽略以下消息:"+n.ignoreMessage);break}return e.join(`
|
|
3
|
+
`)};function Se(t,e,s){const n=t||{resolve:"json",messageField:$},r={ok:!1,code:e,message:s,data:null};switch(n.resolve){case"body":r.message=V(s)||s;break;case"json":const{code:o,message:i}=Ae(s,n.converter,n.statusField,n.messageField);r.code=o||e,r.message=V(s)||i;break}return r}function Ae(t,e,s,n=$){if(!Z(t))return{message:""};const r=T(F(t),e);return!r||!y(r)?{message:t}:{code:s?A(r,s):"",message:A(r,n)||t}}function A(t,e){const s=Array.isArray(e)?e:[e];for(const n of s)if(n in t)return Te(t[n]);return""}function Te(t){return t?typeof t=="string"?t:JSON.stringify(t):""}const Ue=/<title>([^<]+)<\/title>/i,Me=/<message>([^<]+)<\/message>/i;function V(t){const e=t.match(Ue);if(e)return e[1];const s=t.match(Me);return s?s[1]:""}function Pe(t,e,s,n){const r=t||{resolve:"body"},o={ok:!0,code:s,message:"",data:null};if(e===204||!n)return o;if(r.resolve==="body")return o.data=Z(n)?T(F(n),t.converter):n,o;const i=T(F(n),t.converter);if(!i||!y(i))return o.ok=!1,o.code="ResponseFormatError",o.message="响应内容无法格式化为 Object",o;const u=r.statusField,c=r.statusOKValue||"",_=r.dataField||te,f=r.messageField||$,h=r.ignoreMessage||"";if(u&&!(u in i))return o.ok=!1,o.code="ResponseFieldMissing",o.message="响应内容找不到状态字段 "+u,o;const p=u?i[u]+"":"";return o.ok=u?p===c:!0,o.code=p||s,o.data=_===!0?i:_ in i?i[_]:null,o.message=A(i,f),h&&o.message&&(Array.isArray(h)&&h.includes(o.message)||typeof h=="string"&&o.message===h)&&(o.message=""),o}function G(t){return t>=200&&t<400}function T(t,e){return e?typeof e=="function"?e(t):(console.warn('工具不再支持 "camelize", "snakify" 参数,请自行提供函数来转化 body 内容'),t):t}const Ce=oe("APIError");function Ie(t){const e={};for(const r in t.headers)(r.startsWith("x-")||r.includes("trace")||r.includes("server")||/\b(?:id|uuid)\b/.test(r))&&(e[r]=t.headers[r]);const s=t.url.replace(/^(?:https?:)?\/*/i,"").replace(/\?.+/,""),n=t.status<0?"unknown":t.status;return{sentryError:new Ce(`${s} | ${n}${t.code?` | ${t.code}`:""}`),sentryTags:{...e,status:n,method:t.method,code:t.code||"unknown",message:t.message||"empty"},sentryExtra:{url:t.url,responseBody:t.body||"empty",responseHeaders:t.headers,rawError:t.error}}}function se(t){return t.reduce((e,[s,n])=>(s&&(e[s]=n||""),e),{})}function qe(t,e,s,n){const r=t.status,o=t.method,i=se(Object.entries(t.headers||{}).map(([b,w])=>[b.toLowerCase(),w])),{ok:u,code:c,data:_,message:f}=Oe(r,t.statusText,t.body,s.get("responseRule"),n?.responseRule);if(!G(r)){const b=Ie({url:t.url,method:t.method,status:r,code:c,message:f,body:t.body,headers:i,error:t.rawError});(s.get("errorHandler")||De)({url:e,method:o,status:r,code:c,message:f,headers:i,rawError:t.rawError,responseBody:t.body,...b})}if(r<0)return J({ok:!1,status:r,code:t.statusText,headers:{},message:"",data:null},`${o} ${e} ${t.statusText}`,o,e,s,n);const h={ok:u,data:_,code:c,message:f,status:r,headers:i};s.get("responseHandler")?.({...h},o,e);const p=u?f:f||t.statusText;return J(h,p,o,e,s,n)}function J(t,e,s,n,r,o){const i=r.get("message"),u=i===!1||o?.message===!1?!1:o?.message||i;if(u!==!1){const c=typeof u=="function"?u(t,s,n,e):e;c instanceof Error?r.showMessage(!0,c.message,t.code,t.status):c&&typeof c=="object"&&"message"in c?r.showMessage(!1,c.message,t.code,t.status):r.showMessage(!t.ok,c,t.code,t.status)}return t}function De(t){const e={};for(const s in t)s.startsWith("sentry")||(e[s]=t[s]);console.error("RequestError",e)}async function ne(t,e,s,n,r){const o=r||0,i=Math.max(0,Math.min(10,n?.maxRetry??s.get("maxRetry")??0)),u=n?.retryResolve??s.get("retryResolve"),c=s.get("logHandler");c?.({type:"prepare",url:e,method:n?.method||"GET",retry:o,maxRetry:i,message:o===0?"start":`retry ${o}/${i} start`,headers:n?.headers,options:n});const _=Date.now(),f=await t(e,s,n),h=f.status,p=Date.now()-_,b=`[cost ${p}][${h}] ${h<0?f.body:""}`;c?.({type:"finished",url:e,method:f.method,retry:o,maxRetry:i,message:o===0?`finish ${b}`:`retry ${o}/${i} finish ${b}`,response:f,headers:f.headers,cost:p});const w=G(h);if(!i||o>=i||u==="network"&&h>0||u==="status"&&w||Array.isArray(u)&&!u.includes(h)||typeof u=="function"&&u(f,o)!==!0)return f;const m=n?.retryInterval??s.get("retryInterval")??100;return await re(Math.max(100,m==="2EB"?Math.pow(2,o)*100:typeof m=="function"?m(o+1,{url:e,status:h,method:f.method})||0:m)),await ne(t,e,s,n,o+1)}exports.NetRequestHandler=Re;exports.Nt=N;exports.RequestGlobalConfig=ee;exports.RequestInternalError=H;exports._e=ke;exports.convertOptions=Ee;exports.fromEntries=se;exports.getResponseRulesDescription=Fe;exports.handleResponse=qe;exports.jt=k;exports.le=de;exports.retryRequest=ne;
|