@seayoo-web/request 1.6.6 → 1.7.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 +11 -2
- package/dist/inc/type.d.ts +6 -0
- package/dist/index.cjs +2 -2
- package/dist/index.js +12 -12
- package/dist/node.cjs +1 -1
- package/dist/node.js +7 -7
- package/dist/version-CCXW7_VI.cjs +2 -0
- package/dist/version-DOOsgzgL.js +486 -0
- package/dist/version.d.ts +1 -1
- package/dist/wx.cjs +1 -1
- package/dist/wx.js +3 -3
- package/package.json +2 -2
- package/dist/version-BvWF1NS2.cjs +0 -2
- package/dist/version-Cq5oIhuq.js +0 -454
package/README.md
CHANGED
|
@@ -15,7 +15,8 @@
|
|
|
15
15
|
2. 支持重试配置 maxRetry / retryResolve / retryInterval
|
|
16
16
|
3. 支持响应结果处理策略 responseRule 和通用提示配置
|
|
17
17
|
4. 支持类型守卫 typeGuard
|
|
18
|
-
5.
|
|
18
|
+
5. 支持响应内容命名风格转化(camelize / snakify)
|
|
19
|
+
6. 支持多实例,多端(浏览器,nodejs,微信小程序)
|
|
19
20
|
7. get 请求函数支持并发缓存(默认缓存 500ms)
|
|
20
21
|
8. 函数永不抛错,返回固定解析结构 { ok, data, status, headers, code, message }
|
|
21
22
|
9. 提供 jsonp / jsonx 函数,支持带上传进度的 upload 函数
|
|
@@ -160,7 +161,7 @@ setConfig({ timeout: 5000 })
|
|
|
160
161
|
|
|
161
162
|
说明:用于指定如何解析响应体内容
|
|
162
163
|
|
|
163
|
-
- **FailedRule**: { resolve, statusField?, messageField? }
|
|
164
|
+
- **FailedRule**: { resolve, converter?, statusField?, messageField? }
|
|
164
165
|
|
|
165
166
|
http失败时 (status <200 || status >= 400) 解析策略
|
|
166
167
|
|
|
@@ -168,6 +169,10 @@ setConfig({ timeout: 5000 })
|
|
|
168
169
|
|
|
169
170
|
解析方式,设置为 json(默认),则可以进一步指定错误消息字段;设置为 body 则将整个 body 解析为错误信息;
|
|
170
171
|
|
|
172
|
+
**converter**: "camelize" | "snakify"
|
|
173
|
+
|
|
174
|
+
内容转化方式,默认不转化;设置 "camelize" 则所有字段转成驼峰格式,设置 "snakify" 则所有字段转成蛇形格式
|
|
175
|
+
|
|
171
176
|
**statusField**: string
|
|
172
177
|
|
|
173
178
|
解析错误消息的状态字段,仅在 resolve 为 json 时有效,有值的话会替换 response 的 code
|
|
@@ -184,6 +189,10 @@ setConfig({ timeout: 5000 })
|
|
|
184
189
|
|
|
185
190
|
解析方式,若设置为 json,则可以进一步指定更多字段;若设置为 body(默认),则把整个响应体作为接口返回的数据使用,如果格式化失败,则返回响应的字符串;
|
|
186
191
|
|
|
192
|
+
**converter**: "camelize" | "snakify"
|
|
193
|
+
|
|
194
|
+
内容转化方式,默认不转化;设置 "camelize" 则所有字段转成驼峰格式,设置 "snakify" 则所有字段转成蛇形格式
|
|
195
|
+
|
|
187
196
|
**statusField**: string
|
|
188
197
|
|
|
189
198
|
指定表示自定义状态的字段名,默认是 "code"
|
package/dist/inc/type.d.ts
CHANGED
|
@@ -99,12 +99,16 @@ export type IRequestGlobalConfig = {
|
|
|
99
99
|
* status 当网络错误或者 http状态码错误时(<200 || >=400)重试;
|
|
100
100
|
*/
|
|
101
101
|
export type IRetryResolve = "network" | "status" | number[] | ((response: IRequestBaseResponse, count: number) => boolean);
|
|
102
|
+
/** 响应内容转化器 */
|
|
103
|
+
export type IResponseBodyConverter = "camelize" | "snakify";
|
|
102
104
|
/** 响应内容解析规则配置 */
|
|
103
105
|
export interface IResponseRule {
|
|
104
106
|
/** http失败时 (status <200 || status >= 400) 解析策略 */
|
|
105
107
|
failed: {
|
|
106
108
|
/** 解析方式,如果解析方式为 json,则可以进一步指定错误消息字段 */
|
|
107
109
|
resolve: "json" | "body";
|
|
110
|
+
/** 将响应内容进行风格转化 */
|
|
111
|
+
converter?: IResponseBodyConverter;
|
|
108
112
|
/** 解析错误消息的状态字段,比如 error 或 code,仅在 resolve 为 json 时有效,有值的话会替换 response 的 code */
|
|
109
113
|
statusField?: string;
|
|
110
114
|
/** 解析错误消息的字段,仅在 resolve 为 json 时有效 */
|
|
@@ -124,6 +128,8 @@ export interface IResponseRule {
|
|
|
124
128
|
* 此时 reponse body 被格式化为 json 并作为接口返回的数据使用,如果格式化失败,则返回 body 本身的字符串
|
|
125
129
|
*/
|
|
126
130
|
resolve: "json" | "body";
|
|
131
|
+
/** 将响应内容进行风格转化 */
|
|
132
|
+
converter?: IResponseBodyConverter;
|
|
127
133
|
/** 表示自定义状态的字段名 */
|
|
128
134
|
statusField?: string;
|
|
129
135
|
/** 自定义状态成功时的取值 */
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./version-
|
|
2
|
-
`).forEach(e=>{const r=e.trim();if(!r)return;const i=r.split(":"),o=i[0].trim();o&&(s[o]=(i[1]||"").trim())}),s}const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./version-CCXW7_VI.cjs"),y=async function(n,s,t){const e=await c.convertOptions(n,s,t),r=new URL(e.url),i=e.params;i instanceof Object&&Object.keys(i).forEach(a=>r.searchParams.set(a,i[a]));const o=c.Support.AbortController?new AbortController:null;function l(){o&&!o.signal.aborted&&o.abort()}e.abort&&e.abort.addEventListener("abort",l);const b=e.timeout>0?setTimeout(l,e.timeout):null,g=new Request(r,{method:e.method,headers:Object.keys(e.headers).length>0?new Headers(e.headers):void 0,body:e.body,credentials:e.credentials,signal:o==null?void 0:o.signal,redirect:"follow"});return await fetch(g).then(async a=>({url:r.toString(),method:e.method,status:a.status,statusText:a.statusText,headers:c.fromEntries([...a.headers.entries()]),body:e.method==="HEAD"?"":await a.text()})).catch(a=>({url:r.toString(),method:e.method,status:-1,statusText:o!=null&&o.signal.aborted?"Aborted":"NetworkError",body:String(a)})).finally(()=>{b!==null&&clearTimeout(b),e.abort&&e.abort.removeEventListener("abort",l)})},m=async function(n,s,t){const e=await c.convertOptions(n,s,t),r=e.method,i=t==null?void 0:t.onUploadProgress,o=c.Ut(e.url,e.params);return await new Promise(l=>{let b=null,g=!1;const a=function(){g||(d.abort(),g=!0)};function f(){b!==null&&clearTimeout(b),e.abort&&e.abort.removeEventListener("abort",a)}const d=new XMLHttpRequest;if(d.open(r,o,!0),i){let h=1;d.upload.addEventListener("progress",w=>{h=w.total,i({total:w.total,loaded:w.loaded})}),d.addEventListener("load",()=>{f(),i({loaded:h,total:h}),l({url:o,method:r,status:d.status,statusText:d.statusText,headers:R(d),body:r==="HEAD"?"":d.responseText})})}d.addEventListener("error",()=>{f(),l({url:o,method:r,status:-1,statusText:"Failed",body:""})}),d.addEventListener("abort",()=>{f(),l({url:o,method:r,status:-1,statusText:"Aborted",body:""})}),Object.entries(e.headers).forEach(([h,w])=>{d.setRequestHeader(h,w)}),e.credentials==="include"&&(d.withCredentials=!0),d.send(e.body||void 0),e.abort&&e.abort.addEventListener("abort",a),e.timeout>0&&(b=setTimeout(a,e.timeout))})};function R(n){const s={};if(!n)return s;const t=n.getAllResponseHeaders();return t&&t!=="null"&&t.replace(/\r/g,"").split(`
|
|
2
|
+
`).forEach(e=>{const r=e.trim();if(!r)return;const i=r.split(":"),o=i[0].trim();o&&(s[o]=(i[1]||"").trim())}),s}const T=async function(n,s,t){return c.handleResponse(await c.retryRequest(y,n,s,t),n,s,t)},q=async function(n,s,t){return c.handleResponse(await c.retryRequest(m,n,s,t),n,s,t)};async function H(n,s,t,e){const r=t==null?void 0:t.body,i=(t==null?void 0:t.method)==="PUT"?"PUT":"POST";if(s instanceof Blob){const a=new c.RequestGlobalConfig(e),f=await m(n,a,{...t,method:i,body:s});return c.handleResponse(f,n,a,t)}const o=new FormData,l={...s};r instanceof Object&&Object.entries(r).forEach(([a,f])=>{f instanceof Blob?l[a]=f:Array.isArray(f)?f.forEach((d,h)=>{o.append(`${a}[${h}]`,String(d))}):o.append(a,String(f))});for(const a in l)o.append(a,l[a]);const b=new c.RequestGlobalConfig(e),g=await m(n,b,{...t,method:i,body:o});return c.handleResponse(g,n,b,t)}async function E(n,s,t={}){const e=window;"callback"in t||(t.callback="jsonxData"+Math.random().toString(16).slice(2));const r=t.callback+"";if(!n)return null;const i=c.Ut(n,t,!0);return new Promise(o=>{e[r]=function(l){if(r in window&&delete e[r],s(l))return l;console.warn("response type check faild",n,l),o(null)},c.Ae(i).catch(function(){o(null),delete e[r]})})}async function S(n,s,t={}){const e=window;return"var"in t||(t.var="jsonxData"+Math.random().toString(16).slice(2)),n?await c.Ae(c.Ut(n,t,!0)).then(()=>{const r=e[t.var+""];return s(r)?r:(console.warn("response type check faild",n,r),null)}).catch(()=>null):null}const v=async function(n,s,t){return await H(n,s,t,{baseURL:u.getConfig("baseURL"),logHandler:u.getConfig("logHandler"),errorHandler:u.getConfig("errorHandler"),requestTransformer:u.getConfig("requestTransformer"),messageHandler:u.getConfig("messageHandler"),responseHandler:u.getConfig("responseHandler")})};function p(n){if(!c.Support.window)throw new Error("Default Module Only Support In Browser");return c.Support.fetch?new c.NetRequestHandler(T,n):new c.NetRequestHandler(q,n)}const u=p(),x=u.setConfig,C=u.head,j=u.get,L=u.post,U=u.del,A=u.put,O=u.patch;exports.getResponseRulesDescription=c.getResponseRulesDescription;exports.version=c.version;exports.NetRequest=p;exports.del=U;exports.get=j;exports.head=C;exports.jsonp=E;exports.jsonx=S;exports.patch=O;exports.post=L;exports.put=A;exports.setGlobalConfig=x;exports.upload=v;
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { c as
|
|
2
|
-
import { g as z, v as J } from "./version-
|
|
1
|
+
import { c as E, S as w, f as q, U as p, h as m, r as H, R, A as x, N as T } from "./version-DOOsgzgL.js";
|
|
2
|
+
import { g as z, v as J } from "./version-DOOsgzgL.js";
|
|
3
3
|
const L = async function(n, o, e) {
|
|
4
|
-
const t = await
|
|
4
|
+
const t = await E(n, o, e), r = new URL(t.url), c = t.params;
|
|
5
5
|
c instanceof Object && Object.keys(c).forEach((s) => r.searchParams.set(s, c[s]));
|
|
6
6
|
const a = w.AbortController ? new AbortController() : null;
|
|
7
7
|
function i() {
|
|
@@ -33,7 +33,7 @@ const L = async function(n, o, e) {
|
|
|
33
33
|
f !== null && clearTimeout(f), t.abort && t.abort.removeEventListener("abort", i);
|
|
34
34
|
});
|
|
35
35
|
}, y = async function(n, o, e) {
|
|
36
|
-
const t = await
|
|
36
|
+
const t = await E(n, o, e), r = t.method, c = e == null ? void 0 : e.onUploadProgress, a = p(t.url, t.params);
|
|
37
37
|
return await new Promise((i) => {
|
|
38
38
|
let f = null, h = !1;
|
|
39
39
|
const s = function() {
|
|
@@ -98,7 +98,7 @@ const v = async function(n, o, e) {
|
|
|
98
98
|
}, C = async function(n, o, e) {
|
|
99
99
|
return m(await H(y, n, o, e), n, o, e);
|
|
100
100
|
};
|
|
101
|
-
async function
|
|
101
|
+
async function U(n, o, e, t) {
|
|
102
102
|
const r = e == null ? void 0 : e.body, c = (e == null ? void 0 : e.method) === "PUT" ? "PUT" : "POST";
|
|
103
103
|
if (o instanceof Blob) {
|
|
104
104
|
const s = new R(t), u = await y(n, s, {
|
|
@@ -123,7 +123,7 @@ async function j(n, o, e, t) {
|
|
|
123
123
|
});
|
|
124
124
|
return m(h, n, f, e);
|
|
125
125
|
}
|
|
126
|
-
async function
|
|
126
|
+
async function k(n, o, e = {}) {
|
|
127
127
|
const t = window;
|
|
128
128
|
"callback" in e || (e.callback = "jsonxData" + Math.random().toString(16).slice(2));
|
|
129
129
|
const r = e.callback + "";
|
|
@@ -148,7 +148,7 @@ async function O(n, o, e = {}) {
|
|
|
148
148
|
}).catch(() => null) : null;
|
|
149
149
|
}
|
|
150
150
|
const D = async function(n, o, e) {
|
|
151
|
-
return await
|
|
151
|
+
return await U(n, o, e, {
|
|
152
152
|
baseURL: l.getConfig("baseURL"),
|
|
153
153
|
logHandler: l.getConfig("logHandler"),
|
|
154
154
|
errorHandler: l.getConfig("errorHandler"),
|
|
@@ -157,19 +157,19 @@ const D = async function(n, o, e) {
|
|
|
157
157
|
responseHandler: l.getConfig("responseHandler")
|
|
158
158
|
});
|
|
159
159
|
};
|
|
160
|
-
function
|
|
160
|
+
function A(n) {
|
|
161
161
|
if (!w.window)
|
|
162
162
|
throw new Error("Default Module Only Support In Browser");
|
|
163
|
-
return w.fetch ? new
|
|
163
|
+
return w.fetch ? new T(v, n) : new T(C, n);
|
|
164
164
|
}
|
|
165
|
-
const l =
|
|
165
|
+
const l = A(), P = l.setConfig, M = l.head, N = l.get, F = l.post, B = l.del, X = l.put, G = l.patch;
|
|
166
166
|
export {
|
|
167
|
-
|
|
167
|
+
A as NetRequest,
|
|
168
168
|
B as del,
|
|
169
169
|
N as get,
|
|
170
170
|
z as getResponseRulesDescription,
|
|
171
171
|
M as head,
|
|
172
|
-
|
|
172
|
+
k as jsonp,
|
|
173
173
|
O as jsonx,
|
|
174
174
|
G as patch,
|
|
175
175
|
F as post,
|
package/dist/node.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("node:http"),q=require("node:https"),o=require("./version-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("node:http"),q=require("node:https"),o=require("./version-CCXW7_VI.cjs"),R=async function(n,u,c){return o.handleResponse(await o.retryRequest(w,n,u,c),n,u,c)},w=async function(n,u,c){const t=await o.convertOptions(n,u,c);if(!o.D(t.url))return{url:t.url,method:t.method,status:-1,statusText:"URLFormatError",headers:{},body:""};const f=/^https:\/\//i.test(t.url)?q:y,a=new URL(t.url),i=t.params;i instanceof Object&&Object.keys(i).forEach(r=>a.searchParams.set(r,i[r]));const b=t.method==="HEAD";return new Promise(r=>{const d=f.request(a,{headers:t.headers,method:t.method,timeout:t.timeout>0?t.timeout:void 0},function(e){const p=[];e.on("data",h=>p.push(h)),e.on("end",()=>{const h=o.fromEntries(Object.entries(e.headers).map(([g,m])=>[g.toLowerCase(),Array.isArray(m)?m.join(","):m]));r({url:a.toString(),method:t.method,status:e.statusCode||-1,statusText:e.statusMessage||"Unknown",headers:h,body:b?"":Buffer.concat(p).toString("utf-8")})})});d.on("error",e=>{r({url:a.toString(),method:t.method,status:-1,statusText:e.name||"Unknown",body:e.message})}),d.on("timeout",()=>{r({url:a.toString(),method:t.method,status:-1,statusText:"Timeout",body:""})}),t.body&&d.write(t.body),d.end()})};function l(n){return new o.NetRequestHandler(R,n)}const s=l(),S=s.setConfig,T=s.head,j=s.get,C=s.post,O=s.del,U=s.put,x=s.patch;exports.version=o.version;exports.NetRequest=l;exports.del=O;exports.get=j;exports.head=T;exports.patch=x;exports.post=C;exports.put=U;exports.setGlobalConfig=S;
|
package/dist/node.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import l from "node:http";
|
|
2
2
|
import y from "node:https";
|
|
3
|
-
import { h as R, r as g, c as q,
|
|
4
|
-
import { v as G } from "./version-
|
|
5
|
-
const
|
|
3
|
+
import { h as R, r as g, c as q, D as w, f as x, N as T } from "./version-DOOsgzgL.js";
|
|
4
|
+
import { v as G } from "./version-DOOsgzgL.js";
|
|
5
|
+
const U = async function(s, a, u) {
|
|
6
6
|
return R(await g(j, s, a, u), s, a, u);
|
|
7
7
|
}, j = async function(s, a, u) {
|
|
8
8
|
const t = await q(s, a, u);
|
|
@@ -63,17 +63,17 @@ const T = async function(s, a, u) {
|
|
|
63
63
|
});
|
|
64
64
|
};
|
|
65
65
|
function C(s) {
|
|
66
|
-
return new U
|
|
66
|
+
return new T(U, s);
|
|
67
67
|
}
|
|
68
|
-
const o = C(), O = o.setConfig, S = o.head, A = o.get, H = o.post, k = o.del,
|
|
68
|
+
const o = C(), O = o.setConfig, S = o.head, A = o.get, H = o.post, k = o.del, D = o.put, P = o.patch;
|
|
69
69
|
export {
|
|
70
70
|
C as NetRequest,
|
|
71
71
|
k as del,
|
|
72
72
|
A as get,
|
|
73
73
|
S as head,
|
|
74
|
-
|
|
74
|
+
P as patch,
|
|
75
75
|
H as post,
|
|
76
|
-
|
|
76
|
+
D as put,
|
|
77
77
|
O as setGlobalConfig,
|
|
78
78
|
G as version
|
|
79
79
|
};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var N=Object.defineProperty;var G=(t,e,s)=>e in t?N(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var f=(t,e,s)=>(G(t,typeof e!="symbol"?e+"":e,s),s);const m=typeof globalThis<"u"?globalThis:typeof global<"u"?global:typeof window<"u"?window:{},b={fetch:"fetch"in m,window:"window"in m,FormData:"FormData"in m,Blob:"Blob"in m,wx:"wx"in m,TextDecoder:"TextDecoder"in m,AbortController:"AbortController"in m};function B(t){return t.reduce((e,[s,n])=>(s&&(e[s]=n||""),e),{})}async function J(t,e,s){var g;const n=Object.assign({method:"GET"},s),a=b.FormData?n.body instanceof FormData:!1,r=a&&n.method!=="POST"&&n.method!=="PUT"?"POST":n.method,o=r==="GET"||r==="HEAD"||r==="DELETE";o&&n.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);const c=Object.assign(a||o?{}:{"Content-Type":b.Blob&&n.body instanceof Blob?n.body.type||"application/octet-stream":"application/json;charset=utf-8"},n.headers),i=n.params||{},l={};Object.keys(i).forEach(p=>{i[p]!==void 0&&(l[p]=V(i[p]))});const h=e.getFullUrl(t),u=W(n.body),d=n.timeout||e.get("timeout"),y=await async function(){var E;const p=e.get("requestTransformer");return p?await p({headers:c,params:l,method:r,url:h,body:u}):await((E=e.get("requestHandler"))==null?void 0:E(c,l,r,t))}(),R=typeof y=="string"&&y?y:h;return(g=e.get("logHandler"))==null||g({type:"ready",url:R,method:r,headers:c,timeout:d,body:u}),{url:R,method:r,body:u,params:l,headers:c,timeout:d,abort:n.abort,credentials:n.credentials||e.get("credentials")}}function V(t){return typeof t=="string"?t:Array.isArray(t)?t.join(","):t+""}function W(t){if(t)return typeof t=="string"||t instanceof URLSearchParams||t instanceof ArrayBuffer||b.Blob&&t instanceof Blob||b.FormData&&t instanceof FormData?t:JSON.stringify(t)}function Z(t){return new Promise(e=>setTimeout(e,Math.max(0,t)))}function z(){}function j(t){return t?t[0].toLowerCase()+t.slice(1):""}const P=/_\w*/,S=/-\w*/;function D(t){const e=P.test(t)?t.replace(/(?:^_*|_*$)/g,"").replace(/_+([^_])/g,(s,n)=>n.toUpperCase()):S.test(t)?t.replace(/(?:^-*|-*$)/g,"").replace(/-+(\w)/g,(s,n)=>n.toUpperCase()):t;return j(e)}function M(t){return P.test(t)?j(t).replace(/(?:^_*|_*$)/g,"").replace(/_+([^_])/g,(e,s)=>"_"+s.toLowerCase()):S.test(t)?j(t.replace(/(?:^-*|-*$)/g,"")).replace(/-+(\w)/g,(e,s)=>"_"+s.toLowerCase()):j(t).replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}const Q=/^(?:https?:)?\/\/.+$/i,X=/^https?:\/\/.+$/i,Y=/^\{[\d\D]*\}$/,ee=/^\[[\d\D]*\]$/;function v(t,e=!1){return e?Q.test(t):X.test(t)}function te(t){return t==null}function F(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 H(t){return Y.test(t)||ee.test(t)}function k(t,e){try{const s=JSON.parse(t);return e?e(s)?s:null:s}catch{return null}}""+Math.random().toString(32).slice(2);function $(t,e=!1){return typeof t=="string"?D(t):Array.isArray(t)?t.map(s=>!e||typeof s=="string"?$(s):typeof s=="object"&&s?$(s,!0):s):F(t)?Object.keys(t).reduce((s,n)=>{const a=D(String(n)),r=a.charAt(0).toLowerCase()+a.slice(1);return s[r]=e?t[n]:$(t[n]),s},{}):t}function O(t,e=!1){return typeof t=="string"?M(t):Array.isArray(t)?t.map(s=>!e||typeof s=="string"?O(s):typeof s=="object"&&s?O(s,e):s):F(t)?Object.keys(t).reduce((s,n)=>{const a=M(String(n));return s[a]=e?t[n]:O(t[n]),s},{}):t}async function se(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 ne(t,e="数据未能正确识别"){return typeof t=="function"?{guard:t,message:e}:{guard:t.guard,message:t.message||e}}function L(t,e=""){return!e||v(t,!0)?U(t):(U(e)+"/"+t).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function U(t){return v(t,!0)?t.startsWith("http")?t:("location"in globalThis?location.protocol:"https:")+t:("location"in globalThis?location.origin:"http://127.0.0.1")+"/"+t.replace(/^\/+/,"")}function re(t,e){if(e){if(e===!0)return t.replace(/\?[^#]*/,"")}else return t;const s=t.split("#"),n=s[0].split("?"),a=n[0],r=n.length>1?n[1]:"",o=s.length>1?"#"+s[1]:"",c=typeof e=="string"?[e]:Array.isArray(e)?e:[];return!c.length||!r?s[0]+o:(c.map(i=>i.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(a+"?"+r.replace(new RegExp("(?:^|&)(?:"+c.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+o)}function ae(t,e,s=!1){const n=typeof e=="string"?e:Object.keys(e).map(o=>`${o}=${encodeURIComponent(e[o])}`).join("&");if(!n)return t;const a=t.split("#");s&&(a[0]=re(a[0],(n.match(/([^=&#?]+)=[^&#]+/g)||[]).map(o=>o.replace(/=.+$/,""))));const r=a[0].indexOf("?")+1?"&":"?";return(a[0]+r+n+(a.length>1?"#"+a[1]:"")).replace(/\?&/,"?")}const q="data",w="message";function oe(t,e,s,n,a){const r=a||n;return T(t)?ge(r.ok||n.ok,t,e,s):ie(r.failed||n.failed,e,s)}const ce=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||w)+" 作为错误消息");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||q)+" 作为响应数据,读取 "+(n.messageField||w)+" 作为提示消息"),n.statusField&&e.push(" 当 "+n.statusField+" 为 "+(n.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&e.push(" 并忽略以下消息:"+n.ignoreMessage);break}return e.join(`
|
|
2
|
+
`)};function ie(t,e,s){const n=t||{resolve:"json",messageField:w},a={ok:!1,code:e,message:s,data:null};switch(n.resolve){case"body":a.message=x(s)||s;break;case"json":const{code:r,message:o}=ue(s,n.converter,n.statusField,n.messageField);a.code=r||e,a.message=x(s)||o;break}return a}function ue(t,e,s,n=w){if(!H(t))return{message:""};const a=A(k(t),e);return!a||!F(a)?{message:t}:{code:s?C(a,s):"",message:C(a,n)||t}}function C(t,e){const s=Array.isArray(e)?e:[e];for(const n of s)if(n in t)return le(t[n]);return""}function le(t){return t?typeof t=="string"?t:JSON.stringify(t):""}const he=/<title>([^<]+)<\/title>/i,de=/<message>([^<]+)<\/message>/i;function x(t){const e=t.match(he);if(e)return e[1];const s=t.match(de);return s?s[1]:""}function ge(t,e,s,n){const a=t||{resolve:"body"},r={ok:!0,code:s,message:"",data:null};if(e===204||!n)return r;if(a.resolve==="body")return r.data=H(n)?A(k(n),t.converter):n,r;const o=A(k(n),t.converter);if(!o||!F(o))return r.ok=!1,r.code="ResponseFormatError",r.message="响应内容无法格式化为 Object",r;const c=a.statusField,i=a.statusOKValue||"",l=a.dataField||q,h=a.messageField||w,u=a.ignoreMessage||"";if(c&&!(c in o))return r.ok=!1,r.code="ResponseFieldMissing",r.message="响应内容找不到状态字段 "+c,r;const d=c?o[c]+"":"";return r.ok=c?d===i:!0,r.code=d||s,r.data=l===!0?o:l in o?o[l]:null,r.message=C(o,h),u&&r.message&&(Array.isArray(u)&&u.includes(r.message)||typeof u=="string"&&r.message===u)&&(r.message=""),r}function T(t){return t>=200&&t<400}function A(t,e){return e==="camelize"?$(t):e==="snakify"?O(t):t}async function K(t,e,s,n,a){const r=a||0,o=Math.max(0,Math.min(10,(n==null?void 0:n.maxRetry)??s.get("maxRetry")??0)),c=(n==null?void 0:n.retryResolve)??s.get("retryResolve"),i=s.get("logHandler")||z;i({type:"prepear",url:e,method:(n==null?void 0:n.method)||"GET",retry:r,maxRetry:o,message:r===0?"start":`retry ${r}/${o} start`,headers:n==null?void 0:n.headers,options:n});const l=Date.now(),h=await t(e,s,n),u=h.status,d=Date.now()-l,y=`[cost ${d}][${u}] ${u<0?h.body:""}`;i({type:"finished",url:e,method:h.method,retry:r,maxRetry:o,message:r===0?`finish ${y}`:`retry ${r}/${o} finish ${y}`,response:h,headers:h.headers,cost:d});const R=T(u);if(!o||c==="network"&&u>0||c==="status"&&R||Array.isArray(c)&&!c.includes(u)||typeof c=="function"&&c(h,r)!==!0||r>=o)return h;const g=(n==null?void 0:n.retryInterval)??s.get("retryInterval")??1e3;return await Z(Math.max(100,g==="2EB"?Math.pow(2,r)*1e3:typeof g=="function"?g(r+1)||0:g)),await K(t,e,s,n,r+1)}function fe(t,e,s,n){var o,c;if(t.status<0)return _({ok:!1,status:t.status,code:t.statusText,headers:{},message:"",data:null},`${t.method} ${e} ${t.statusText}`,t.method,e,s,n);T(t.status)||(o=s.get("errorHandler"))==null||o(t.status,t.method,e);const a={...oe(t.status,t.statusText,t.body,s.get("responseRule"),n==null?void 0:n.responseRule),status:t.status,headers:B(Object.entries(t.headers||{}).map(([i,l])=>[i.toLowerCase(),l]))};(c=s.get("responseHandler"))==null||c({...a},t.method,e);const r=a.ok?a.message:`${t.method} ${e} [${a.code||t.statusText}] ${a.message||t.statusText}`;return _(a,r,t.method,e,s,n)}function _(t,e,s,n,a,r){const o=a.get("message"),c=o===!1||(r==null?void 0:r.message)===!1?!1:(r==null?void 0:r.message)||o;if(c!==!1){const i=typeof c=="function"?c(t,s,n,e):e;i instanceof Error?a.showMessage(!0,i.message):i&&typeof i=="object"&&"message"in i?a.showMessage(!1,i.message):a.showMessage(!t.ok,i)}return t}class I{constructor(e){f(this,"config",{baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}});e&&this.set(e)}set(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!v(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)}get(e){return this.config[e]}getFullUrl(e){return e.startsWith("/")?L(e):L(e,this.config.baseURL)}showMessage(e,s){this.config.messageHandler&&s&&this.config.messageHandler(e,s)}}class me{constructor(e=500){f(this,"ttl");f(this,"cache");this.cache={},this.ttl=Math.max(e,0)}getKey(e,s){const n=Object.keys(s||{}).sort().map(a=>`${a}#${s==null?void 0:s[a]}`);return e+n.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){this.ttl!==0&&(this.cache[e]={ttl:Date.now()+this.ttl,res:s})}}function ye(t,e,s,n){if(e.ok&&!te(e.data)&&n){const a=ne(n,"响应数据未能正确识别");return a.guard(e.data)||(console.error("ResponseCheckFaild",t,e.data),s.showMessage(!0,`${t} ${a.message}`),e.data=null),e}return e}class pe{constructor(e,s){f(this,"agent");f(this,"config");f(this,"cache");this.config=new I(s),this.agent=e,this.cache=new me(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this),this.head=this.head.bind(this)}async exec(e,s){try{return await this.agent(e,this.config,s)}catch(n){return console.error("RequestError",n),{ok:!1,status:-9,code:"Unkonwn",message:String(n),headers:{},data:null}}}async guard(e,s,n){return ye(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.exec(e,n),null)}async get(e,s,n){const a=Object.assign({},n||null);a.method="GET";const r=this.cache.getKey(e,a.params),o=this.cache.get(r);if(o)return this.guard(e,await o,s||null);const c=this.exec(e,a);return this.cache.set(r,c),this.guard(e,await c,s||null)}async post(e,s,n,a){const r=Object.assign({},a||null);return r.method="POST",r.body=s,this.guard(e,await this.exec(e,r),n||null)}async del(e,s,n){const a=Object.assign({},n||null);return a.method="DELETE",this.guard(e,await this.exec(e,a),s||null)}async put(e,s,n,a){const r=Object.assign({},a||null);return r.method="PUT",r.body=s,this.guard(e,await this.exec(e,r),n||null)}async patch(e,s,n,a){const r=Object.assign({},a||null);return r.method="PATCH",r.body=s,this.guard(e,await this.exec(e,r),n||null)}}const be="1.7.0";exports.Ae=se;exports.D=v;exports.NetRequestHandler=pe;exports.RequestGlobalConfig=I;exports.Support=b;exports.Ut=ae;exports.convertOptions=J;exports.fromEntries=B;exports.getResponseRulesDescription=ce;exports.handleResponse=fe;exports.retryRequest=K;exports.version=be;
|
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
var q = Object.defineProperty;
|
|
2
|
+
var K = (t, e, s) => e in t ? q(t, e, { enumerable: !0, configurable: !0, writable: !0, value: s }) : t[e] = s;
|
|
3
|
+
var f = (t, e, s) => (K(t, typeof e != "symbol" ? e + "" : e, s), s);
|
|
4
|
+
const m = typeof globalThis < "u" ? globalThis : typeof global < "u" ? global : typeof window < "u" ? window : {}, O = {
|
|
5
|
+
fetch: "fetch" in m,
|
|
6
|
+
window: "window" in m,
|
|
7
|
+
FormData: "FormData" in m,
|
|
8
|
+
Blob: "Blob" in m,
|
|
9
|
+
wx: "wx" in m,
|
|
10
|
+
TextDecoder: "TextDecoder" in m,
|
|
11
|
+
AbortController: "AbortController" in m
|
|
12
|
+
};
|
|
13
|
+
function I(t) {
|
|
14
|
+
return t.reduce(
|
|
15
|
+
(e, [s, n]) => (s && (e[s] = n || ""), e),
|
|
16
|
+
{}
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
async function ge(t, e, s) {
|
|
20
|
+
var g;
|
|
21
|
+
const n = Object.assign({ method: "GET" }, s), a = O.FormData ? n.body instanceof FormData : !1, r = a && n.method !== "POST" && n.method !== "PUT" ? "POST" : n.method, o = r === "GET" || r === "HEAD" || r === "DELETE";
|
|
22
|
+
o && n.body !== void 0 && (console.warn("request body is invalid with method get, head, delete"), delete n.body);
|
|
23
|
+
const c = Object.assign(
|
|
24
|
+
a || o ? {} : {
|
|
25
|
+
"Content-Type": O.Blob && n.body instanceof Blob ? n.body.type || "application/octet-stream" : "application/json;charset=utf-8"
|
|
26
|
+
},
|
|
27
|
+
n.headers
|
|
28
|
+
), i = n.params || {}, l = {};
|
|
29
|
+
Object.keys(i).forEach((p) => {
|
|
30
|
+
i[p] !== void 0 && (l[p] = N(i[p]));
|
|
31
|
+
});
|
|
32
|
+
const h = e.getFullUrl(t), u = J(n.body), d = n.timeout || e.get("timeout"), y = await async function() {
|
|
33
|
+
var E;
|
|
34
|
+
const p = e.get("requestTransformer");
|
|
35
|
+
return p ? await p({ headers: c, params: l, method: r, url: h, body: u }) : await ((E = e.get("requestHandler")) == null ? void 0 : E(c, l, r, t));
|
|
36
|
+
}(), w = typeof y == "string" && y ? y : h;
|
|
37
|
+
return (g = e.get("logHandler")) == null || g({ type: "ready", url: w, method: r, headers: c, timeout: d, body: u }), {
|
|
38
|
+
url: w,
|
|
39
|
+
method: r,
|
|
40
|
+
body: u,
|
|
41
|
+
params: l,
|
|
42
|
+
headers: c,
|
|
43
|
+
timeout: d,
|
|
44
|
+
abort: n.abort,
|
|
45
|
+
credentials: n.credentials || e.get("credentials")
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function N(t) {
|
|
49
|
+
return typeof t == "string" ? t : Array.isArray(t) ? t.join(",") : t + "";
|
|
50
|
+
}
|
|
51
|
+
function J(t) {
|
|
52
|
+
if (t)
|
|
53
|
+
return typeof t == "string" || t instanceof URLSearchParams || t instanceof ArrayBuffer || O.Blob && t instanceof Blob || O.FormData && t instanceof FormData ? t : JSON.stringify(t);
|
|
54
|
+
}
|
|
55
|
+
function G(t) {
|
|
56
|
+
return new Promise((e) => setTimeout(e, Math.max(0, t)));
|
|
57
|
+
}
|
|
58
|
+
function V() {
|
|
59
|
+
}
|
|
60
|
+
function R(t) {
|
|
61
|
+
return t ? t[0].toLowerCase() + t.slice(1) : "";
|
|
62
|
+
}
|
|
63
|
+
const B = /_\w*/, P = /-\w*/;
|
|
64
|
+
function M(t) {
|
|
65
|
+
const e = B.test(t) ? t.replace(/(?:^_*|_*$)/g, "").replace(/_+([^_])/g, (s, n) => n.toUpperCase()) : P.test(t) ? t.replace(/(?:^-*|-*$)/g, "").replace(/-+(\w)/g, (s, n) => n.toUpperCase()) : t;
|
|
66
|
+
return R(e);
|
|
67
|
+
}
|
|
68
|
+
function D(t) {
|
|
69
|
+
return B.test(t) ? R(t).replace(/(?:^_*|_*$)/g, "").replace(/_+([^_])/g, (e, s) => "_" + s.toLowerCase()) : P.test(t) ? R(t.replace(/(?:^-*|-*$)/g, "")).replace(/-+(\w)/g, (e, s) => "_" + s.toLowerCase()) : R(t).replace(/[A-Z]/g, (e) => `_${e.toLowerCase()}`);
|
|
70
|
+
}
|
|
71
|
+
const W = /^(?:https?:)?\/\/.+$/i, Z = /^https?:\/\/.+$/i, z = /^\{[\d\D]*\}$/, Q = /^\[[\d\D]*\]$/;
|
|
72
|
+
function C(t, e = !1) {
|
|
73
|
+
return e ? W.test(t) : Z.test(t);
|
|
74
|
+
}
|
|
75
|
+
function X(t) {
|
|
76
|
+
return t == null;
|
|
77
|
+
}
|
|
78
|
+
function v(t, ...e) {
|
|
79
|
+
if (!t || typeof t != "object")
|
|
80
|
+
return !1;
|
|
81
|
+
const s = Object.getPrototypeOf(t);
|
|
82
|
+
return s !== Object.prototype && s !== null ? !1 : e.every((n) => n in t);
|
|
83
|
+
}
|
|
84
|
+
function S(t) {
|
|
85
|
+
return z.test(t) || Q.test(t);
|
|
86
|
+
}
|
|
87
|
+
function F(t, e) {
|
|
88
|
+
try {
|
|
89
|
+
const s = JSON.parse(t);
|
|
90
|
+
return e ? e(s) ? s : null : s;
|
|
91
|
+
} catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
"" + Math.random().toString(32).slice(2);
|
|
96
|
+
function j(t, e = !1) {
|
|
97
|
+
return typeof t == "string" ? M(t) : Array.isArray(t) ? t.map((s) => !e || typeof s == "string" ? j(s) : typeof s == "object" && s ? j(s, !0) : s) : v(t) ? Object.keys(t).reduce(
|
|
98
|
+
(s, n) => {
|
|
99
|
+
const a = M(String(n)), r = a.charAt(0).toLowerCase() + a.slice(1);
|
|
100
|
+
return s[r] = e ? t[n] : j(t[n]), s;
|
|
101
|
+
},
|
|
102
|
+
{}
|
|
103
|
+
) : t;
|
|
104
|
+
}
|
|
105
|
+
function $(t, e = !1) {
|
|
106
|
+
return typeof t == "string" ? D(t) : Array.isArray(t) ? t.map((s) => !e || typeof s == "string" ? $(s) : typeof s == "object" && s ? $(s, e) : s) : v(t) ? Object.keys(t).reduce(
|
|
107
|
+
(s, n) => {
|
|
108
|
+
const a = D(String(n));
|
|
109
|
+
return s[a] = e ? t[n] : $(t[n]), s;
|
|
110
|
+
},
|
|
111
|
+
{}
|
|
112
|
+
) : t;
|
|
113
|
+
}
|
|
114
|
+
async function fe(t) {
|
|
115
|
+
return await new Promise(function(e) {
|
|
116
|
+
const s = document.getElementsByTagName("head")[0], n = document.createElement("script");
|
|
117
|
+
n.setAttribute("type", "text/javascript"), n.setAttribute("charset", "utf-8"), n.onload = function() {
|
|
118
|
+
s.removeChild(n), e(!0);
|
|
119
|
+
}, n.onerror = function() {
|
|
120
|
+
s.removeChild(n), e(!1);
|
|
121
|
+
}, n.setAttribute("src", t), s.appendChild(n);
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
function Y(t, e = "数据未能正确识别") {
|
|
125
|
+
return typeof t == "function" ? {
|
|
126
|
+
guard: t,
|
|
127
|
+
message: e
|
|
128
|
+
} : {
|
|
129
|
+
guard: t.guard,
|
|
130
|
+
message: t.message || e
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
function L(t, e = "") {
|
|
134
|
+
return !e || C(t, !0) ? U(t) : (U(e) + "/" + t).replace(/\/{2,}/g, "/").replace(/:\//, "://");
|
|
135
|
+
}
|
|
136
|
+
function U(t) {
|
|
137
|
+
return C(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(/^\/+/, "");
|
|
138
|
+
}
|
|
139
|
+
function ee(t, e) {
|
|
140
|
+
if (e) {
|
|
141
|
+
if (e === !0)
|
|
142
|
+
return t.replace(/\?[^#]*/, "");
|
|
143
|
+
} else
|
|
144
|
+
return t;
|
|
145
|
+
const s = t.split("#"), n = s[0].split("?"), a = n[0], r = n.length > 1 ? n[1] : "", o = s.length > 1 ? "#" + s[1] : "", c = typeof e == "string" ? [e] : Array.isArray(e) ? e : [];
|
|
146
|
+
return !c.length || !r ? s[0] + o : (c.map((i) => i.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (a + "?" + r.replace(new RegExp("(?:^|&)(?:" + c.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + o);
|
|
147
|
+
}
|
|
148
|
+
function me(t, e, s = !1) {
|
|
149
|
+
const n = typeof e == "string" ? e : Object.keys(e).map((o) => `${o}=${encodeURIComponent(e[o])}`).join("&");
|
|
150
|
+
if (!n)
|
|
151
|
+
return t;
|
|
152
|
+
const a = t.split("#");
|
|
153
|
+
s && (a[0] = ee(
|
|
154
|
+
a[0],
|
|
155
|
+
(n.match(/([^=&#?]+)=[^&#]+/g) || []).map((o) => o.replace(/=.+$/, ""))
|
|
156
|
+
));
|
|
157
|
+
const r = a[0].indexOf("?") + 1 ? "&" : "?";
|
|
158
|
+
return (a[0] + r + n + (a.length > 1 ? "#" + a[1] : "")).replace(/\?&/, "?");
|
|
159
|
+
}
|
|
160
|
+
const H = "data", b = "message";
|
|
161
|
+
function te(t, e, s, n, a) {
|
|
162
|
+
const r = a || n;
|
|
163
|
+
return T(t) ? ce(r.ok || n.ok, t, e, s) : se(r.failed || n.failed, e, s);
|
|
164
|
+
}
|
|
165
|
+
const ye = function(t) {
|
|
166
|
+
const e = [], s = t.failed || { resolve: "json" };
|
|
167
|
+
switch (e.push("- 当http状态码 <200 或者 >=400 时"), s.resolve) {
|
|
168
|
+
case "body":
|
|
169
|
+
e.push(" 将响应内容格式化为字符串并作为错误消息");
|
|
170
|
+
break;
|
|
171
|
+
case "json":
|
|
172
|
+
e.push(" 将响应解析为json,并读取 " + (s.messageField || b) + " 作为错误消息");
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
const n = t.ok || { resolve: "body" };
|
|
176
|
+
switch (e.push("- 当http状态码 >=200 并且 <400 时"), n.resolve) {
|
|
177
|
+
case "body":
|
|
178
|
+
e.push(" 将响应尝试解析为 json,并作为数据内容返回");
|
|
179
|
+
break;
|
|
180
|
+
case "json":
|
|
181
|
+
e.push(
|
|
182
|
+
" 将响应解析为 json,读取 " + (n.dataField || H) + " 作为响应数据,读取 " + (n.messageField || b) + " 作为提示消息"
|
|
183
|
+
), n.statusField && e.push(" 当 " + n.statusField + " 为 " + (n.statusOKValue || "空值") + " 时是成功提示,否则是错误消息"), n.ignoreMessage && e.push(" 并忽略以下消息:" + n.ignoreMessage);
|
|
184
|
+
break;
|
|
185
|
+
}
|
|
186
|
+
return e.join(`
|
|
187
|
+
`);
|
|
188
|
+
};
|
|
189
|
+
function se(t, e, s) {
|
|
190
|
+
const n = t || { resolve: "json", messageField: b }, a = {
|
|
191
|
+
ok: !1,
|
|
192
|
+
code: e,
|
|
193
|
+
message: s,
|
|
194
|
+
data: null
|
|
195
|
+
};
|
|
196
|
+
switch (n.resolve) {
|
|
197
|
+
case "body":
|
|
198
|
+
a.message = x(s) || s;
|
|
199
|
+
break;
|
|
200
|
+
case "json":
|
|
201
|
+
const { code: r, message: o } = ne(s, n.converter, n.statusField, n.messageField);
|
|
202
|
+
a.code = r || e, a.message = x(s) || o;
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
return a;
|
|
206
|
+
}
|
|
207
|
+
function ne(t, e, s, n = b) {
|
|
208
|
+
if (!S(t))
|
|
209
|
+
return { message: "" };
|
|
210
|
+
const a = A(F(t), e);
|
|
211
|
+
return !a || !v(a) ? { message: t } : {
|
|
212
|
+
code: s ? k(a, s) : "",
|
|
213
|
+
message: k(a, n) || t
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
function k(t, e) {
|
|
217
|
+
const s = Array.isArray(e) ? e : [e];
|
|
218
|
+
for (const n of s)
|
|
219
|
+
if (n in t)
|
|
220
|
+
return re(t[n]);
|
|
221
|
+
return "";
|
|
222
|
+
}
|
|
223
|
+
function re(t) {
|
|
224
|
+
return t ? typeof t == "string" ? t : JSON.stringify(t) : "";
|
|
225
|
+
}
|
|
226
|
+
const ae = /<title>([^<]+)<\/title>/i, oe = /<message>([^<]+)<\/message>/i;
|
|
227
|
+
function x(t) {
|
|
228
|
+
const e = t.match(ae);
|
|
229
|
+
if (e)
|
|
230
|
+
return e[1];
|
|
231
|
+
const s = t.match(oe);
|
|
232
|
+
return s ? s[1] : "";
|
|
233
|
+
}
|
|
234
|
+
function ce(t, e, s, n) {
|
|
235
|
+
const a = t || { resolve: "body" }, r = {
|
|
236
|
+
ok: !0,
|
|
237
|
+
code: s,
|
|
238
|
+
message: "",
|
|
239
|
+
data: null
|
|
240
|
+
};
|
|
241
|
+
if (e === 204 || !n)
|
|
242
|
+
return r;
|
|
243
|
+
if (a.resolve === "body")
|
|
244
|
+
return r.data = S(n) ? A(F(n), t.converter) : n, r;
|
|
245
|
+
const o = A(F(n), t.converter);
|
|
246
|
+
if (!o || !v(o))
|
|
247
|
+
return r.ok = !1, r.code = "ResponseFormatError", r.message = "响应内容无法格式化为 Object", r;
|
|
248
|
+
const c = a.statusField, i = a.statusOKValue || "", l = a.dataField || H, h = a.messageField || b, u = a.ignoreMessage || "";
|
|
249
|
+
if (c && !(c in o))
|
|
250
|
+
return r.ok = !1, r.code = "ResponseFieldMissing", r.message = "响应内容找不到状态字段 " + c, r;
|
|
251
|
+
const d = c ? o[c] + "" : "";
|
|
252
|
+
return r.ok = c ? d === i : !0, r.code = d || s, r.data = l === !0 ? o : l in o ? o[l] : null, r.message = k(o, h), u && r.message && (Array.isArray(u) && u.includes(r.message) || typeof u == "string" && r.message === u) && (r.message = ""), r;
|
|
253
|
+
}
|
|
254
|
+
function T(t) {
|
|
255
|
+
return t >= 200 && t < 400;
|
|
256
|
+
}
|
|
257
|
+
function A(t, e) {
|
|
258
|
+
return e === "camelize" ? j(t) : e === "snakify" ? $(t) : t;
|
|
259
|
+
}
|
|
260
|
+
async function ie(t, e, s, n, a) {
|
|
261
|
+
const r = a || 0, o = Math.max(0, Math.min(10, (n == null ? void 0 : n.maxRetry) ?? s.get("maxRetry") ?? 0)), c = (n == null ? void 0 : n.retryResolve) ?? s.get("retryResolve"), i = s.get("logHandler") || V;
|
|
262
|
+
i({
|
|
263
|
+
type: "prepear",
|
|
264
|
+
url: e,
|
|
265
|
+
method: (n == null ? void 0 : n.method) || "GET",
|
|
266
|
+
retry: r,
|
|
267
|
+
maxRetry: o,
|
|
268
|
+
message: r === 0 ? "start" : `retry ${r}/${o} start`,
|
|
269
|
+
headers: n == null ? void 0 : n.headers,
|
|
270
|
+
options: n
|
|
271
|
+
});
|
|
272
|
+
const l = Date.now(), h = await t(e, s, n), u = h.status, d = Date.now() - l, y = `[cost ${d}][${u}] ${u < 0 ? h.body : ""}`;
|
|
273
|
+
i({
|
|
274
|
+
type: "finished",
|
|
275
|
+
url: e,
|
|
276
|
+
method: h.method,
|
|
277
|
+
retry: r,
|
|
278
|
+
maxRetry: o,
|
|
279
|
+
message: r === 0 ? `finish ${y}` : `retry ${r}/${o} finish ${y}`,
|
|
280
|
+
response: h,
|
|
281
|
+
headers: h.headers,
|
|
282
|
+
cost: d
|
|
283
|
+
});
|
|
284
|
+
const w = T(u);
|
|
285
|
+
if (!o || c === "network" && u > 0 || c === "status" && w || Array.isArray(c) && !c.includes(u) || typeof c == "function" && c(h, r) !== !0 || r >= o)
|
|
286
|
+
return h;
|
|
287
|
+
const g = (n == null ? void 0 : n.retryInterval) ?? s.get("retryInterval") ?? 1e3;
|
|
288
|
+
return await G(
|
|
289
|
+
Math.max(
|
|
290
|
+
100,
|
|
291
|
+
g === "2EB" ? Math.pow(2, r) * 1e3 : typeof g == "function" ? g(r + 1) || 0 : g
|
|
292
|
+
)
|
|
293
|
+
), await ie(t, e, s, n, r + 1);
|
|
294
|
+
}
|
|
295
|
+
function pe(t, e, s, n) {
|
|
296
|
+
var o, c;
|
|
297
|
+
if (t.status < 0)
|
|
298
|
+
return _(
|
|
299
|
+
{ ok: !1, status: t.status, code: t.statusText, headers: {}, message: "", data: null },
|
|
300
|
+
`${t.method} ${e} ${t.statusText}`,
|
|
301
|
+
t.method,
|
|
302
|
+
e,
|
|
303
|
+
s,
|
|
304
|
+
n
|
|
305
|
+
);
|
|
306
|
+
T(t.status) || (o = s.get("errorHandler")) == null || o(t.status, t.method, e);
|
|
307
|
+
const a = {
|
|
308
|
+
...te(t.status, t.statusText, t.body, s.get("responseRule"), n == null ? void 0 : n.responseRule),
|
|
309
|
+
status: t.status,
|
|
310
|
+
headers: I(Object.entries(t.headers || {}).map(([i, l]) => [i.toLowerCase(), l]))
|
|
311
|
+
};
|
|
312
|
+
(c = s.get("responseHandler")) == null || c({ ...a }, t.method, e);
|
|
313
|
+
const r = a.ok ? a.message : `${t.method} ${e} [${a.code || t.statusText}] ${a.message || t.statusText}`;
|
|
314
|
+
return _(a, r, t.method, e, s, n);
|
|
315
|
+
}
|
|
316
|
+
function _(t, e, s, n, a, r) {
|
|
317
|
+
const o = a.get("message"), c = o === !1 || (r == null ? void 0 : r.message) === !1 ? !1 : (r == null ? void 0 : r.message) || o;
|
|
318
|
+
if (c !== !1) {
|
|
319
|
+
const i = typeof c == "function" ? c(t, s, n, e) : e;
|
|
320
|
+
i instanceof Error ? a.showMessage(!0, i.message) : i && typeof i == "object" && "message" in i ? a.showMessage(!1, i.message) : a.showMessage(!t.ok, i);
|
|
321
|
+
}
|
|
322
|
+
return t;
|
|
323
|
+
}
|
|
324
|
+
class ue {
|
|
325
|
+
constructor(e) {
|
|
326
|
+
// 保存的配置需要部分字段强制设置默认值
|
|
327
|
+
f(this, "config", {
|
|
328
|
+
baseURL: "",
|
|
329
|
+
maxRetry: 0,
|
|
330
|
+
retryInterval: 1e3,
|
|
331
|
+
retryResolve: "network",
|
|
332
|
+
timeout: 5e3,
|
|
333
|
+
cacheTTL: 500,
|
|
334
|
+
credentials: "same-origin",
|
|
335
|
+
responseRule: {
|
|
336
|
+
ok: {
|
|
337
|
+
resolve: "body"
|
|
338
|
+
},
|
|
339
|
+
failed: {
|
|
340
|
+
resolve: "json",
|
|
341
|
+
messageField: "message"
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
});
|
|
345
|
+
e && this.set(e);
|
|
346
|
+
}
|
|
347
|
+
set(e) {
|
|
348
|
+
if (e.baseURL && !/^\/.+/.test(e.baseURL) && !C(e.baseURL))
|
|
349
|
+
throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"), new Error("BaseURLError");
|
|
350
|
+
Object.assign(this.config, e);
|
|
351
|
+
}
|
|
352
|
+
get(e) {
|
|
353
|
+
return this.config[e];
|
|
354
|
+
}
|
|
355
|
+
/** 基于 baseURL 返回完整的 url 地址, 如果 url 地址以 / 开头则表示忽略 baseURL 的值 */
|
|
356
|
+
getFullUrl(e) {
|
|
357
|
+
return e.startsWith("/") ? L(e) : L(e, this.config.baseURL);
|
|
358
|
+
}
|
|
359
|
+
/** 提示消息 */
|
|
360
|
+
showMessage(e, s) {
|
|
361
|
+
this.config.messageHandler && s && this.config.messageHandler(e, s);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
class le {
|
|
365
|
+
constructor(e = 500) {
|
|
366
|
+
f(this, "ttl");
|
|
367
|
+
f(this, "cache");
|
|
368
|
+
this.cache = {}, this.ttl = Math.max(e, 0);
|
|
369
|
+
}
|
|
370
|
+
getKey(e, s) {
|
|
371
|
+
const n = Object.keys(s || {}).sort().map((a) => `${a}#${s == null ? void 0 : s[a]}`);
|
|
372
|
+
return e + n.join(",");
|
|
373
|
+
}
|
|
374
|
+
updateTTL(e) {
|
|
375
|
+
this.ttl = Math.max(e, 0);
|
|
376
|
+
}
|
|
377
|
+
get(e) {
|
|
378
|
+
if (this.ttl === 0)
|
|
379
|
+
return null;
|
|
380
|
+
const s = this.cache[e];
|
|
381
|
+
return s ? s.ttl < Date.now() ? (delete this.cache[e], null) : s.res : null;
|
|
382
|
+
}
|
|
383
|
+
set(e, s) {
|
|
384
|
+
this.ttl !== 0 && (this.cache[e] = {
|
|
385
|
+
ttl: Date.now() + this.ttl,
|
|
386
|
+
res: s
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
function he(t, e, s, n) {
|
|
391
|
+
if (e.ok && !X(e.data) && n) {
|
|
392
|
+
const a = Y(n, "响应数据未能正确识别");
|
|
393
|
+
return a.guard(e.data) || (console.error("ResponseCheckFaild", t, e.data), s.showMessage(!0, `${t} ${a.message}`), e.data = null), e;
|
|
394
|
+
}
|
|
395
|
+
return e;
|
|
396
|
+
}
|
|
397
|
+
class be {
|
|
398
|
+
constructor(e, s) {
|
|
399
|
+
f(this, "agent");
|
|
400
|
+
f(this, "config");
|
|
401
|
+
f(this, "cache");
|
|
402
|
+
this.config = new ue(s), this.agent = e, this.cache = new le(this.config.get("cacheTTL")), this.setConfig = this.setConfig.bind(this), this.getConfig = this.getConfig.bind(this), this.get = this.get.bind(this), this.post = this.post.bind(this), this.del = this.del.bind(this), this.patch = this.patch.bind(this), this.put = this.put.bind(this), this.head = this.head.bind(this);
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* 执行网络请求
|
|
406
|
+
*/
|
|
407
|
+
async exec(e, s) {
|
|
408
|
+
try {
|
|
409
|
+
return await this.agent(e, this.config, s);
|
|
410
|
+
} catch (n) {
|
|
411
|
+
return console.error("RequestError", n), {
|
|
412
|
+
ok: !1,
|
|
413
|
+
status: -9,
|
|
414
|
+
code: "Unkonwn",
|
|
415
|
+
message: String(n),
|
|
416
|
+
headers: {},
|
|
417
|
+
data: null
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* 检查响应的数据类型
|
|
423
|
+
*/
|
|
424
|
+
async guard(e, s, n) {
|
|
425
|
+
return he(e, s, this.config, n);
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
|
|
429
|
+
*/
|
|
430
|
+
setConfig(e) {
|
|
431
|
+
this.config.set(e), this.cache.updateTTL(this.config.get("cacheTTL"));
|
|
432
|
+
}
|
|
433
|
+
/**
|
|
434
|
+
* 读取默认的请求配置
|
|
435
|
+
*/
|
|
436
|
+
getConfig(e) {
|
|
437
|
+
return this.config.get(e);
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* 发送一个 HEAD 请求,并且不处理响应 body
|
|
441
|
+
*/
|
|
442
|
+
async head(e, s) {
|
|
443
|
+
const n = Object.assign({}, s || null);
|
|
444
|
+
return n.method = "HEAD", this.guard(e, await this.exec(e, n), null);
|
|
445
|
+
}
|
|
446
|
+
async get(e, s, n) {
|
|
447
|
+
const a = Object.assign({}, n || null);
|
|
448
|
+
a.method = "GET";
|
|
449
|
+
const r = this.cache.getKey(e, a.params), o = this.cache.get(r);
|
|
450
|
+
if (o)
|
|
451
|
+
return this.guard(e, await o, s || null);
|
|
452
|
+
const c = this.exec(e, a);
|
|
453
|
+
return this.cache.set(r, c), this.guard(e, await c, s || null);
|
|
454
|
+
}
|
|
455
|
+
async post(e, s, n, a) {
|
|
456
|
+
const r = Object.assign({}, a || null);
|
|
457
|
+
return r.method = "POST", r.body = s, this.guard(e, await this.exec(e, r), n || null);
|
|
458
|
+
}
|
|
459
|
+
async del(e, s, n) {
|
|
460
|
+
const a = Object.assign({}, n || null);
|
|
461
|
+
return a.method = "DELETE", this.guard(e, await this.exec(e, a), s || null);
|
|
462
|
+
}
|
|
463
|
+
async put(e, s, n, a) {
|
|
464
|
+
const r = Object.assign({}, a || null);
|
|
465
|
+
return r.method = "PUT", r.body = s, this.guard(e, await this.exec(e, r), n || null);
|
|
466
|
+
}
|
|
467
|
+
async patch(e, s, n, a) {
|
|
468
|
+
const r = Object.assign({}, a || null);
|
|
469
|
+
return r.method = "PATCH", r.body = s, this.guard(e, await this.exec(e, r), n || null);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
const we = "1.7.0";
|
|
473
|
+
export {
|
|
474
|
+
fe as A,
|
|
475
|
+
C as D,
|
|
476
|
+
be as N,
|
|
477
|
+
ue as R,
|
|
478
|
+
O as S,
|
|
479
|
+
me as U,
|
|
480
|
+
ge as c,
|
|
481
|
+
I as f,
|
|
482
|
+
ye as g,
|
|
483
|
+
pe as h,
|
|
484
|
+
ie as r,
|
|
485
|
+
we as v
|
|
486
|
+
};
|
package/dist/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const version = "1.
|
|
1
|
+
export declare const version = "1.7.0";
|
package/dist/wx.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./version-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./version-CCXW7_VI.cjs"),p=async function(t,r,n){return e.handleResponse(await e.retryRequest(l,t,r,n),t,r,n)},l=async function(t,r,n){const o=await e.convertOptions(t,r,n),u=o.method==="PATCH"?"POST":o.method,a=e.Ut(o.url,o.params);return e.Support.wx?new Promise(d=>{wx.request({url:a,data:o.body,header:o.headers,method:u,dataType:"string",responseType:"text",fail(){d({url:a,method:u,status:-1,statusText:"NetworkError",body:""})},success(c){d({url:a,method:u,status:c.statusCode,statusText:c.statusCode+"",headers:{...c.header},body:o.method==="HEAD"?"":f(c.data)})}})}):{url:a,method:u,status:-1,statusText:"NotSupport",body:"NotFound namespace of wx"}};function f(t){return typeof t=="string"?t:t instanceof ArrayBuffer&&e.Support.TextDecoder?new TextDecoder().decode(t):JSON.stringify(t)}function i(t){return new e.NetRequestHandler(p,t)}const s=i(),y=s.setConfig,g=s.head,h=s.get,x=s.post,w=s.del,T=s.put;exports.version=e.version;exports.NetRequest=i;exports.del=w;exports.get=h;exports.head=g;exports.post=x;exports.put=T;exports.setGlobalConfig=y;
|
package/dist/wx.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { h as i, r as p, c as f,
|
|
2
|
-
import { v as
|
|
1
|
+
import { h as i, r as p, c as f, U as l, S as d, N as x } from "./version-DOOsgzgL.js";
|
|
2
|
+
import { v as D } from "./version-DOOsgzgL.js";
|
|
3
3
|
const h = async function(t, o, r) {
|
|
4
4
|
return i(await p(y, t, o, r), t, o, r);
|
|
5
5
|
}, y = async function(t, o, r) {
|
|
@@ -55,5 +55,5 @@ export {
|
|
|
55
55
|
R as post,
|
|
56
56
|
S as put,
|
|
57
57
|
g as setGlobalConfig,
|
|
58
|
-
|
|
58
|
+
D as version
|
|
59
59
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@seayoo-web/request",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0",
|
|
4
4
|
"description": "requst tools for seayoo web",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -82,6 +82,6 @@
|
|
|
82
82
|
"vitest": "^1.4.0"
|
|
83
83
|
},
|
|
84
84
|
"dependencies": {
|
|
85
|
-
"@seayoo-web/utils": "^1.
|
|
85
|
+
"@seayoo-web/utils": "^1.17.1"
|
|
86
86
|
}
|
|
87
87
|
}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var L=Object.defineProperty;var B=(t,e,n)=>e in t?L(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var f=(t,e,n)=>(B(t,typeof e!="symbol"?e+"":e,n),n);const m=typeof globalThis<"u"?globalThis:typeof global<"u"?global:typeof window<"u"?window:{},b={fetch:"fetch"in m,window:"window"in m,FormData:"FormData"in m,Blob:"Blob"in m,wx:"wx"in m,TextDecoder:"TextDecoder"in m,AbortController:"AbortController"in m};function M(t){return t.reduce((e,[n,s])=>(n&&(e[n]=s||""),e),{})}async function H(t,e,n){var w;const s=Object.assign({method:"GET"},n),r=b.FormData?s.body instanceof FormData:!1,a=r&&s.method!=="POST"&&s.method!=="PUT"?"POST":s.method;(a==="GET"||a==="HEAD"||a==="DELETE")&&s.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);const o=Object.assign(r?{}:{"Content-Type":b.Blob&&s.body instanceof Blob?s.body.type||"application/octet-stream":"application/json;charset=utf-8"},s.headers),i=s.params||{},c={};Object.keys(i).forEach(h=>{i[h]!==void 0&&(c[h]=P(i[h]))});const d=e.getFullUrl(t),l=S(s.body),u=s.timeout||e.get("timeout"),g=await async function(){var F;const h=e.get("requestTransformer");return h?await h({headers:o,params:c,method:a,url:d,body:l}):await((F=e.get("requestHandler"))==null?void 0:F(o,c,a,t))}(),y=typeof g=="string"&&g?g:d;return(w=e.get("logHandler"))==null||w({type:"ready",url:y,method:a,headers:o,timeout:u,body:l}),{url:y,method:a,body:l,params:c,headers:o,timeout:u,abort:s.abort,credentials:s.credentials||e.get("credentials")}}function P(t){return typeof t=="string"?t:Array.isArray(t)?t.join(","):t+""}function S(t){if(t)return typeof t=="string"||t instanceof URLSearchParams||t instanceof ArrayBuffer||b.Blob&&t instanceof Blob||b.FormData&&t instanceof FormData?t:JSON.stringify(t)}function q(t){return new Promise(e=>setTimeout(e,Math.max(0,t)))}function K(){}function j(t,e){try{const n=JSON.parse(t);return e?e(n)?n:null:n}catch{return null}}""+Math.random().toString(32).slice(2);const I=/^(?:https?:)?\/\/.+$/i,N=/^https?:\/\/.+$/i,G=/^\{[\d\D]*\}$/,J=/^\[[\d\D]*\]$/;function R(t,e=!1){return e?I.test(t):N.test(t)}function W(t){return t==null}function D(t,...e){if(!t||typeof t!="object")return!1;const n=Object.getPrototypeOf(t);return n!==Object.prototype&&n!==null?!1:e.every(s=>s in t)}function C(t){return G.test(t)||J.test(t)}async function _(t){return await new Promise(function(e){const n=document.getElementsByTagName("head")[0],s=document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("charset","utf-8"),s.onload=function(){n.removeChild(s),e(!0)},s.onerror=function(){n.removeChild(s),e(!1)},s.setAttribute("src",t),n.appendChild(s)})}function V(t,e="数据未能正确识别"){return typeof t=="function"?{guard:t,message:e}:{guard:t.guard,message:t.message||e}}function O(t,e=""){return!e||R(t,!0)?T(t):(T(e)+"/"+t).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function T(t){return R(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 z(t,e){if(e){if(e===!0)return t.replace(/\?[^#]*/,"")}else return t;const n=t.split("#"),s=n[0].split("?"),r=s[0],a=s.length>1?s[1]:"",o=n.length>1?"#"+n[1]:"",i=typeof e=="string"?[e]:Array.isArray(e)?e:[];return!i.length||!a?n[0]+o:(i.map(c=>c.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(r+"?"+a.replace(new RegExp("(?:^|&)(?:"+i.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+o)}function Q(t,e,n=!1){const s=typeof e=="string"?e:Object.keys(e).map(o=>`${o}=${encodeURIComponent(e[o])}`).join("&");if(!s)return t;const r=t.split("#");n&&(r[0]=z(r[0],(s.match(/([^=&#?]+)=[^&#]+/g)||[]).map(o=>o.replace(/=.+$/,""))));const a=r[0].indexOf("?")+1?"&":"?";return(r[0]+a+s+(r.length>1?"#"+r[1]:"")).replace(/\?&/,"?")}const A="data",p="message";function X(t,e,n,s,r){const a=r||s;return v(t)?ae(a.ok||s.ok,t,e,n):Z(a.failed||s.failed,e,n)}const Y=function(t){const e=[],n=t.failed||{resolve:"json"};switch(e.push("- 当http状态码 <200 或者 >=400 时"),n.resolve){case"body":e.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":e.push(" 将响应解析为json,并读取 "+(n.messageField||p)+" 作为错误消息");break}const s=t.ok||{resolve:"body"};switch(e.push("- 当http状态码 >=200 并且 <400 时"),s.resolve){case"body":e.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":e.push(" 将响应解析为 json,读取 "+(s.dataField||A)+" 作为响应数据,读取 "+(s.messageField||p)+" 作为提示消息"),s.statusField&&e.push(" 当 "+s.statusField+" 为 "+(s.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),s.ignoreMessage&&e.push(" 并忽略以下消息:"+s.ignoreMessage);break}return e.join(`
|
|
2
|
-
`)};function Z(t,e,n){const s=t||{resolve:"json",messageField:p},r={ok:!1,code:e,message:n,data:null};switch(s.resolve){case"body":r.message=k(n)||n;break;case"json":const{code:a,message:o}=ee(n,s.statusField,s.messageField);r.code=a||e,r.message=k(n)||o;break}return r}function ee(t,e,n=p){if(!C(t))return{message:""};const s=j(t);return!s||!D(s)?{message:t}:{code:e?$(s,e):"",message:$(s,n)||t}}function $(t,e){const n=Array.isArray(e)?e:[e];for(const s of n)if(s in t)return te(t[s]);return""}function te(t){return t?typeof t=="string"?t:JSON.stringify(t):""}const se=/<title>([^<]+)<\/title>/i,ne=/<message>([^<]+)<\/message>/i;function k(t){const e=t.match(se);if(e)return e[1];const n=t.match(ne);return n?n[1]:""}function ae(t,e,n,s){const r=t||{resolve:"body"},a={ok:!0,code:n,message:"",data:null};if(e===202||e===204||!s)return a;if(r.resolve==="body")return a.data=C(s)?j(s):s,a;const o=j(s);if(!o||!D(o))return a.ok=!1,a.code="ResponseFormatError",a.message="响应内容无法格式化为 Object",a;const i=r.statusField,c=r.statusOKValue||"",d=r.dataField||A,l=r.messageField||p,u=r.ignoreMessage||"";if(i&&!(i in o))return a.ok=!1,a.code="ResponseFieldMissing",a.message="响应内容找不到状态字段 "+i,a;const g=i?o[i]+"":"";return a.ok=i?g===c:!0,a.code=g||n,a.data=d===!0?o:d in o?o[d]:null,a.message=$(o,l),u&&a.message&&(Array.isArray(u)&&u.includes(a.message)||typeof u=="string"&&a.message===u)&&(a.message=""),a}function v(t){return t>=200&&t<400}async function U(t,e,n,s,r){const a=r||0,o=Math.max(0,Math.min(10,(s==null?void 0:s.maxRetry)??n.get("maxRetry")??0)),i=(s==null?void 0:s.retryResolve)??n.get("retryResolve"),c=n.get("logHandler")||K;c({type:"prepear",url:e,method:(s==null?void 0:s.method)||"GET",retry:a,maxRetry:o,message:a===0?"start":`retry ${a}/${o} start`,headers:s==null?void 0:s.headers,options:s});const d=Date.now(),l=await t(e,n,s),u=l.status,g=Date.now()-d,y=`[cost ${g}][${u}] ${u<0?l.body:""}`;c({type:"finished",url:e,method:l.method,retry:a,maxRetry:o,message:a===0?`finish ${y}`:`retry ${a}/${o} finish ${y}`,response:l,headers:l.headers,cost:g});const w=v(u);if(!o||i==="network"&&u>0||i==="status"&&w||Array.isArray(i)&&!i.includes(u)||typeof i=="function"&&i(l,a)!==!0||a>=o)return l;const h=(s==null?void 0:s.retryInterval)??n.get("retryInterval")??1e3;return await q(Math.max(100,h==="2EB"?Math.pow(2,a)*1e3:typeof h=="function"?h(a+1)||0:h)),await U(t,e,n,s,a+1)}function re(t,e,n,s){var o,i;if(t.status<0)return E({ok:!1,status:t.status,code:t.statusText,headers:{},message:"",data:null},`${t.method} ${e} ${t.statusText}`,t.method,e,n,s);v(t.status)||(o=n.get("errorHandler"))==null||o(t.status,t.method,e);const r={...X(t.status,t.statusText,t.body,n.get("responseRule"),s==null?void 0:s.responseRule),status:t.status,headers:M(Object.entries(t.headers||{}).map(([c,d])=>[c.toLowerCase(),d]))};(i=n.get("responseHandler"))==null||i({...r},t.method,e);const a=r.ok?r.message:`${t.method} ${e} [${r.code||t.statusText}] ${r.message||t.statusText}`;return E(r,a,t.method,e,n,s)}function E(t,e,n,s,r,a){const o=r.get("message"),i=o===!1||(a==null?void 0:a.message)===!1?!1:(a==null?void 0:a.message)||o;if(i!==!1){const c=typeof i=="function"?i(t,n,s,e):e;c instanceof Error?r.showMessage(!0,c.message):c&&typeof c=="object"&&"message"in c?r.showMessage(!1,c.message):r.showMessage(!t.ok,c)}return t}class x{constructor(e){f(this,"config",{baseURL:"",maxRetry:0,retryInterval:1e3,retryResolve:"network",timeout:5e3,cacheTTL:500,credentials:"same-origin",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}});e&&this.set(e)}set(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!R(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)}get(e){return this.config[e]}getFullUrl(e){return e.startsWith("/")?O(e):O(e,this.config.baseURL)}showMessage(e,n){this.config.messageHandler&&n&&this.config.messageHandler(e,n)}}class oe{constructor(e=500){f(this,"ttl");f(this,"cache");this.cache={},this.ttl=Math.max(e,0)}getKey(e,n){const s=Object.keys(n||{}).sort().map(r=>`${r}#${n==null?void 0:n[r]}`);return e+s.join(",")}updateTTL(e){this.ttl=Math.max(e,0)}get(e){if(this.ttl===0)return null;const n=this.cache[e];return n?n.ttl<Date.now()?(delete this.cache[e],null):n.res:null}set(e,n){this.ttl!==0&&(this.cache[e]={ttl:Date.now()+this.ttl,res:n})}}function ie(t,e,n,s){if(e.ok&&!W(e.data)&&s){const r=V(s,"响应数据未能正确识别");return r.guard(e.data)||(console.error("ResponseCheckFaild",t,e.data),n.showMessage(!0,`${t} ${r.message}`),e.data=null),e}return e}class ce{constructor(e,n){f(this,"agent");f(this,"config");f(this,"cache");this.config=new x(n),this.agent=e,this.cache=new oe(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this),this.head=this.head.bind(this)}async exec(e,n){try{return await this.agent(e,this.config,n)}catch(s){return console.error("RequestError",s),{ok:!1,status:-9,code:"Unkonwn",message:String(s),headers:{},data:null}}}async guard(e,n,s){return ie(e,n,this.config,s)}setConfig(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(e){return this.config.get(e)}async head(e,n){const s=Object.assign({},n||null);return s.method="HEAD",this.guard(e,await this.exec(e,s),null)}async get(e,n,s){const r=Object.assign({},s||null);r.method="GET";const a=this.cache.getKey(e,r.params),o=this.cache.get(a);if(o)return this.guard(e,await o,n||null);const i=this.exec(e,r);return this.cache.set(a,i),this.guard(e,await i,n||null)}async post(e,n,s,r){const a=Object.assign({},r||null);return a.method="POST",a.body=n,this.guard(e,await this.exec(e,a),s||null)}async del(e,n,s){const r=Object.assign({},s||null);return r.method="DELETE",this.guard(e,await this.exec(e,r),n||null)}async put(e,n,s,r){const a=Object.assign({},r||null);return a.method="PUT",a.body=n,this.guard(e,await this.exec(e,a),s||null)}async patch(e,n,s,r){const a=Object.assign({},r||null);return a.method="PATCH",a.body=n,this.guard(e,await this.exec(e,a),s||null)}}const ue="1.6.6";exports.Et=Q;exports.NetRequestHandler=ce;exports.RequestGlobalConfig=x;exports.Support=b;exports.U=R;exports.convertOptions=H;exports.fromEntries=M;exports.getResponseRulesDescription=Y;exports.handleResponse=re;exports.he=_;exports.retryRequest=U;exports.version=ue;
|
package/dist/version-Cq5oIhuq.js
DELETED
|
@@ -1,454 +0,0 @@
|
|
|
1
|
-
var A = Object.defineProperty;
|
|
2
|
-
var x = (t, e, n) => e in t ? A(t, e, { enumerable: !0, configurable: !0, writable: !0, value: n }) : t[e] = n;
|
|
3
|
-
var f = (t, e, n) => (x(t, typeof e != "symbol" ? e + "" : e, n), n);
|
|
4
|
-
const m = typeof globalThis < "u" ? globalThis : typeof global < "u" ? global : typeof window < "u" ? window : {}, w = {
|
|
5
|
-
fetch: "fetch" in m,
|
|
6
|
-
window: "window" in m,
|
|
7
|
-
FormData: "FormData" in m,
|
|
8
|
-
Blob: "Blob" in m,
|
|
9
|
-
wx: "wx" in m,
|
|
10
|
-
TextDecoder: "TextDecoder" in m,
|
|
11
|
-
AbortController: "AbortController" in m
|
|
12
|
-
};
|
|
13
|
-
function U(t) {
|
|
14
|
-
return t.reduce(
|
|
15
|
-
(e, [n, s]) => (n && (e[n] = s || ""), e),
|
|
16
|
-
{}
|
|
17
|
-
);
|
|
18
|
-
}
|
|
19
|
-
async function ae(t, e, n) {
|
|
20
|
-
var p;
|
|
21
|
-
const s = Object.assign({ method: "GET" }, n), r = w.FormData ? s.body instanceof FormData : !1, a = r && s.method !== "POST" && s.method !== "PUT" ? "POST" : s.method;
|
|
22
|
-
(a === "GET" || a === "HEAD" || a === "DELETE") && s.body !== void 0 && (console.warn("request body is invalid with method get, head, delete"), delete s.body);
|
|
23
|
-
const o = Object.assign(
|
|
24
|
-
r ? {} : {
|
|
25
|
-
"Content-Type": w.Blob && s.body instanceof Blob ? s.body.type || "application/octet-stream" : "application/json;charset=utf-8"
|
|
26
|
-
},
|
|
27
|
-
s.headers
|
|
28
|
-
), i = s.params || {}, c = {};
|
|
29
|
-
Object.keys(i).forEach((h) => {
|
|
30
|
-
i[h] !== void 0 && (c[h] = L(i[h]));
|
|
31
|
-
});
|
|
32
|
-
const d = e.getFullUrl(t), l = B(s.body), u = s.timeout || e.get("timeout"), g = await async function() {
|
|
33
|
-
var v;
|
|
34
|
-
const h = e.get("requestTransformer");
|
|
35
|
-
return h ? await h({ headers: o, params: c, method: a, url: d, body: l }) : await ((v = e.get("requestHandler")) == null ? void 0 : v(o, c, a, t));
|
|
36
|
-
}(), y = typeof g == "string" && g ? g : d;
|
|
37
|
-
return (p = e.get("logHandler")) == null || p({ type: "ready", url: y, method: a, headers: o, timeout: u, body: l }), {
|
|
38
|
-
url: y,
|
|
39
|
-
method: a,
|
|
40
|
-
body: l,
|
|
41
|
-
params: c,
|
|
42
|
-
headers: o,
|
|
43
|
-
timeout: u,
|
|
44
|
-
abort: s.abort,
|
|
45
|
-
credentials: s.credentials || e.get("credentials")
|
|
46
|
-
};
|
|
47
|
-
}
|
|
48
|
-
function L(t) {
|
|
49
|
-
return typeof t == "string" ? t : Array.isArray(t) ? t.join(",") : t + "";
|
|
50
|
-
}
|
|
51
|
-
function B(t) {
|
|
52
|
-
if (t)
|
|
53
|
-
return typeof t == "string" || t instanceof URLSearchParams || t instanceof ArrayBuffer || w.Blob && t instanceof Blob || w.FormData && t instanceof FormData ? t : JSON.stringify(t);
|
|
54
|
-
}
|
|
55
|
-
function P(t) {
|
|
56
|
-
return new Promise((e) => setTimeout(e, Math.max(0, t)));
|
|
57
|
-
}
|
|
58
|
-
function H() {
|
|
59
|
-
}
|
|
60
|
-
function R(t, e) {
|
|
61
|
-
try {
|
|
62
|
-
const n = JSON.parse(t);
|
|
63
|
-
return e ? e(n) ? n : null : n;
|
|
64
|
-
} catch {
|
|
65
|
-
return null;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
"" + Math.random().toString(32).slice(2);
|
|
69
|
-
const S = /^(?:https?:)?\/\/.+$/i, K = /^https?:\/\/.+$/i, q = /^\{[\d\D]*\}$/, I = /^\[[\d\D]*\]$/;
|
|
70
|
-
function $(t, e = !1) {
|
|
71
|
-
return e ? S.test(t) : K.test(t);
|
|
72
|
-
}
|
|
73
|
-
function N(t) {
|
|
74
|
-
return t == null;
|
|
75
|
-
}
|
|
76
|
-
function M(t, ...e) {
|
|
77
|
-
if (!t || typeof t != "object")
|
|
78
|
-
return !1;
|
|
79
|
-
const n = Object.getPrototypeOf(t);
|
|
80
|
-
return n !== Object.prototype && n !== null ? !1 : e.every((s) => s in t);
|
|
81
|
-
}
|
|
82
|
-
function D(t) {
|
|
83
|
-
return q.test(t) || I.test(t);
|
|
84
|
-
}
|
|
85
|
-
async function re(t) {
|
|
86
|
-
return await new Promise(function(e) {
|
|
87
|
-
const n = document.getElementsByTagName("head")[0], s = document.createElement("script");
|
|
88
|
-
s.setAttribute("type", "text/javascript"), s.setAttribute("charset", "utf-8"), s.onload = function() {
|
|
89
|
-
n.removeChild(s), e(!0);
|
|
90
|
-
}, s.onerror = function() {
|
|
91
|
-
n.removeChild(s), e(!1);
|
|
92
|
-
}, s.setAttribute("src", t), n.appendChild(s);
|
|
93
|
-
});
|
|
94
|
-
}
|
|
95
|
-
function G(t, e = "数据未能正确识别") {
|
|
96
|
-
return typeof t == "function" ? {
|
|
97
|
-
guard: t,
|
|
98
|
-
message: e
|
|
99
|
-
} : {
|
|
100
|
-
guard: t.guard,
|
|
101
|
-
message: t.message || e
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
function O(t, e = "") {
|
|
105
|
-
return !e || $(t, !0) ? T(t) : (T(e) + "/" + t).replace(/\/{2,}/g, "/").replace(/:\//, "://");
|
|
106
|
-
}
|
|
107
|
-
function T(t) {
|
|
108
|
-
return $(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(/^\/+/, "");
|
|
109
|
-
}
|
|
110
|
-
function J(t, e) {
|
|
111
|
-
if (e) {
|
|
112
|
-
if (e === !0)
|
|
113
|
-
return t.replace(/\?[^#]*/, "");
|
|
114
|
-
} else
|
|
115
|
-
return t;
|
|
116
|
-
const n = t.split("#"), s = n[0].split("?"), r = s[0], a = s.length > 1 ? s[1] : "", o = n.length > 1 ? "#" + n[1] : "", i = typeof e == "string" ? [e] : Array.isArray(e) ? e : [];
|
|
117
|
-
return !i.length || !a ? n[0] + o : (i.map((c) => c.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (r + "?" + a.replace(new RegExp("(?:^|&)(?:" + i.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + o);
|
|
118
|
-
}
|
|
119
|
-
function oe(t, e, n = !1) {
|
|
120
|
-
const s = typeof e == "string" ? e : Object.keys(e).map((o) => `${o}=${encodeURIComponent(e[o])}`).join("&");
|
|
121
|
-
if (!s)
|
|
122
|
-
return t;
|
|
123
|
-
const r = t.split("#");
|
|
124
|
-
n && (r[0] = J(
|
|
125
|
-
r[0],
|
|
126
|
-
(s.match(/([^=&#?]+)=[^&#]+/g) || []).map((o) => o.replace(/=.+$/, ""))
|
|
127
|
-
));
|
|
128
|
-
const a = r[0].indexOf("?") + 1 ? "&" : "?";
|
|
129
|
-
return (r[0] + a + s + (r.length > 1 ? "#" + r[1] : "")).replace(/\?&/, "?");
|
|
130
|
-
}
|
|
131
|
-
const C = "data", b = "message";
|
|
132
|
-
function W(t, e, n, s, r) {
|
|
133
|
-
const a = r || s;
|
|
134
|
-
return F(t) ? Y(a.ok || s.ok, t, e, n) : _(a.failed || s.failed, e, n);
|
|
135
|
-
}
|
|
136
|
-
const ie = function(t) {
|
|
137
|
-
const e = [], n = t.failed || { resolve: "json" };
|
|
138
|
-
switch (e.push("- 当http状态码 <200 或者 >=400 时"), n.resolve) {
|
|
139
|
-
case "body":
|
|
140
|
-
e.push(" 将响应内容格式化为字符串并作为错误消息");
|
|
141
|
-
break;
|
|
142
|
-
case "json":
|
|
143
|
-
e.push(" 将响应解析为json,并读取 " + (n.messageField || b) + " 作为错误消息");
|
|
144
|
-
break;
|
|
145
|
-
}
|
|
146
|
-
const s = t.ok || { resolve: "body" };
|
|
147
|
-
switch (e.push("- 当http状态码 >=200 并且 <400 时"), s.resolve) {
|
|
148
|
-
case "body":
|
|
149
|
-
e.push(" 将响应尝试解析为 json,并作为数据内容返回");
|
|
150
|
-
break;
|
|
151
|
-
case "json":
|
|
152
|
-
e.push(
|
|
153
|
-
" 将响应解析为 json,读取 " + (s.dataField || C) + " 作为响应数据,读取 " + (s.messageField || b) + " 作为提示消息"
|
|
154
|
-
), s.statusField && e.push(" 当 " + s.statusField + " 为 " + (s.statusOKValue || "空值") + " 时是成功提示,否则是错误消息"), s.ignoreMessage && e.push(" 并忽略以下消息:" + s.ignoreMessage);
|
|
155
|
-
break;
|
|
156
|
-
}
|
|
157
|
-
return e.join(`
|
|
158
|
-
`);
|
|
159
|
-
};
|
|
160
|
-
function _(t, e, n) {
|
|
161
|
-
const s = t || { resolve: "json", messageField: b }, r = {
|
|
162
|
-
ok: !1,
|
|
163
|
-
code: e,
|
|
164
|
-
message: n,
|
|
165
|
-
data: null
|
|
166
|
-
};
|
|
167
|
-
switch (s.resolve) {
|
|
168
|
-
case "body":
|
|
169
|
-
r.message = k(n) || n;
|
|
170
|
-
break;
|
|
171
|
-
case "json":
|
|
172
|
-
const { code: a, message: o } = V(n, s.statusField, s.messageField);
|
|
173
|
-
r.code = a || e, r.message = k(n) || o;
|
|
174
|
-
break;
|
|
175
|
-
}
|
|
176
|
-
return r;
|
|
177
|
-
}
|
|
178
|
-
function V(t, e, n = b) {
|
|
179
|
-
if (!D(t))
|
|
180
|
-
return { message: "" };
|
|
181
|
-
const s = R(t);
|
|
182
|
-
return !s || !M(s) ? { message: t } : {
|
|
183
|
-
code: e ? j(s, e) : "",
|
|
184
|
-
message: j(s, n) || t
|
|
185
|
-
};
|
|
186
|
-
}
|
|
187
|
-
function j(t, e) {
|
|
188
|
-
const n = Array.isArray(e) ? e : [e];
|
|
189
|
-
for (const s of n)
|
|
190
|
-
if (s in t)
|
|
191
|
-
return z(t[s]);
|
|
192
|
-
return "";
|
|
193
|
-
}
|
|
194
|
-
function z(t) {
|
|
195
|
-
return t ? typeof t == "string" ? t : JSON.stringify(t) : "";
|
|
196
|
-
}
|
|
197
|
-
const Q = /<title>([^<]+)<\/title>/i, X = /<message>([^<]+)<\/message>/i;
|
|
198
|
-
function k(t) {
|
|
199
|
-
const e = t.match(Q);
|
|
200
|
-
if (e)
|
|
201
|
-
return e[1];
|
|
202
|
-
const n = t.match(X);
|
|
203
|
-
return n ? n[1] : "";
|
|
204
|
-
}
|
|
205
|
-
function Y(t, e, n, s) {
|
|
206
|
-
const r = t || { resolve: "body" }, a = {
|
|
207
|
-
ok: !0,
|
|
208
|
-
code: n,
|
|
209
|
-
message: "",
|
|
210
|
-
data: null
|
|
211
|
-
};
|
|
212
|
-
if (e === 202 || e === 204 || !s)
|
|
213
|
-
return a;
|
|
214
|
-
if (r.resolve === "body")
|
|
215
|
-
return a.data = D(s) ? R(s) : s, a;
|
|
216
|
-
const o = R(s);
|
|
217
|
-
if (!o || !M(o))
|
|
218
|
-
return a.ok = !1, a.code = "ResponseFormatError", a.message = "响应内容无法格式化为 Object", a;
|
|
219
|
-
const i = r.statusField, c = r.statusOKValue || "", d = r.dataField || C, l = r.messageField || b, u = r.ignoreMessage || "";
|
|
220
|
-
if (i && !(i in o))
|
|
221
|
-
return a.ok = !1, a.code = "ResponseFieldMissing", a.message = "响应内容找不到状态字段 " + i, a;
|
|
222
|
-
const g = i ? o[i] + "" : "";
|
|
223
|
-
return a.ok = i ? g === c : !0, a.code = g || n, a.data = d === !0 ? o : d in o ? o[d] : null, a.message = j(o, l), u && a.message && (Array.isArray(u) && u.includes(a.message) || typeof u == "string" && a.message === u) && (a.message = ""), a;
|
|
224
|
-
}
|
|
225
|
-
function F(t) {
|
|
226
|
-
return t >= 200 && t < 400;
|
|
227
|
-
}
|
|
228
|
-
async function Z(t, e, n, s, r) {
|
|
229
|
-
const a = r || 0, o = Math.max(0, Math.min(10, (s == null ? void 0 : s.maxRetry) ?? n.get("maxRetry") ?? 0)), i = (s == null ? void 0 : s.retryResolve) ?? n.get("retryResolve"), c = n.get("logHandler") || H;
|
|
230
|
-
c({
|
|
231
|
-
type: "prepear",
|
|
232
|
-
url: e,
|
|
233
|
-
method: (s == null ? void 0 : s.method) || "GET",
|
|
234
|
-
retry: a,
|
|
235
|
-
maxRetry: o,
|
|
236
|
-
message: a === 0 ? "start" : `retry ${a}/${o} start`,
|
|
237
|
-
headers: s == null ? void 0 : s.headers,
|
|
238
|
-
options: s
|
|
239
|
-
});
|
|
240
|
-
const d = Date.now(), l = await t(e, n, s), u = l.status, g = Date.now() - d, y = `[cost ${g}][${u}] ${u < 0 ? l.body : ""}`;
|
|
241
|
-
c({
|
|
242
|
-
type: "finished",
|
|
243
|
-
url: e,
|
|
244
|
-
method: l.method,
|
|
245
|
-
retry: a,
|
|
246
|
-
maxRetry: o,
|
|
247
|
-
message: a === 0 ? `finish ${y}` : `retry ${a}/${o} finish ${y}`,
|
|
248
|
-
response: l,
|
|
249
|
-
headers: l.headers,
|
|
250
|
-
cost: g
|
|
251
|
-
});
|
|
252
|
-
const p = F(u);
|
|
253
|
-
if (!o || i === "network" && u > 0 || i === "status" && p || Array.isArray(i) && !i.includes(u) || typeof i == "function" && i(l, a) !== !0 || a >= o)
|
|
254
|
-
return l;
|
|
255
|
-
const h = (s == null ? void 0 : s.retryInterval) ?? n.get("retryInterval") ?? 1e3;
|
|
256
|
-
return await P(
|
|
257
|
-
Math.max(
|
|
258
|
-
100,
|
|
259
|
-
h === "2EB" ? Math.pow(2, a) * 1e3 : typeof h == "function" ? h(a + 1) || 0 : h
|
|
260
|
-
)
|
|
261
|
-
), await Z(t, e, n, s, a + 1);
|
|
262
|
-
}
|
|
263
|
-
function ce(t, e, n, s) {
|
|
264
|
-
var o, i;
|
|
265
|
-
if (t.status < 0)
|
|
266
|
-
return E(
|
|
267
|
-
{ ok: !1, status: t.status, code: t.statusText, headers: {}, message: "", data: null },
|
|
268
|
-
`${t.method} ${e} ${t.statusText}`,
|
|
269
|
-
t.method,
|
|
270
|
-
e,
|
|
271
|
-
n,
|
|
272
|
-
s
|
|
273
|
-
);
|
|
274
|
-
F(t.status) || (o = n.get("errorHandler")) == null || o(t.status, t.method, e);
|
|
275
|
-
const r = {
|
|
276
|
-
...W(t.status, t.statusText, t.body, n.get("responseRule"), s == null ? void 0 : s.responseRule),
|
|
277
|
-
status: t.status,
|
|
278
|
-
headers: U(Object.entries(t.headers || {}).map(([c, d]) => [c.toLowerCase(), d]))
|
|
279
|
-
};
|
|
280
|
-
(i = n.get("responseHandler")) == null || i({ ...r }, t.method, e);
|
|
281
|
-
const a = r.ok ? r.message : `${t.method} ${e} [${r.code || t.statusText}] ${r.message || t.statusText}`;
|
|
282
|
-
return E(r, a, t.method, e, n, s);
|
|
283
|
-
}
|
|
284
|
-
function E(t, e, n, s, r, a) {
|
|
285
|
-
const o = r.get("message"), i = o === !1 || (a == null ? void 0 : a.message) === !1 ? !1 : (a == null ? void 0 : a.message) || o;
|
|
286
|
-
if (i !== !1) {
|
|
287
|
-
const c = typeof i == "function" ? i(t, n, s, e) : e;
|
|
288
|
-
c instanceof Error ? r.showMessage(!0, c.message) : c && typeof c == "object" && "message" in c ? r.showMessage(!1, c.message) : r.showMessage(!t.ok, c);
|
|
289
|
-
}
|
|
290
|
-
return t;
|
|
291
|
-
}
|
|
292
|
-
class ee {
|
|
293
|
-
constructor(e) {
|
|
294
|
-
// 保存的配置需要部分字段强制设置默认值
|
|
295
|
-
f(this, "config", {
|
|
296
|
-
baseURL: "",
|
|
297
|
-
maxRetry: 0,
|
|
298
|
-
retryInterval: 1e3,
|
|
299
|
-
retryResolve: "network",
|
|
300
|
-
timeout: 5e3,
|
|
301
|
-
cacheTTL: 500,
|
|
302
|
-
credentials: "same-origin",
|
|
303
|
-
responseRule: {
|
|
304
|
-
ok: {
|
|
305
|
-
resolve: "body"
|
|
306
|
-
},
|
|
307
|
-
failed: {
|
|
308
|
-
resolve: "json",
|
|
309
|
-
messageField: "message"
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
});
|
|
313
|
-
e && this.set(e);
|
|
314
|
-
}
|
|
315
|
-
set(e) {
|
|
316
|
-
if (e.baseURL && !/^\/.+/.test(e.baseURL) && !$(e.baseURL))
|
|
317
|
-
throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"), new Error("BaseURLError");
|
|
318
|
-
Object.assign(this.config, e);
|
|
319
|
-
}
|
|
320
|
-
get(e) {
|
|
321
|
-
return this.config[e];
|
|
322
|
-
}
|
|
323
|
-
/** 基于 baseURL 返回完整的 url 地址, 如果 url 地址以 / 开头则表示忽略 baseURL 的值 */
|
|
324
|
-
getFullUrl(e) {
|
|
325
|
-
return e.startsWith("/") ? O(e) : O(e, this.config.baseURL);
|
|
326
|
-
}
|
|
327
|
-
/** 提示消息 */
|
|
328
|
-
showMessage(e, n) {
|
|
329
|
-
this.config.messageHandler && n && this.config.messageHandler(e, n);
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
class te {
|
|
333
|
-
constructor(e = 500) {
|
|
334
|
-
f(this, "ttl");
|
|
335
|
-
f(this, "cache");
|
|
336
|
-
this.cache = {}, this.ttl = Math.max(e, 0);
|
|
337
|
-
}
|
|
338
|
-
getKey(e, n) {
|
|
339
|
-
const s = Object.keys(n || {}).sort().map((r) => `${r}#${n == null ? void 0 : n[r]}`);
|
|
340
|
-
return e + s.join(",");
|
|
341
|
-
}
|
|
342
|
-
updateTTL(e) {
|
|
343
|
-
this.ttl = Math.max(e, 0);
|
|
344
|
-
}
|
|
345
|
-
get(e) {
|
|
346
|
-
if (this.ttl === 0)
|
|
347
|
-
return null;
|
|
348
|
-
const n = this.cache[e];
|
|
349
|
-
return n ? n.ttl < Date.now() ? (delete this.cache[e], null) : n.res : null;
|
|
350
|
-
}
|
|
351
|
-
set(e, n) {
|
|
352
|
-
this.ttl !== 0 && (this.cache[e] = {
|
|
353
|
-
ttl: Date.now() + this.ttl,
|
|
354
|
-
res: n
|
|
355
|
-
});
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
function se(t, e, n, s) {
|
|
359
|
-
if (e.ok && !N(e.data) && s) {
|
|
360
|
-
const r = G(s, "响应数据未能正确识别");
|
|
361
|
-
return r.guard(e.data) || (console.error("ResponseCheckFaild", t, e.data), n.showMessage(!0, `${t} ${r.message}`), e.data = null), e;
|
|
362
|
-
}
|
|
363
|
-
return e;
|
|
364
|
-
}
|
|
365
|
-
class ue {
|
|
366
|
-
constructor(e, n) {
|
|
367
|
-
f(this, "agent");
|
|
368
|
-
f(this, "config");
|
|
369
|
-
f(this, "cache");
|
|
370
|
-
this.config = new ee(n), this.agent = e, this.cache = new te(this.config.get("cacheTTL")), this.setConfig = this.setConfig.bind(this), this.getConfig = this.getConfig.bind(this), this.get = this.get.bind(this), this.post = this.post.bind(this), this.del = this.del.bind(this), this.patch = this.patch.bind(this), this.put = this.put.bind(this), this.head = this.head.bind(this);
|
|
371
|
-
}
|
|
372
|
-
/**
|
|
373
|
-
* 执行网络请求
|
|
374
|
-
*/
|
|
375
|
-
async exec(e, n) {
|
|
376
|
-
try {
|
|
377
|
-
return await this.agent(e, this.config, n);
|
|
378
|
-
} catch (s) {
|
|
379
|
-
return console.error("RequestError", s), {
|
|
380
|
-
ok: !1,
|
|
381
|
-
status: -9,
|
|
382
|
-
code: "Unkonwn",
|
|
383
|
-
message: String(s),
|
|
384
|
-
headers: {},
|
|
385
|
-
data: null
|
|
386
|
-
};
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
/**
|
|
390
|
-
* 检查响应的数据类型
|
|
391
|
-
*/
|
|
392
|
-
async guard(e, n, s) {
|
|
393
|
-
return se(e, n, this.config, s);
|
|
394
|
-
}
|
|
395
|
-
/**
|
|
396
|
-
* 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
|
|
397
|
-
*/
|
|
398
|
-
setConfig(e) {
|
|
399
|
-
this.config.set(e), this.cache.updateTTL(this.config.get("cacheTTL"));
|
|
400
|
-
}
|
|
401
|
-
/**
|
|
402
|
-
* 读取默认的请求配置
|
|
403
|
-
*/
|
|
404
|
-
getConfig(e) {
|
|
405
|
-
return this.config.get(e);
|
|
406
|
-
}
|
|
407
|
-
/**
|
|
408
|
-
* 发送一个 HEAD 请求,并且不处理响应 body
|
|
409
|
-
*/
|
|
410
|
-
async head(e, n) {
|
|
411
|
-
const s = Object.assign({}, n || null);
|
|
412
|
-
return s.method = "HEAD", this.guard(e, await this.exec(e, s), null);
|
|
413
|
-
}
|
|
414
|
-
async get(e, n, s) {
|
|
415
|
-
const r = Object.assign({}, s || null);
|
|
416
|
-
r.method = "GET";
|
|
417
|
-
const a = this.cache.getKey(e, r.params), o = this.cache.get(a);
|
|
418
|
-
if (o)
|
|
419
|
-
return this.guard(e, await o, n || null);
|
|
420
|
-
const i = this.exec(e, r);
|
|
421
|
-
return this.cache.set(a, i), this.guard(e, await i, n || null);
|
|
422
|
-
}
|
|
423
|
-
async post(e, n, s, r) {
|
|
424
|
-
const a = Object.assign({}, r || null);
|
|
425
|
-
return a.method = "POST", a.body = n, this.guard(e, await this.exec(e, a), s || null);
|
|
426
|
-
}
|
|
427
|
-
async del(e, n, s) {
|
|
428
|
-
const r = Object.assign({}, s || null);
|
|
429
|
-
return r.method = "DELETE", this.guard(e, await this.exec(e, r), n || null);
|
|
430
|
-
}
|
|
431
|
-
async put(e, n, s, r) {
|
|
432
|
-
const a = Object.assign({}, r || null);
|
|
433
|
-
return a.method = "PUT", a.body = n, this.guard(e, await this.exec(e, a), s || null);
|
|
434
|
-
}
|
|
435
|
-
async patch(e, n, s, r) {
|
|
436
|
-
const a = Object.assign({}, r || null);
|
|
437
|
-
return a.method = "PATCH", a.body = n, this.guard(e, await this.exec(e, a), s || null);
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
const le = "1.6.6";
|
|
441
|
-
export {
|
|
442
|
-
oe as E,
|
|
443
|
-
ue as N,
|
|
444
|
-
ee as R,
|
|
445
|
-
w as S,
|
|
446
|
-
$ as U,
|
|
447
|
-
re as a,
|
|
448
|
-
ae as c,
|
|
449
|
-
U as f,
|
|
450
|
-
ie as g,
|
|
451
|
-
ce as h,
|
|
452
|
-
Z as r,
|
|
453
|
-
le as v
|
|
454
|
-
};
|