@seayoo-web/request 2.1.2 → 3.0.1
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 +11 -11
- package/dist/index.cjs +2 -2
- package/dist/index.js +10 -10
- package/dist/node.cjs +1 -1
- package/dist/node.js +13 -13
- package/dist/{request.fetch-rPuFhiKx.cjs → request.fetch-BV6wXr9n.cjs} +1 -1
- package/dist/{request.fetch-DF7WikXa.js → request.fetch-DyACTVjU.js} +1 -1
- package/dist/retry-C55r4dQg.cjs +3 -0
- package/dist/retry-CiM_TrAz.js +595 -0
- package/dist/wx.cjs +1 -1
- package/dist/wx.js +6 -6
- package/package.json +3 -3
- package/types/inc/main.d.ts +2 -2
- package/types/inc/rule.d.ts +1 -1
- package/types/inc/type.d.ts +7 -7
- package/types/index.d.ts +2 -1
- package/dist/retry-B9vBp2mw.cjs +0 -2
- package/dist/retry-Ch1GFMrA.js +0 -572
package/README.md
CHANGED
|
@@ -173,7 +173,7 @@ defaultMessage: string
|
|
|
173
173
|
|
|
174
174
|
**resolve**: "json" | "body"
|
|
175
175
|
|
|
176
|
-
|
|
176
|
+
解析方式,设置为 json(默认),则可以进一步指定错误消息字段;设置为 body 则将整个 body 解析为错误信息;
|
|
177
177
|
|
|
178
178
|
**converter**: "camelize" | "snakify"
|
|
179
179
|
|
|
@@ -181,11 +181,11 @@ defaultMessage: string
|
|
|
181
181
|
|
|
182
182
|
**statusField**: string
|
|
183
183
|
|
|
184
|
-
|
|
184
|
+
解析错误消息的状态字段,仅在 resolve 为 json 时有效,有值的话会替换 response 的 code
|
|
185
185
|
|
|
186
186
|
**messageField**: string | string[]
|
|
187
187
|
|
|
188
|
-
|
|
188
|
+
错误消息解析字段,仅在 resolve 为 json 时有效,默认值 "message"
|
|
189
189
|
|
|
190
190
|
- **OKRule**: { resolve, converter?, statusField?, statusOKValue?, dataField?, messageField?, ignoreMessage? }
|
|
191
191
|
|
|
@@ -193,7 +193,7 @@ defaultMessage: string
|
|
|
193
193
|
|
|
194
194
|
**resolve**: "json" | "body"
|
|
195
195
|
|
|
196
|
-
|
|
196
|
+
解析方式,若设置为 json,则可以进一步指定更多字段;若设置为 body(默认),则把整个响应体作为接口返回的数据使用,如果格式化失败,则返回响应的字符串;
|
|
197
197
|
|
|
198
198
|
**converter**: "camelize" | "snakify"
|
|
199
199
|
|
|
@@ -201,23 +201,23 @@ defaultMessage: string
|
|
|
201
201
|
|
|
202
202
|
**statusField**: string
|
|
203
203
|
|
|
204
|
-
|
|
204
|
+
指定表示自定义状态的字段名,默认是 "code"
|
|
205
205
|
|
|
206
206
|
**statusOKValue**: string
|
|
207
207
|
|
|
208
|
-
|
|
208
|
+
指定表示自定义状态成功时的 value,默认是 "0",如果响应值为数字,则会被转化为字符串进行处理
|
|
209
209
|
|
|
210
210
|
**dataField**: string | true
|
|
211
211
|
|
|
212
|
-
|
|
212
|
+
指定表示响应数据的字段,默认是 "data",如果设置为 true,则将整个 json body 作为数据内容返回
|
|
213
213
|
|
|
214
214
|
**messageField**: string | string[]
|
|
215
215
|
|
|
216
|
-
|
|
216
|
+
指定表示提示消息的字段,提示消息可以包括错误消息和成功消息,默认是 "message"
|
|
217
217
|
|
|
218
218
|
**ignoreMessage**: string | string[]
|
|
219
219
|
|
|
220
|
-
|
|
220
|
+
指定忽略的消息,比如 ok 等,可以设置多个忽略消息,区分大小写
|
|
221
221
|
|
|
222
222
|
### maxRetry
|
|
223
223
|
|
|
@@ -294,7 +294,7 @@ sentryExtra: Record<string, unknown>
|
|
|
294
294
|
|
|
295
295
|
类型:null | ((isError: boolean, message: string, code: string, status:number) => void)
|
|
296
296
|
|
|
297
|
-
说明:全局默认提示函数,isError 表示需要提示的消息是否为错误消息,message 为提示内容,code 为状态描述码或内置错误码(可导出
|
|
297
|
+
说明:全局默认提示函数,isError 表示需要提示的消息是否为错误消息,message 为提示内容,code 为状态描述码或内置错误码(可导出 RequestInternalError 进行对比),status 为 http 状态码
|
|
298
298
|
|
|
299
299
|
### logHandler
|
|
300
300
|
|
|
@@ -386,7 +386,7 @@ sentryExtra: Record<string, unknown>
|
|
|
386
386
|
|
|
387
387
|
- http statusText 当请求完成且无自定义错误码时,可能为空字符串
|
|
388
388
|
- responseRule 中自定义的错误码字段所传递的值
|
|
389
|
-
- "Aborted" 或 "Unknown" 网络错误或取消等异常情况,详细参见 `
|
|
389
|
+
- "Aborted" 或 "Unknown" 网络错误或取消等异常情况,详细参见 `RequestInternalError`
|
|
390
390
|
|
|
391
391
|
### message
|
|
392
392
|
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./retry-
|
|
2
|
-
`).forEach(n=>{const r=n.trim();if(!r)return;const d=r.split(":"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./retry-C55r4dQg.cjs"),q=require("./request.fetch-BV6wXr9n.cjs"),y=async function(t,s,e){return o.handleResponse(await o.retryRequest(R,t,s,e),t,s,e)};async function m(t,s,e,n){const r=e==null?void 0:e.body,d=(e==null?void 0:e.method)==="PUT"?"PUT":"POST";if(s instanceof Blob){const u=new o.RequestGlobalConfig(n),g=await R(t,u,{...e,method:d,body:s});return o.handleResponse(g,t,u,e)}const l=new FormData,f={...s};r instanceof Object&&Object.entries(r).forEach(([u,g])=>{g instanceof Blob?f[u]=g:Array.isArray(g)?g.forEach((a,i)=>{l.append(`${u}[${i}]`,String(a))}):l.append(u,String(g))});for(const u in f)l.append(u,f[u]);const b=new o.RequestGlobalConfig(n),w=await R(t,b,{...e,method:d,body:l});return o.handleResponse(w,t,b,e)}const R=async function(t,s,e){const n=await o.convertOptions(t,s,e),r=n.method,d=e==null?void 0:e.onUploadProgress,l=o.le(n.url,n.params);return await new Promise(f=>{let b=null,w=!1;const u=function(){w||(a.abort(),w=!0)};function g(){b!==null&&clearTimeout(b),n.abort&&n.abort.removeEventListener("abort",u)}const a=new XMLHttpRequest;if(a.open(r,l,!0),d){let i=1;a.upload.addEventListener("progress",h=>{i=h.total,d({total:h.total,loaded:h.loaded})}),a.addEventListener("load",()=>{d({loaded:i,total:i})})}a.addEventListener("load",()=>{const i=a.status;g(),f({url:l,method:r,status:i,statusText:a.statusText,headers:E(a),body:r==="HEAD"||i===204?"":a.responseText})}),a.addEventListener("error",i=>{g(),f({url:l,method:r,status:a.status||-1,statusText:a.statusText||o.RequestInternalError.NetworkError,body:"",rawError:i})},!0),a.addEventListener("abort",()=>{g(),f({url:l,method:r,status:0,statusText:o.RequestInternalError.Aborted,body:""})}),Object.entries(n.headers).forEach(([i,h])=>{a.setRequestHeader(i,h)}),n.credentials==="include"&&(a.withCredentials=!0),a.send(n.body||void 0),n.abort&&n.abort.addEventListener("abort",u),n.timeout>0&&(b=setTimeout(u,n.timeout))})};function E(t){const s={};if(!t)return s;const e=t.getAllResponseHeaders();return e&&e!=="null"&&e.replace(/\r/g,"").split(`
|
|
2
|
+
`).forEach(n=>{const r=n.trim();if(!r)return;const d=r.split(":"),l=d[0].trim();l&&(s[l]=(d[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 r=e.callback+"";if(!t)return null;const d=o.le(t,e,!0);return new Promise(l=>{n[r]=function(f){if(r in window&&delete n[r],s(f))return f;console.warn("response type check failed",t,f),l(null)},o.Ge(d).catch(function(){l(null),delete n[r]})})}async function T(t,s,e={}){const n=window;return"var"in e||(e.var="jsonxData"+Math.random().toString(16).slice(2)),t?await o.Ge(o.le(t,e,!0)).then(()=>{const r=n[e.var+""];return s(r)?r:(console.warn("response type check failed",t,r),null)}).catch(()=>null):null}const x=async function(t,s,e){return await m(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 p(t){if(!o.Rt.window)throw new Error("Default Module Only Support In Browser");return o.Rt.fetch?new o.NetRequestHandler(q.fetchRequest,t):new o.NetRequestHandler(y,t)}const c=p(),C=c.setConfig,j=c.request,L=c.head,S=c.get,k=c.post,v=c.del,D=c.put,U=c.patch;exports.RequestInternalError=o.RequestInternalError;exports.getResponseRulesDescription=o.getResponseRulesDescription;exports.NetRequest=p;exports.del=v;exports.get=S;exports.head=L;exports.jsonp=H;exports.jsonx=T;exports.patch=U;exports.post=k;exports.put=D;exports.request=j;exports.setGlobalConfig=C;exports.upload=x;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { h as w, r as T, R as y, c as x,
|
|
2
|
-
import { g as
|
|
3
|
-
import { f as C } from "./request.fetch-
|
|
1
|
+
import { h as w, r as T, R as y, c as x, l as p, a as R, G as q, b as E, N as H } from "./retry-CiM_TrAz.js";
|
|
2
|
+
import { g as J } from "./retry-CiM_TrAz.js";
|
|
3
|
+
import { f as C } from "./request.fetch-DyACTVjU.js";
|
|
4
4
|
const L = async function(t, a, e) {
|
|
5
5
|
return w(await T(m, t, a, e), t, a, e);
|
|
6
6
|
};
|
|
@@ -110,7 +110,7 @@ async function D(t, a, e = {}) {
|
|
|
110
110
|
n[r] = function(u) {
|
|
111
111
|
if (r in window && delete n[r], a(u))
|
|
112
112
|
return u;
|
|
113
|
-
console.warn("response type check
|
|
113
|
+
console.warn("response type check failed", t, u), s(null);
|
|
114
114
|
}, q(d).catch(function() {
|
|
115
115
|
s(null), delete n[r];
|
|
116
116
|
});
|
|
@@ -120,7 +120,7 @@ async function O(t, a, e = {}) {
|
|
|
120
120
|
const n = window;
|
|
121
121
|
return "var" in e || (e.var = "jsonxData" + Math.random().toString(16).slice(2)), t ? await q(p(t, e, !0)).then(() => {
|
|
122
122
|
const r = n[e.var + ""];
|
|
123
|
-
return a(r) ? r : (console.warn("response type check
|
|
123
|
+
return a(r) ? r : (console.warn("response type check failed", t, r), null);
|
|
124
124
|
}).catch(() => null) : null;
|
|
125
125
|
}
|
|
126
126
|
const P = async function(t, a, e) {
|
|
@@ -138,17 +138,17 @@ function U(t) {
|
|
|
138
138
|
throw new Error("Default Module Only Support In Browser");
|
|
139
139
|
return E.fetch ? new H(C, t) : new H(L, t);
|
|
140
140
|
}
|
|
141
|
-
const c = U(), A = c.setConfig, M = c.request, N = c.head,
|
|
141
|
+
const c = U(), A = c.setConfig, M = c.request, N = c.head, G = c.get, B = c.post, X = c.del, F = c.put, I = c.patch;
|
|
142
142
|
export {
|
|
143
143
|
U as NetRequest,
|
|
144
|
-
R as
|
|
144
|
+
R as RequestInternalError,
|
|
145
145
|
X as del,
|
|
146
|
-
|
|
147
|
-
|
|
146
|
+
G as get,
|
|
147
|
+
J as getResponseRulesDescription,
|
|
148
148
|
N as head,
|
|
149
149
|
D as jsonp,
|
|
150
150
|
O as jsonx,
|
|
151
|
-
|
|
151
|
+
I as patch,
|
|
152
152
|
B as post,
|
|
153
153
|
F as put,
|
|
154
154
|
M 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-C55r4dQg.cjs"),y=require("./request.fetch-BV6wXr9n.cjs"),b=require("node:http"),g=require("node:https"),w=async function(r,u,c){return e.handleResponse(await e.retryRequest(E,r,u,c),r,u,c)},E=async function(r,u,c){const t=await e.convertOptions(r,u,c);if(!e.$t(t.url))return{url:t.url,method:t.method,status:-1,statusText:e.RequestInternalError.URLFormatError,headers:{},body:""};const p=/^https:\/\//i.test(t.url)?g:b,a=new URL(t.url),i=t.params;i instanceof Object&&Object.keys(i).forEach(n=>a.searchParams.set(n,i[n]));const R=t.method==="HEAD";return new Promise(n=>{const d=p.request(a,{headers:t.headers,method:t.method,timeout:t.timeout>0?t.timeout:void 0},function(o){const l=[];o.on("data",h=>l.push(h)),o.on("end",()=>{const h=e.fromEntries(Object.entries(o.headers).map(([f,m])=>[f.toLowerCase(),Array.isArray(m)?m.join(","):m]));n({url:a.toString(),method:t.method,status:o.statusCode||-1,statusText:o.statusMessage||e.RequestInternalError.Unknown,headers:h,body:R||o.statusCode===204?"":Buffer.concat(l).toString("utf-8")})})});d.on("error",o=>{n({url:a.toString(),method:t.method,status:-1,statusText:e.RequestInternalError.NetworkError,body:"",rawError:o})}),d.on("timeout",()=>{n({url:a.toString(),method:t.method,status:-1,statusText:e.RequestInternalError.Timeout,body:""})}),t.body&&d.write(t.body),d.end()})};function q(r){return e.Rt.fetch?new e.NetRequestHandler(y.fetchRequest,r):new e.NetRequestHandler(w,r)}const s=q(),C=s.setConfig,N=s.head,S=s.get,T=s.post,j=s.del,O=s.put,x=s.patch;exports.NetRequest=q;exports.del=j;exports.get=S;exports.head=N;exports.patch=x;exports.post=T;exports.put=O;exports.setGlobalConfig=C;
|
package/dist/node.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { h as y, r as q, c as w,
|
|
2
|
-
import { f as C } from "./request.fetch-
|
|
1
|
+
import { h as y, r as q, c as w, $ as g, a as d, f as E, N as p, b as x } from "./retry-CiM_TrAz.js";
|
|
2
|
+
import { f as C } from "./request.fetch-DyACTVjU.js";
|
|
3
3
|
import N from "node:http";
|
|
4
4
|
import T from "node:https";
|
|
5
5
|
const j = async function(o, a, u) {
|
|
@@ -15,11 +15,11 @@ const j = async function(o, a, u) {
|
|
|
15
15
|
headers: {},
|
|
16
16
|
body: ""
|
|
17
17
|
};
|
|
18
|
-
const
|
|
18
|
+
const R = /^https:\/\//i.test(t.url) ? T : N, n = new URL(t.url), i = t.params;
|
|
19
19
|
i instanceof Object && Object.keys(i).forEach((r) => n.searchParams.set(r, i[r]));
|
|
20
|
-
const
|
|
20
|
+
const l = t.method === "HEAD";
|
|
21
21
|
return new Promise((r) => {
|
|
22
|
-
const c =
|
|
22
|
+
const c = R.request(
|
|
23
23
|
n,
|
|
24
24
|
{
|
|
25
25
|
headers: t.headers,
|
|
@@ -38,7 +38,7 @@ const j = async function(o, a, u) {
|
|
|
38
38
|
status: e.statusCode || -1,
|
|
39
39
|
statusText: e.statusMessage || d.Unknown,
|
|
40
40
|
headers: m,
|
|
41
|
-
body:
|
|
41
|
+
body: l || e.statusCode === 204 ? "" : Buffer.concat(f).toString("utf-8")
|
|
42
42
|
});
|
|
43
43
|
});
|
|
44
44
|
}
|
|
@@ -66,14 +66,14 @@ const j = async function(o, a, u) {
|
|
|
66
66
|
function O(o) {
|
|
67
67
|
return x.fetch ? new p(C, o) : new p(j, o);
|
|
68
68
|
}
|
|
69
|
-
const s = O(), k = s.setConfig,
|
|
69
|
+
const s = O(), k = s.setConfig, B = s.head, P = s.get, $ = s.post, D = s.del, F = s.put, G = s.patch;
|
|
70
70
|
export {
|
|
71
71
|
O as NetRequest,
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
72
|
+
D as del,
|
|
73
|
+
P as get,
|
|
74
|
+
B as head,
|
|
75
|
+
G as patch,
|
|
76
|
+
$ as post,
|
|
77
|
+
F as put,
|
|
78
78
|
k as setGlobalConfig
|
|
79
79
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";const s=require("./retry-
|
|
1
|
+
"use strict";const s=require("./retry-C55r4dQg.cjs"),m=async function(a,n,i){return s.handleResponse(await s.retryRequest(w,a,n,i),a,n,i)},w=async function(a,n,i){const t=await s.convertOptions(a,n,i),c=new URL(t.url),u=t.params;u instanceof Object&&Object.keys(u).forEach(e=>c.searchParams.set(e,u[e]));const r=s.Rt.AbortController?new AbortController:null;function d(){r&&!r.signal.aborted&&r.abort()}t.abort&&t.abort.addEventListener("abort",d);const h=t.timeout>0?setTimeout(d,t.timeout):null,l=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:r==null?void 0:r.signal,redirect:"follow"}).then(async e=>{const o={url:c.toString(),method:t.method,status:e.status,statusText:e.statusText,headers:s.fromEntries([...e.headers.entries()])},b=l||e.status===204?"":await e.text().catch(f=>f);return b instanceof Error?{...o,body:"",statusText:s.RequestInternalError.Unknown,rawError:b}:{...o,body:b}}).catch(e=>{const o=r==null?void 0:r.signal.aborted;return{url:c.toString(),method:t.method,status:o?0:-1,statusText:o?s.RequestInternalError.Aborted:s.RequestInternalError.NetworkError,body:"",rawError:e}}).finally(()=>{h!==null&&clearTimeout(h),t.abort&&t.abort.removeEventListener("abort",d)})};exports.fetchRequest=m;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { h as m, r as w, c as y,
|
|
1
|
+
import { h as m, r as w, c as y, b as E, f as R, a as b } from "./retry-CiM_TrAz.js";
|
|
2
2
|
const x = async function(s, o, n) {
|
|
3
3
|
return m(await w(g, s, o, n), s, o, n);
|
|
4
4
|
}, g = async function(s, o, n) {
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"use strict";var J=Object.defineProperty;var z=(e,t,s)=>t in e?J(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var b=(e,t,s)=>z(e,typeof t!="symbol"?t+"":t,s);const c=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),R={wx:"wx"in c&&j(c.wx)&&"getSystemInfo"in c.wx&&d(c.wx.getSystemInfo),fetch:"fetch"in c&&d(c.fetch),window:"window"in c&&j(c.window),requestAnimationFrame:"requestAnimationFrame"in c&&d(c.requestAnimationFrame),localStorage:"localStorage"in c&&j(c.localStorage)&&"getItem"in c.localStorage&&d(c.localStorage.getItem),sessionStorage:"sessionStorage"in c&&j(c.sessionStorage)&&"getItem"in c.sessionStorage&&d(c.sessionStorage.getItem),File:"File"in c&&d(c.File),Blob:"Blob"in c&&d(c.Blob),Proxy:"Proxy"in c&&d(c.Proxy),Request:"Request"in c&&d(c.Request),FormData:"FormData"in c&&d(c.FormData),TextDecoder:"TextDecoder"in c&&d(c.TextDecoder),ResizeObserver:"ResizeObserver"in c&&d(c.ResizeObserver),AbortController:"AbortController"in c&&d(c.AbortController)};function d(e){return typeof e=="function"}function j(e){return typeof e=="object"&&e!==null}function V(e){return new Promise(t=>setTimeout(t,Math.max(0,e)))}function W(){}function q(e,t){const s={log:console.log.bind(console),error:console.error.bind(console),warn:console.warn.bind(console)},r=`[${e}]`;return["log","error","warn"].forEach(o=>{const n=console[o];s[o]=(...a)=>{n.apply(console,[r,...a])}}),s}function Z(e){const t=e||"CustomError";return class extends Error{constructor(s){super(s),Object.defineProperty(this,"name",{value:t,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 X=/^(?:https?:)?\/\/.+$/i,Q=/^https?:\/\/.+$/i,Y=/^\{[\d\D]*\}$/,ee=/^\[[\d\D]*\]$/;function F(e,t=!1){return t?X.test(e):Q.test(e)}function te(e){return e==null}function v(e,...t){if(!e||typeof e!="object")return!1;const s=Object.getPrototypeOf(e);return s!==Object.prototype&&s!==null?!1:t.every(r=>r in e)}function B(e){return Y.test(e)||ee.test(e)}function O(e){return e?e[0].toLowerCase()+e.slice(1):""}const _=/_\w*/,H=/-\w*/;function x(e){const t=_.test(e)?e.replace(/(?:^_*|_*$)/g,"").replace(/_+([^_])/g,(s,r)=>r.toUpperCase()):H.test(e)?e.replace(/(?:^-*|-*$)/g,"").replace(/-+(\w)/g,(s,r)=>r.toUpperCase()):e;return O(t)}function M(e){return _.test(e)?O(e).replace(/(?:^_*|_*$)/g,"").replace(/_+([^_])/g,(t,s)=>"_"+s.toLowerCase()):H.test(e)?O(e.replace(/(?:^-*|-*$)/g,"")).replace(/-+(\w)/g,(t,s)=>"_"+s.toLowerCase()):O(e).replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function A(e,t){try{const s=JSON.parse(e);return t?t(s)?s:null:s}catch{return null}}""+Math.random().toString(32).slice(2);function E(e,t=!1){return typeof e=="string"?x(e):Array.isArray(e)?e.map(s=>!t||typeof s=="string"?E(s):typeof s=="object"&&s?E(s,!0):s):v(e)?Object.keys(e).reduce((s,r)=>{const o=x(String(r)),n=o.charAt(0).toLowerCase()+o.slice(1);return s[n]=t?e[r]:E(e[r]),s},{}):e}function k(e,t=!1){return typeof e=="string"?M(e):Array.isArray(e)?e.map(s=>!t||typeof s=="string"?k(s):typeof s=="object"&&s?k(s,t):s):v(e)?Object.keys(e).reduce((s,r)=>{const o=M(String(r));return s[o]=t?e[r]:k(e[r]),s},{}):e}q("LoadUtils");async function se(e){return await new Promise(function(t){const s=document.getElementsByTagName("head")[0],r=document.createElement("script");r.setAttribute("type","text/javascript"),r.setAttribute("charset","utf-8"),r.onload=function(){s.removeChild(r),t(!0)},r.onerror=function(){s.removeChild(r),t(!1)},r.setAttribute("src",e),s.appendChild(r)})}q("Validator");function re(e,t="数据未能正确识别"){return typeof e=="function"?{guard:e,message:t}:{guard:e.guard,message:e.message||t}}function ne(e,t=""){return!t||F(e,!0)?D(e):(D(t)+"/"+e).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function D(e){return F(e,!0)?e.startsWith("http")?e:("location"in globalThis?location.protocol:"https:")+e:("location"in globalThis?location.origin:"http://127.0.0.1")+"/"+e.replace(/^\/+/,"")}function oe(e,t){const s={};return(e.match(/([^=&#?]+)=[^&#]*/g)||[]).forEach(function(r){const o=r.split("="),n=o[0],a=decodeURIComponent(o[1]||"");s[n]!==void 0?s[n]+=","+a:s[n]=a}),t!==!0?s[t]||"":s}function ae(e,t){if(t){if(t===!0)return e.replace(/\?[^#]*/,"")}else return e;const s=e.split("#"),r=s[0].split("?"),o=r[0],n=r.length>1?r[1]:"",a=s.length>1?"#"+s[1]:"",i=typeof t=="string"?[t]:Array.isArray(t)?t:[];return!i.length||!n?s[0]+a:(i.map(u=>u.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(o+"?"+n.replace(new RegExp("(?:^|&)(?:"+i.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+a)}function ce(e,t,s=!1){const r=typeof t=="string"?t:Object.keys(t).map(a=>`${a}=${encodeURIComponent(t[a])}`).join("&");if(!r)return e;const o=e.split("#");s&&(o[0]=ae(o[0],(r.match(/([^=&#?]+)=[^&#]+/g)||[]).map(a=>a.replace(/=.+$/,""))));const n=o[0].indexOf("?")+1?"&":"?";return(o[0]+n+r+(o.length>1?"#"+o[1]:"")).replace(/\?&/,"?")}function ie(e){const t=e.match(/(?:\?|&)([^=]+)(?:&|$)/g);return t?t.join("").replace(/(?:\?|^&+|&+$)/g,"").replace(/&{2}/g,"&").split("&").sort():[]}class ue{constructor(t=500){b(this,"ttl");b(this,"cache");this.cache={},this.ttl=Math.max(t,0)}getKey(t,s){const r=t.replace(/#.+/,""),o=r.replace(/\?.+/g,""),n=Object.assign(oe(r,!0),s),a=ie(r),i=Object.keys(n).sort().map(u=>`${u}#${n[u]}`);return`${o}_${i.join(",")}_${a.join(",")}`}updateTTL(t){this.ttl=Math.max(t,0)}get(t){if(this.ttl===0)return null;const s=this.cache[t];return s?s.ttl<Date.now()?(delete this.cache[t],null):s.res:null}set(t,s){this.ttl!==0&&(this.cache[t]={ttl:Date.now()+this.ttl,res:s})}}class I{constructor(t){b(this,"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"}}});t&&this.set(t)}set(t){if(t.baseURL&&!/^\/.+/.test(t.baseURL)&&!F(t.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,t)}get(t){return this.config[t]}getFullUrl(t){return ne(t,this.config.baseURL)}showMessage(t,s,r,o){this.config.messageHandler&&s&&this.config.messageHandler(t,s,r,o)}}var T=(e=>(e.UnexpectResponse="UnexpectResponse",e.Aborted="Aborted",e.Unknown="Unknown",e.NetworkError="NetworkError",e.Timeout="Timeout",e.NotSupport="NotSupport",e.URLFormatError="URLFormatError",e))(T||{});function le(e,t,s,r){if(t.ok&&!te(t.data)&&r){const o=re(r,s.get("defaultTypeGuardMessage"));return o.guard(t.data)||(t.code=T.UnexpectResponse,s.showMessage(!0,`${e} ${o.message}`,t.code,t.status),console.error(t.code,e,t.data),t.data=null,t.message=o.message),t}return t}class he{constructor(t,s){b(this,"agent");b(this,"config");b(this,"cache");this.config=new I(s),this.agent=t,this.cache=new ue(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(t,s){try{return await this.agent(t,this.config,s)}catch(r){return console.error("RequestError",r),{ok:!1,status:-9,code:T.Unknown,message:r instanceof Error?`${r.message}
|
|
2
|
+
${r.stack||""}`:String(r),headers:{},data:null}}}async guard(t,s,r){return le(t,s,this.config,r)}setConfig(t){this.config.set(t),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(t){return this.config.get(t)}async head(t,s){const r=Object.assign({},s||null);return r.method="HEAD",this.guard(t,await this.request(t,r),null)}async get(t,s,r){const o=Object.assign({},r||null);o.method="GET";const n=this.cache.getKey(t,o.params),a=this.cache.get(n);if(a)return this.guard(t,await a,s||null);const i=this.request(t,o);return this.cache.set(n,i),this.guard(t,await i,s||null)}async post(t,s,r,o){const n=Object.assign({},o||null);return n.method="POST",n.body=s||{},this.guard(t,await this.request(t,n),r||null)}async del(t,s,r){const o=Object.assign({},r||null);return o.method="DELETE",this.guard(t,await this.request(t,o),s||null)}async put(t,s,r,o){const n=Object.assign({},o||null);return n.method="PUT",n.body=s||{},this.guard(t,await this.request(t,n),r||null)}async patch(t,s,r,o){const n=Object.assign({},o||null);return n.method="PATCH",n.body=s||{},this.guard(t,await this.request(t,n),r||null)}}async function de(e,t,s){var y;const r=Object.assign({method:"GET"},s),o=R.FormData?r.body instanceof FormData:!1,n=o&&r.method!=="POST"&&r.method!=="PUT"?"POST":r.method,a=n==="GET"||n==="HEAD"||n==="DELETE";a&&r.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete r.body);const i=Object.assign(o||a?{}:{"Content-Type":R.Blob&&r.body instanceof Blob?r.body.type||"application/octet-stream":"application/json;charset=utf-8"},r.headers),u=r.params||{},f={};Object.keys(u).forEach(w=>{u[w]!==void 0&&(f[w]=fe(u[w]))});const l=t.getFullUrl(e),h=ge(r.body),g=r.timeout||t.get("timeout"),m=await async function(){const w=t.get("requestTransformer");if(w)return await w({headers:i,params:f,method:n,url:l,body:h})}(),p=typeof m=="string"&&m?m:l;return(y=t.get("logHandler"))==null||y({type:"ready",url:p,method:n,headers:i,timeout:g,body:h}),{url:p,method:n,body:h,params:f,headers:i,timeout:g,abort:r.abort,credentials:r.credentials||t.get("credentials")}}function fe(e){return typeof e=="string"?e:Array.isArray(e)?e.join(","):e+""}function ge(e){if(e)return typeof e=="string"||e instanceof URLSearchParams||e instanceof ArrayBuffer||R.Blob&&e instanceof Blob||R.FormData&&e instanceof FormData?e:JSON.stringify(e)}const N="data",$="message";function me(e,t,s,r,o){const n=o||r;return S(e)?je(n.ok||r.ok,e,t,s):pe(n.failed||r.failed,t,s)}const ye=function(e){const t=[],s=e.failed||{resolve:"json"};switch(t.push("- 当http状态码 <200 或者 >=400 时"),s.resolve){case"body":t.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":t.push(" 将响应解析为json,并读取 "+(s.messageField||$)+" 作为错误消息");break}const r=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),r.resolve){case"body":t.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(r.dataField||N)+" 作为响应数据,读取 "+(r.messageField||$)+" 作为提示消息"),r.statusField&&t.push(" 当 "+r.statusField+" 为 "+(r.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),r.ignoreMessage&&t.push(" 并忽略以下消息:"+r.ignoreMessage);break}return t.join(`
|
|
3
|
+
`)};function pe(e,t,s){const r=e||{resolve:"json",messageField:$},o={ok:!1,code:t,message:s,data:null};switch(r.resolve){case"body":o.message=L(s)||s;break;case"json":const{code:n,message:a}=be(s,r.converter,r.statusField,r.messageField);o.code=n||t,o.message=L(s)||a;break}return o}function be(e,t,s,r=$){if(!B(e))return{message:""};const o=C(A(e),t);return!o||!v(o)?{message:e}:{code:s?U(o,s):"",message:U(o,r)||e}}function U(e,t){const s=Array.isArray(t)?t:[t];for(const r of s)if(r in e)return we(e[r]);return""}function we(e){return e?typeof e=="string"?e:JSON.stringify(e):""}const Re=/<title>([^<]+)<\/title>/i,$e=/<message>([^<]+)<\/message>/i;function L(e){const t=e.match(Re);if(t)return t[1];const s=e.match($e);return s?s[1]:""}function je(e,t,s,r){const o=e||{resolve:"body"},n={ok:!0,code:s,message:"",data:null};if(t===204||!r)return n;if(o.resolve==="body")return n.data=B(r)?C(A(r),e.converter):r,n;const a=C(A(r),e.converter);if(!a||!v(a))return n.ok=!1,n.code="ResponseFormatError",n.message="响应内容无法格式化为 Object",n;const i=o.statusField,u=o.statusOKValue||"",f=o.dataField||N,l=o.messageField||$,h=o.ignoreMessage||"";if(i&&!(i in a))return n.ok=!1,n.code="ResponseFieldMissing",n.message="响应内容找不到状态字段 "+i,n;const g=i?a[i]+"":"";return n.ok=i?g===u:!0,n.code=g||s,n.data=f===!0?a:f in a?a[f]:null,n.message=U(a,l),h&&n.message&&(Array.isArray(h)&&h.includes(n.message)||typeof h=="string"&&n.message===h)&&(n.message=""),n}function S(e){return e>=200&&e<400}function C(e,t){return t==="camelize"?E(e):t==="snakify"?k(e):e}const Oe=Z("APIError");function Ee(e){const t={};for(const o in e.headers)(o.startsWith("x-")||o.includes("trace")||o.includes("server")||/\b(?:id|uuid)\b/.test(o))&&(t[o]=e.headers[o]);const s=e.url.replace(/^(?:https?:)?\/*/i,"").replace(/\?.+/,""),r=e.status<0?"unknown":e.status;return{sentryError:new Oe(`${s} | ${r}${e.code?` | ${e.code}`:""}`),sentryTags:{...t,status:r,method:e.method,code:e.code||"unknown",message:e.message||"empty"},sentryExtra:{url:e.url,responseBody:e.body||"empty",responseHeaders:e.headers,rawError:e.error}}}function G(e){return e.reduce((t,[s,r])=>(s&&(t[s]=r||""),t),{})}function ke(e,t,s,r){var m;const o=e.status,n=e.method,a=G(Object.entries(e.headers||{}).map(([p,y])=>[p.toLowerCase(),y])),{ok:i,code:u,data:f,message:l}=me(o,e.statusText,e.body,s.get("responseRule"),r==null?void 0:r.responseRule);if(!S(o)){const p=Ee({url:e.url,method:e.method,status:o,code:u,message:l,body:e.body,headers:a,error:e.rawError});(s.get("errorHandler")||Fe)({url:t,method:n,status:o,code:u,message:l,headers:a,rawError:e.rawError,responseBody:e.body,...p})}if(o<0)return P({ok:!1,status:o,code:e.statusText,headers:{},message:"",data:null},`${n} ${t} ${e.statusText}`,n,t,s,r);const h={ok:i,data:f,code:u,message:l,status:o,headers:a};(m=s.get("responseHandler"))==null||m({...h},n,t);const g=i?l:l||e.statusText;return P(h,g,n,t,s,r)}function P(e,t,s,r,o,n){const a=o.get("message"),i=a===!1||(n==null?void 0:n.message)===!1?!1:(n==null?void 0:n.message)||a;if(i!==!1){const u=typeof i=="function"?i(e,s,r,t):t;u instanceof Error?o.showMessage(!0,u.message,e.code,e.status):u&&typeof u=="object"&&"message"in u?o.showMessage(!1,u.message,e.code,e.status):o.showMessage(!e.ok,u,e.code,e.status)}return e}function Fe(e){const t={};for(const s in e)s.startsWith("sentry")||(t[s]=e[s]);console.error("RequestError",t)}async function K(e,t,s,r,o){const n=o||0,a=Math.max(0,Math.min(10,(r==null?void 0:r.maxRetry)??s.get("maxRetry")??0)),i=(r==null?void 0:r.retryResolve)??s.get("retryResolve"),u=s.get("logHandler")||W;u({type:"prepare",url:t,method:(r==null?void 0:r.method)||"GET",retry:n,maxRetry:a,message:n===0?"start":`retry ${n}/${a} start`,headers:r==null?void 0:r.headers,options:r});const f=Date.now(),l=await e(t,s,r),h=l.status,g=Date.now()-f,m=`[cost ${g}][${h}] ${h<0?l.body:""}`;u({type:"finished",url:t,method:l.method,retry:n,maxRetry:a,message:n===0?`finish ${m}`:`retry ${n}/${a} finish ${m}`,response:l,headers:l.headers,cost:g});const p=S(h);if(!a||i==="network"&&h>0||i==="status"&&p||Array.isArray(i)&&!i.includes(h)||typeof i=="function"&&i(l,n)!==!0||n>=a)return l;const y=(r==null?void 0:r.retryInterval)??s.get("retryInterval")??100;return await V(Math.max(100,y==="2EB"?Math.pow(2,n)*100:typeof y=="function"?y(n+1)||0:y)),await K(e,t,s,r,n+1)}exports.$t=F;exports.Ge=se;exports.NetRequestHandler=he;exports.RequestGlobalConfig=I;exports.RequestInternalError=T;exports.Rt=R;exports.convertOptions=de;exports.fromEntries=G;exports.getResponseRulesDescription=ye;exports.handleResponse=ke;exports.le=ce;exports.retryRequest=K;
|