@seayoo-web/request 1.5.2 → 1.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import type { TypeGuardFn } from "@seayoo-web/utils";
1
+ import { type TypeGuardFn } from "@seayoo-web/utils";
2
2
  /**
3
3
  * 以 script 方式加载远程资源,资源通过回调函数接收,强制进行类型校验
4
4
  */
@@ -105,7 +105,7 @@ export interface IResponseRule {
105
105
  failed: {
106
106
  /** 解析方式,如果解析方式为 json,则可以进一步指定错误消息字段 */
107
107
  resolve: "json" | "body";
108
- /** 解析错误消息的状态字段,仅在 resolve 为 json 时有效,有值的话会替换 response 的 code */
108
+ /** 解析错误消息的状态字段,比如 error 或 code,仅在 resolve 为 json 时有效,有值的话会替换 response 的 code */
109
109
  statusField?: string;
110
110
  /** 解析错误消息的字段,仅在 resolve 为 json 时有效 */
111
111
  messageField?: string | string[];
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./main-CFU3RpxD.cjs"),H=async function(n,o,e){const t=await c.convertOptions(n,o,e),r=new URL(t.url),l=t.params;l instanceof Object&&Object.keys(l).forEach(s=>r.searchParams.set(s,l[s]));const a=new AbortController;function i(){a.signal.aborted||a.abort()}t.abort&&t.abort.addEventListener("abort",i);const h=t.timeout>0?setTimeout(i,t.timeout):null,f=new Request(r,{method:t.method,headers:new Headers(t.headers),body:t.body,credentials:t.credentials,signal:a.signal,redirect:"follow"});return await fetch(f).then(async s=>({url:r.toString(),method:t.method,status:s.status,statusText:s.statusText,headers:Object.fromEntries(s.headers.entries()),body:t.method==="HEAD"?"":await s.text()})).catch(s=>({url:r.toString(),method:t.method,status:-1,statusText:"NetworkError",body:String(s)})).finally(()=>{h!==null&&clearTimeout(h),t.abort&&t.abort.removeEventListener("abort",i)})},m=async function(n,o,e){const t={...await c.convertOptions(n,o,e),onUploadProgress:e==null?void 0:e.onUploadProgress},r=t.method,l=t.onUploadProgress||c.ht,a=c.rt(t.url,t.params);return await new Promise(i=>{let h=1;function f(g){h=g.total,l({total:g.total,loaded:g.loaded})}let s=null,p=!1;const b=function(){p||(d.abort(),p=!0)};function w(){s!==null&&clearTimeout(s),t.abort&&t.abort.removeEventListener("abort",b)}const d=new XMLHttpRequest;d.open(r,a,!0),d.upload.addEventListener("progress",f),d.addEventListener("load",()=>{w(),l({loaded:h,total:h}),i({url:a,method:r,status:d.status,statusText:d.statusText,headers:q(d),body:r==="HEAD"?"":d.responseText})}),d.addEventListener("error",()=>{w(),i({url:a,method:r,status:-1,statusText:"Failed",body:""})}),d.addEventListener("abort",()=>{w(),i({url:a,method:r,status:-1,statusText:"Aborted",body:""})}),Object.entries(t.headers).forEach(([g,R])=>{d.setRequestHeader(g,R)}),t.credentials==="include"&&(d.withCredentials=!0),d.send(t.body||void 0),t.abort&&t.abort.addEventListener("abort",b),t.timeout>0&&(s=setTimeout(b,t.timeout))})};function q(n){const o={};if(!n)return o;const e=n.getAllResponseHeaders();return e&&e!=="null"&&e.replace(/\r/g,"").split(`
2
- `).forEach(t=>{const r=t.trim();if(!r)return;const l=r.split(":"),a=l[0].trim();a&&(o[a]=(l[1]||"").trim())}),o}const E=async function(n,o,e){return c.handleResponse(await c.retryRequest(H,n,o,e),n,o,e)},T=async function(n,o,e){return c.handleResponse(await c.retryRequest(m,n,o,e),n,o,e)};async function x(n,o,e,t){const r=new FormData,l=e==null?void 0:e.body,a={...o};l instanceof Object&&Object.entries(l).forEach(([f,s])=>{s instanceof Blob?a[f]=s:Array.isArray(s)?s.forEach((p,b)=>{r.append(`${f}[${b}]`,String(p))}):r.append(f,String(s))});for(const f in a)r.append(f,a[f]);const i=new c.RequestGlobalConfig(t),h=await m(n,i,{...e,method:"POST",body:r});return c.handleResponse(h,n,i,e)}async function j(n,o,e={}){const t=window;"callback"in e||(e.callback="jsonxData"+Math.random().toString(16).slice(2));const r=e.callback+"";if(!n)return null;const l=c.rt(n,e,!0);return new Promise(a=>{t[r]=function(i){if(r in window&&delete t[r],o(i))return i;console.warn("response type check faild",n,i),a(null)},c.Ut(l).catch(function(){a(null),delete t[r]})})}async function L(n,o,e={}){const t=window;return"var"in e||(e.var="jsonxData"+Math.random().toString(16).slice(2)),n?await c.Ut(c.rt(n,e,!0)).then(()=>{const r=t[e.var+""];return o(r)?r:(console.warn("response type check faild",n,r),null)}).catch(()=>null):null}const S=async function(n,o,e){return await x(n,o,e,{baseURL:u.getConfig("baseURL"),logHandler:u.getConfig("logHandler"),errorHandler:u.getConfig("errorHandler"),requestHandler:u.getConfig("requestHandler"),messageHandler:u.getConfig("messageHandler"),responseHandler:u.getConfig("responseHandler")})};function y(n){if("window"in globalThis)return"fetch"in window?new c.NetRequestHandler(E,n):new c.NetRequestHandler(T,n);throw new Error("Default Module Only Support In Browser")}const u=y(),C=u.setConfig,U=u.head,v=u.get,O=u.post,D=u.del,k=u.put,P=u.patch;exports.getResponseRulesDescription=c.getResponseRulesDescription;exports.NetRequest=y;exports.del=D;exports.get=v;exports.head=U;exports.jsonp=j;exports.jsonx=L;exports.patch=P;exports.post=O;exports.put=k;exports.setGlobalConfig=C;exports.upload=S;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("./version-B09aAqk-.cjs"),H=async function(n,o,t){const e=await c.convertOptions(n,o,t),r=new URL(e.url),i=e.params;i instanceof Object&&Object.keys(i).forEach(s=>r.searchParams.set(s,i[s]));const a=new AbortController;function l(){a.signal.aborted||a.abort()}e.abort&&e.abort.addEventListener("abort",l);const b=e.timeout>0?setTimeout(l,e.timeout):null,f=new Request(r,{method:e.method,headers:new Headers(e.headers),body:e.body,credentials:e.credentials,signal:a.signal,redirect:"follow"});return await fetch(f).then(async s=>({url:r.toString(),method:e.method,status:s.status,statusText:s.statusText,headers:Object.fromEntries(s.headers.entries()),body:e.method==="HEAD"?"":await s.text()})).catch(s=>({url:r.toString(),method:e.method,status:-1,statusText:"NetworkError",body:String(s)})).finally(()=>{b!==null&&clearTimeout(b),e.abort&&e.abort.removeEventListener("abort",l)})},m=async function(n,o,t){const e={...await c.convertOptions(n,o,t),onUploadProgress:t==null?void 0:t.onUploadProgress},r=e.method,i=e.onUploadProgress||c.Ot,a=c.wt(e.url,e.params);return await new Promise(l=>{let b=1;function f(g){b=g.total,i({total:g.total,loaded:g.loaded})}let s=null,w=!1;const h=function(){w||(d.abort(),w=!0)};function p(){s!==null&&clearTimeout(s),e.abort&&e.abort.removeEventListener("abort",h)}const d=new XMLHttpRequest;d.open(r,a,!0),d.upload.addEventListener("progress",f),d.addEventListener("load",()=>{p(),i({loaded:b,total:b}),l({url:a,method:r,status:d.status,statusText:d.statusText,headers:T(d),body:r==="HEAD"?"":d.responseText})}),d.addEventListener("error",()=>{p(),l({url:a,method:r,status:-1,statusText:"Failed",body:""})}),d.addEventListener("abort",()=>{p(),l({url:a,method:r,status:-1,statusText:"Aborted",body:""})}),Object.entries(e.headers).forEach(([g,R])=>{d.setRequestHeader(g,R)}),e.credentials==="include"&&(d.withCredentials=!0),d.send(e.body||void 0),e.abort&&e.abort.addEventListener("abort",h),e.timeout>0&&(s=setTimeout(h,e.timeout))})};function T(n){const o={};if(!n)return o;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(":"),a=i[0].trim();a&&(o[a]=(i[1]||"").trim())}),o}const q=async function(n,o,t){return c.handleResponse(await c.retryRequest(H,n,o,t),n,o,t)},E=async function(n,o,t){return c.handleResponse(await c.retryRequest(m,n,o,t),n,o,t)};async function x(n,o,t,e){const r=new FormData,i=t==null?void 0:t.body,a={...o};i instanceof Object&&Object.entries(i).forEach(([f,s])=>{s instanceof Blob?a[f]=s:Array.isArray(s)?s.forEach((w,h)=>{r.append(`${f}[${h}]`,String(w))}):r.append(f,String(s))});for(const f in a)r.append(f,a[f]);const l=new c.RequestGlobalConfig(e),b=await m(n,l,{...t,method:"POST",body:r});return c.handleResponse(b,n,l,t)}async function v(n,o,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.wt(n,t,!0);return new Promise(a=>{e[r]=function(l){if(r in window&&delete e[r],o(l))return l;console.warn("response type check faild",n,l),a(null)},c.sn(i).catch(function(){a(null),delete e[r]})})}async function j(n,o,t={}){const e=window;return"var"in t||(t.var="jsonxData"+Math.random().toString(16).slice(2)),n?await c.sn(c.wt(n,t,!0)).then(()=>{const r=e[t.var+""];return o(r)?r:(console.warn("response type check faild",n,r),null)}).catch(()=>null):null}const L=async function(n,o,t){return await x(n,o,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 y(n){if("window"in globalThis)return"fetch"in window?new c.NetRequestHandler(q,n):new c.NetRequestHandler(E,n);throw new Error("Default Module Only Support In Browser")}const u=y(),S=u.setConfig,C=u.head,O=u.get,U=u.post,D=u.del,k=u.put,P=u.patch;exports.getResponseRulesDescription=c.getResponseRulesDescription;exports.version=c.version;exports.NetRequest=y;exports.del=D;exports.get=O;exports.head=C;exports.jsonp=v;exports.jsonx=j;exports.patch=P;exports.post=U;exports.put=k;exports.setGlobalConfig=S;exports.upload=L;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { xhrUpload } from "./inc/request.browser";
2
2
  import { NetRequestHandler } from "./inc/main";
3
3
  import type { IRequestGlobalConfig } from "./inc/type";
4
+ export * from "./version";
4
5
  export { jsonp, jsonx } from "./inc/jsonp";
5
6
  export { getResponseRulesDescription } from "./inc/rule";
6
7
  export type { IRequestOptions, IRequestGlobalConfig, IResponseRule, IResponseResult, IRequestLog } from "./inc/type";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { c as R, r as m, h as q, a as p, b as H, R as L, U as E, N as y } from "./main-DS7dDlqb.js";
2
- import { g as J } from "./main-DS7dDlqb.js";
3
- const U = async function(n, o, e) {
1
+ import { c as R, w as m, O as q, h as p, r as E, R as L, s as H, N as y } from "./version-BXzKbsH3.js";
2
+ import { g as J, v as K } from "./version-BXzKbsH3.js";
3
+ const v = async function(n, o, e) {
4
4
  const t = await R(n, o, e), r = new URL(t.url), c = t.params;
5
5
  c instanceof Object && Object.keys(c).forEach((a) => r.searchParams.set(a, c[a]));
6
6
  const s = new AbortController();
@@ -32,7 +32,7 @@ const U = async function(n, o, e) {
32
32
  })).finally(() => {
33
33
  f !== null && clearTimeout(f), t.abort && t.abort.removeEventListener("abort", i);
34
34
  });
35
- }, x = async function(n, o, e) {
35
+ }, T = async function(n, o, e) {
36
36
  const t = {
37
37
  ...await R(n, o, e),
38
38
  onUploadProgress: e == null ? void 0 : e.onUploadProgress
@@ -75,8 +75,8 @@ const U = async function(n, o, e) {
75
75
  statusText: "Aborted",
76
76
  body: ""
77
77
  });
78
- }), Object.entries(t.headers).forEach(([h, T]) => {
79
- l.setRequestHeader(h, T);
78
+ }), Object.entries(t.headers).forEach(([h, x]) => {
79
+ l.setRequestHeader(h, x);
80
80
  }), t.credentials === "include" && (l.withCredentials = !0), l.send(t.body || void 0), t.abort && t.abort.addEventListener("abort", b), t.timeout > 0 && (a = setTimeout(b, t.timeout));
81
81
  });
82
82
  };
@@ -94,12 +94,12 @@ function C(n) {
94
94
  s && (o[s] = (c[1] || "").trim());
95
95
  }), o;
96
96
  }
97
- const S = async function(n, o, e) {
98
- return p(await H(U, n, o, e), n, o, e);
99
- }, j = async function(n, o, e) {
100
- return p(await H(x, n, o, e), n, o, e);
97
+ const O = async function(n, o, e) {
98
+ return p(await E(v, n, o, e), n, o, e);
99
+ }, S = async function(n, o, e) {
100
+ return p(await E(T, n, o, e), n, o, e);
101
101
  };
102
- async function v(n, o, e, t) {
102
+ async function j(n, o, e, t) {
103
103
  const r = new FormData(), c = e == null ? void 0 : e.body, s = { ...o };
104
104
  c instanceof Object && Object.entries(c).forEach(([u, a]) => {
105
105
  a instanceof Blob ? s[u] = a : Array.isArray(a) ? a.forEach((g, b) => {
@@ -108,7 +108,7 @@ async function v(n, o, e, t) {
108
108
  });
109
109
  for (const u in s)
110
110
  r.append(u, s[u]);
111
- const i = new L(t), f = await x(n, i, {
111
+ const i = new L(t), f = await T(n, i, {
112
112
  ...e,
113
113
  method: "POST",
114
114
  body: r
@@ -127,36 +127,36 @@ async function D(n, o, e = {}) {
127
127
  if (r in window && delete t[r], o(i))
128
128
  return i;
129
129
  console.warn("response type check faild", n, i), s(null);
130
- }, E(c).catch(function() {
130
+ }, H(c).catch(function() {
131
131
  s(null), delete t[r];
132
132
  });
133
133
  });
134
134
  }
135
135
  async function A(n, o, e = {}) {
136
136
  const t = window;
137
- return "var" in e || (e.var = "jsonxData" + Math.random().toString(16).slice(2)), n ? await E(m(n, e, !0)).then(() => {
137
+ return "var" in e || (e.var = "jsonxData" + Math.random().toString(16).slice(2)), n ? await H(m(n, e, !0)).then(() => {
138
138
  const r = t[e.var + ""];
139
139
  return o(r) ? r : (console.warn("response type check faild", n, r), null);
140
140
  }).catch(() => null) : null;
141
141
  }
142
142
  const P = async function(n, o, e) {
143
- return await v(n, o, e, {
143
+ return await j(n, o, e, {
144
144
  baseURL: d.getConfig("baseURL"),
145
145
  logHandler: d.getConfig("logHandler"),
146
146
  errorHandler: d.getConfig("errorHandler"),
147
- requestHandler: d.getConfig("requestHandler"),
147
+ requestTransformer: d.getConfig("requestTransformer"),
148
148
  messageHandler: d.getConfig("messageHandler"),
149
149
  responseHandler: d.getConfig("responseHandler")
150
150
  });
151
151
  };
152
- function O(n) {
152
+ function U(n) {
153
153
  if ("window" in globalThis)
154
- return "fetch" in window ? new y(S, n) : new y(j, n);
154
+ return "fetch" in window ? new y(O, n) : new y(S, n);
155
155
  throw new Error("Default Module Only Support In Browser");
156
156
  }
157
- const d = O(), M = d.setConfig, N = d.head, F = d.get, X = d.post, B = d.del, G = d.put, I = d.patch;
157
+ const d = U(), M = d.setConfig, N = d.head, F = d.get, X = d.post, B = d.del, G = d.put, I = d.patch;
158
158
  export {
159
- O as NetRequest,
159
+ U as NetRequest,
160
160
  B as del,
161
161
  F as get,
162
162
  J as getResponseRulesDescription,
@@ -167,5 +167,6 @@ export {
167
167
  X as post,
168
168
  G as put,
169
169
  M as setGlobalConfig,
170
- P as upload
170
+ P as upload,
171
+ K as version
171
172
  };
package/dist/node.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./main-CFU3RpxD.cjs"),p={},R=async function(s,u,c){return a.handleResponse(await a.retryRequest(q,s,u,c),s,u,c)},q=async function(s,u,c){const t=await a.convertOptions(s,u,c);if(!a.S(t.url))return{url:t.url,method:t.method,status:-1,statusText:"URLFormatError",headers:{},body:""};const f=(/^https:\/\//i.test(t.url),p),r=new URL(t.url),i=t.params;i instanceof Object&&Object.keys(i).forEach(n=>r.searchParams.set(n,i[n]));const g=t.method==="HEAD";return new Promise(n=>{const d=f.request(r,{headers:t.headers,method:t.method,timeout:t.timeout>0?t.timeout:void 0},function(e){const l=[];e.on("data",h=>l.push(h)),e.on("end",()=>{const h=Object.fromEntries(Object.entries(e.headers).map(([y,m])=>[y.toLowerCase(),Array.isArray(m)?m.join(","):m]));n({url:r.toString(),method:t.method,status:e.statusCode||-1,statusText:e.statusMessage||"Unknown",headers:h,body:g?"":Buffer.concat(l).toString("utf-8")})})});d.on("error",e=>{n({url:r.toString(),method:t.method,status:-1,statusText:e.name||"Unknown",body:e.message})}),d.on("timeout",()=>{n({url:r.toString(),method:t.method,status:-1,statusText:"Timeout",body:""})}),t.body&&d.write(t.body),d.end()})};function b(s){return new a.NetRequestHandler(R,s)}const o=b(),w=o.setConfig,S=o.head,j=o.get,O=o.post,T=o.del,C=o.put,U=o.patch;exports.NetRequest=b;exports.del=T;exports.get=j;exports.head=S;exports.patch=U;exports.post=O;exports.put=C;exports.setGlobalConfig=w;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const r=require("./version-B09aAqk-.cjs"),p={},R=async function(s,u,c){return r.handleResponse(await r.retryRequest(q,s,u,c),s,u,c)},q=async function(s,u,c){const t=await r.convertOptions(s,u,c);if(!r.R(t.url))return{url:t.url,method:t.method,status:-1,statusText:"URLFormatError",headers:{},body:""};const f=(/^https:\/\//i.test(t.url),p),a=new URL(t.url),i=t.params;i instanceof Object&&Object.keys(i).forEach(n=>a.searchParams.set(n,i[n]));const g=t.method==="HEAD";return new Promise(n=>{const d=f.request(a,{headers:t.headers,method:t.method,timeout:t.timeout>0?t.timeout:void 0},function(e){const l=[];e.on("data",h=>l.push(h)),e.on("end",()=>{const h=Object.fromEntries(Object.entries(e.headers).map(([y,m])=>[y.toLowerCase(),Array.isArray(m)?m.join(","):m]));n({url:a.toString(),method:t.method,status:e.statusCode||-1,statusText:e.statusMessage||"Unknown",headers:h,body:g?"":Buffer.concat(l).toString("utf-8")})})});d.on("error",e=>{n({url:a.toString(),method:t.method,status:-1,statusText:e.name||"Unknown",body:e.message})}),d.on("timeout",()=>{n({url:a.toString(),method:t.method,status:-1,statusText:"Timeout",body:""})}),t.body&&d.write(t.body),d.end()})};function b(s){return new r.NetRequestHandler(R,s)}const o=b(),w=o.setConfig,j=o.head,O=o.get,S=o.post,T=o.del,C=o.put,U=o.patch;exports.version=r.version;exports.NetRequest=b;exports.del=T;exports.get=O;exports.head=j;exports.patch=U;exports.post=S;exports.put=C;exports.setGlobalConfig=w;
package/dist/node.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { NetRequestHandler } from "./inc/main";
2
2
  import type { IRequestGlobalConfig } from "./inc/type";
3
+ export * from "./version";
3
4
  export type { IRequestGlobalConfig } from "./inc/type";
4
5
  /**
5
6
  * 创建新的实例空间,配置和缓存跟全局默认实例是隔离的
package/dist/node.js CHANGED
@@ -1,7 +1,8 @@
1
- import { a as y, b as R, c as g, S as q, N as w } from "./main-DS7dDlqb.js";
2
- const p = {}, j = async function(s, a, u) {
3
- return y(await R(x, s, a, u), s, a, u);
4
- }, x = async function(s, a, u) {
1
+ import { h as y, r as R, c as g, a as q, N as w } from "./version-BXzKbsH3.js";
2
+ import { v as P } from "./version-BXzKbsH3.js";
3
+ const p = {}, x = async function(s, a, u) {
4
+ return y(await R(j, s, a, u), s, a, u);
5
+ }, j = async function(s, a, u) {
5
6
  const t = await g(s, a, u);
6
7
  if (!q(t.url))
7
8
  return {
@@ -60,16 +61,17 @@ const p = {}, j = async function(s, a, u) {
60
61
  });
61
62
  };
62
63
  function O(s) {
63
- return new w(j, s);
64
+ return new w(x, s);
64
65
  }
65
- const o = O(), T = o.setConfig, U = o.head, C = o.get, E = o.post, L = o.del, N = o.put, A = o.patch;
66
+ const o = O(), U = o.setConfig, C = o.head, E = o.get, L = o.post, N = o.del, S = o.put, A = o.patch;
66
67
  export {
67
68
  O as NetRequest,
68
- L as del,
69
- C as get,
70
- U as head,
69
+ N as del,
70
+ E as get,
71
+ C as head,
71
72
  A as patch,
72
- E as post,
73
- N as put,
74
- T as setGlobalConfig
73
+ L as post,
74
+ S as put,
75
+ U as setGlobalConfig,
76
+ P as version
75
77
  };
@@ -0,0 +1,2 @@
1
+ "use strict";var L=Object.defineProperty;var U=(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)=>(U(t,typeof e!="symbol"?e+"":e,n),n);async function x(t,e,n){var b;const s=Object.assign({method:"GET"},n),r="FormData"in globalThis?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":"Blob"in globalThis&&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]=H(i[h]))});const d=e.getFullUrl(t),l=P(s.body),u=s.timeout||e.get("timeout"),g=await async function(){var O;const h=e.get("requestTransformer");return h?await h({headers:o,params:c,method:a,url:d,body:l}):await((O=e.get("requestHandler"))==null?void 0:O(o,c,a,t))}(),m=typeof g=="string"&&g?g:d;return(b=e.get("logHandler"))==null||b({type:"ready",url:m,method:a,headers:o,timeout:u,body:l}),{url:m,method:a,body:l,params:c,headers:o,timeout:u,abort:s.abort,credentials:s.credentials||e.get("credentials")}}function H(t){return typeof t=="string"?t:Array.isArray(t)?t.join(","):t+""}function P(t){if(t)return typeof t=="string"||t instanceof URLSearchParams||t instanceof ArrayBuffer||"Blob"in globalThis&&t instanceof Blob||"FormData"in globalThis&&t instanceof FormData?t:JSON.stringify(t)}function B(t){return new Promise(e=>setTimeout(e,Math.max(0,t)))}function k(){}function R(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 q=/^(?:https?:)?\/\/.+$/i,K=/^https?:\/\/.+$/i,S=/^\{[\d\D]*\}$/,I=/^\[[\d\D]*\]$/;function p(t,e=!1){return e?q.test(t):K.test(t)}function N(t){return t==null}function M(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 E(t){return S.test(t)||I.test(t)}async function G(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 J(t,e="数据未能正确识别"){return typeof t=="function"?{guard:t,message:e}:{guard:t.guard,message:t.message||e}}function $(t,e=""){return!e||p(t,!0)?v(t):(v(e)+"/"+t).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function v(t){return p(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 _(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 V(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]=_(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 C="data",y="message";function W(t,e,n,s,r){const a=r||s;return j(t)?te(a.ok||s.ok,t,e,n):Y(a.failed||s.failed,e,n)}const X=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||y)+" 作为错误消息");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||C)+" 作为响应数据,读取 "+(s.messageField||y)+" 作为提示消息"),s.statusField&&e.push(" 当 "+s.statusField+" 为 "+(s.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),s.ignoreMessage&&e.push(" 并忽略以下消息:"+s.ignoreMessage);break}return e.join(`
2
+ `)};function Y(t,e,n){const s=t||{resolve:"json",messageField:y},r={ok:!1,code:e,message:n,data:null};switch(s.resolve){case"body":r.message=F(n)||n;break;case"json":const{code:a,message:o}=z(n,s.statusField,s.messageField);r.code=a||e,r.message=F(n)||o;break}return r}function z(t,e,n=y){if(!E(t))return{message:""};const s=R(t);return!s||!M(s)?{message:t}:{code:e?w(s,e):"",message:w(s,n)||t}}function w(t,e){const n=Array.isArray(e)?e:[e];for(const s of n)if(s in t)return Q(t[s]);return""}function Q(t){return t?typeof t=="string"?t:JSON.stringify(t):""}const Z=/<title>([^<]+)<\/title>/i,ee=/<message>([^<]+)<\/message>/i;function F(t){const e=t.match(Z);if(e)return e[1];const n=t.match(ee);return n?n[1]:""}function te(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=E(s)?R(s):s,a;const o=R(s);if(!o||!M(o))return a.ok=!1,a.code="ResponseFormatError",a.message="响应内容无法格式化为 Object",a;const i=r.statusField,c=r.statusOKValue||"",d=r.dataField||C,l=r.messageField||y,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=w(o,l),u&&a.message&&(Array.isArray(u)&&u.includes(a.message)||typeof u=="string"&&a.message===u)&&(a.message=""),a}function j(t){return t>=200&&t<400}async function D(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,m=`[cost ${g}][${u}] ${u<0?l.body:""}`;c({type:"finished",url:e,method:l.method,retry:a,maxRetry:o,message:a===0?`finish ${m}`:`retry ${a}/${o} finish ${m}`,response:l,headers:l.headers,cost:g});const b=j(u);if(!o||i==="network"&&u>0||i==="status"&&b||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 B(Math.max(100,h==="2EB"?Math.pow(2,a)*1e3:typeof h=="function"?h(a+1)||0:h)),await D(t,e,n,s,a+1)}function se(t,e,n,s){var o,i;if(t.status<0)return T({ok:!1,status:t.status,code:t.statusText,headers:{},message:"",data:null},`${t.method} ${e} ${t.statusText}`,t.method,e,n,s);j(t.status)||(o=n.get("errorHandler"))==null||o(t.status,t.method,e);const r={...W(t.status,t.statusText,t.body,n.get("responseRule"),s==null?void 0:s.responseRule),status:t.status,headers:Object.fromEntries(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 T(r,a,t.method,e,n,s)}function T(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 A{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)&&!p(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("/")?$(e):$(e,this.config.baseURL)}showMessage(e,n){this.config.messageHandler&&n&&this.config.messageHandler(e,n)}}class ne{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 ae(t,e,n,s){if(e.ok&&!N(e.data)&&s){const r=J(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 re{constructor(e,n){f(this,"agent");f(this,"config");f(this,"cache");this.config=new A(n),this.agent=e,this.cache=new ne(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){return await this.agent(e,this.config,n)}async guard(e,n,s){return ae(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 oe="1.5.4";exports.NetRequestHandler=re;exports.Ot=k;exports.R=p;exports.RequestGlobalConfig=A;exports.convertOptions=x;exports.getResponseRulesDescription=X;exports.handleResponse=se;exports.retryRequest=D;exports.sn=G;exports.version=oe;exports.wt=V;
@@ -1,82 +1,83 @@
1
- var A = Object.defineProperty;
2
- var C = (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) => (C(t, typeof e != "symbol" ? e + "" : e, n), n);
4
- async function se(t, e, n) {
1
+ var C = Object.defineProperty;
2
+ var D = (t, e, a) => e in t ? C(t, e, { enumerable: !0, configurable: !0, writable: !0, value: a }) : t[e] = a;
3
+ var f = (t, e, a) => (D(t, typeof e != "symbol" ? e + "" : e, a), a);
4
+ async function te(t, e, a) {
5
5
  var b;
6
- const s = Object.assign({ method: "GET" }, n), r = "FormData" in globalThis ? s.body instanceof FormData : !1, a = r ? "POST" : s.method;
7
- (a === "GET" || a === "HEAD" || a === "DELETE") && s.body !== void 0 && (console.warn("request body is invalid with method get, head, delete"), delete s.body);
8
- const i = Object.assign(
6
+ const s = Object.assign({ method: "GET" }, a), r = "FormData" in globalThis ? s.body instanceof FormData : !1, n = r && s.method !== "POST" && s.method !== "PUT" ? "POST" : s.method;
7
+ (n === "GET" || n === "HEAD" || n === "DELETE") && s.body !== void 0 && (console.warn("request body is invalid with method get, head, delete"), delete s.body);
8
+ const o = Object.assign(
9
9
  r ? {} : {
10
10
  "Content-Type": "Blob" in globalThis && s.body instanceof Blob ? s.body.type || "application/octet-stream" : "application/json;charset=utf-8"
11
11
  },
12
12
  s.headers
13
- ), o = s.params || {}, c = {};
14
- Object.keys(o).forEach((h) => {
15
- o[h] !== void 0 && (c[h] = D(o[h]));
13
+ ), i = s.params || {}, c = {};
14
+ Object.keys(i).forEach((h) => {
15
+ i[h] !== void 0 && (c[h] = A(i[h]));
16
16
  });
17
- const d = e.getFullUrl(t), l = U(s.body), u = s.timeout || e.get("timeout"), g = await async function() {
17
+ const d = e.getFullUrl(t), l = L(s.body), u = s.timeout || e.get("timeout"), g = await async function() {
18
18
  var O;
19
19
  const h = e.get("requestTransformer");
20
- return h ? await h({ headers: i, params: c, method: a, url: d, body: l }) : await ((O = e.get("requestHandler")) == null ? void 0 : O(i, c, a, t));
20
+ return h ? await h({ headers: o, params: c, method: n, url: d, body: l }) : await ((O = e.get("requestHandler")) == null ? void 0 : O(o, c, n, t));
21
21
  }(), m = typeof g == "string" && g ? g : d;
22
- return (b = e.get("logHandler")) == null || b({ type: "ready", url: m, method: a, headers: i, timeout: u, body: l }), {
22
+ return (b = e.get("logHandler")) == null || b({ type: "ready", url: m, method: n, headers: o, timeout: u, body: l }), {
23
23
  url: m,
24
- method: a,
24
+ method: n,
25
25
  body: l,
26
26
  params: c,
27
- headers: i,
27
+ headers: o,
28
28
  timeout: u,
29
29
  abort: s.abort,
30
30
  credentials: s.credentials || e.get("credentials")
31
31
  };
32
32
  }
33
- function D(t) {
33
+ function A(t) {
34
34
  return typeof t == "string" ? t : Array.isArray(t) ? t.join(",") : t + "";
35
35
  }
36
- function U(t) {
36
+ function L(t) {
37
37
  if (t)
38
38
  return typeof t == "string" || t instanceof URLSearchParams || t instanceof ArrayBuffer || "Blob" in globalThis && t instanceof Blob || "FormData" in globalThis && t instanceof FormData ? t : JSON.stringify(t);
39
39
  }
40
- function L(t) {
40
+ function U(t) {
41
41
  return new Promise((e) => setTimeout(e, Math.max(0, t)));
42
42
  }
43
43
  function x() {
44
44
  }
45
45
  function p(t, e) {
46
46
  try {
47
- const n = JSON.parse(t);
48
- return e ? e(n) ? n : null : n;
47
+ const a = JSON.parse(t);
48
+ return e ? e(a) ? a : null : a;
49
49
  } catch {
50
50
  return null;
51
51
  }
52
52
  }
53
- const B = /^(?:https?:)?\/\/.+/i, H = /^https?:\/\//i, K = /^\{[\d\D]*\}$/, P = /^\[[\d\D]*\]$/;
53
+ "" + Math.random().toString(32).slice(2);
54
+ const P = /^(?:https?:)?\/\/.+$/i, B = /^https?:\/\/.+$/i, H = /^\{[\d\D]*\}$/, K = /^\[[\d\D]*\]$/;
54
55
  function R(t, e = !1) {
55
- return e ? B.test(t) : H.test(t);
56
- }
57
- function I(t) {
58
- return t == null;
56
+ return e ? P.test(t) : B.test(t);
59
57
  }
60
58
  function S(t) {
61
- return t !== null && typeof t == "object" && !Array.isArray(t);
59
+ return t == null;
62
60
  }
63
- function T(t) {
64
- return S(t) && Object.keys(t).every((e) => typeof e == "string");
61
+ function k(t, ...e) {
62
+ if (!t || typeof t != "object")
63
+ return !1;
64
+ const a = Object.getPrototypeOf(t);
65
+ return a !== Object.prototype && a !== null ? !1 : e.every((s) => s in t);
65
66
  }
66
67
  function M(t) {
67
- return K.test(t) || P.test(t);
68
+ return H.test(t) || K.test(t);
68
69
  }
69
- async function ne(t) {
70
+ async function se(t) {
70
71
  return await new Promise(function(e) {
71
- const n = document.getElementsByTagName("head")[0], s = document.createElement("script");
72
+ const a = document.getElementsByTagName("head")[0], s = document.createElement("script");
72
73
  s.setAttribute("type", "text/javascript"), s.setAttribute("charset", "utf-8"), s.onload = function() {
73
- n.removeChild(s), e(!0);
74
+ a.removeChild(s), e(!0);
74
75
  }, s.onerror = function() {
75
- n.removeChild(s), e(!1);
76
- }, s.setAttribute("src", t), n.appendChild(s);
76
+ a.removeChild(s), e(!1);
77
+ }, s.setAttribute("src", t), a.appendChild(s);
77
78
  });
78
79
  }
79
- function q(t, e = "数据未能正确识别") {
80
+ function I(t, e = "数据未能正确识别") {
80
81
  return typeof t == "function" ? {
81
82
  guard: t,
82
83
  message: e
@@ -86,9 +87,9 @@ function q(t, e = "数据未能正确识别") {
86
87
  };
87
88
  }
88
89
  function $(t, e = "") {
89
- return !e || R(t, !0) ? F(t) : (F(e) + "/" + t).replace(/\/{2,}/g, "/").replace(/:\//, "://");
90
+ return !e || R(t, !0) ? v(t) : (v(e) + "/" + t).replace(/\/{2,}/g, "/").replace(/:\//, "://");
90
91
  }
91
- function F(t) {
92
+ function v(t) {
92
93
  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(/^\/+/, "");
93
94
  }
94
95
  function N(t, e) {
@@ -97,34 +98,34 @@ function N(t, e) {
97
98
  return t.replace(/\?[^#]*/, "");
98
99
  } else
99
100
  return t;
100
- const n = t.split("#"), s = n[0].split("?"), r = s[0], a = s.length > 1 ? s[1] : "", i = n.length > 1 ? "#" + n[1] : "", o = typeof e == "string" ? [e] : Array.isArray(e) ? e : [];
101
- return !o.length || !a ? n[0] + i : (o.map((c) => c.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (r + "?" + a.replace(new RegExp("(?:^|&)(?:" + o.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + i);
101
+ const a = t.split("#"), s = a[0].split("?"), r = s[0], n = s.length > 1 ? s[1] : "", o = a.length > 1 ? "#" + a[1] : "", i = typeof e == "string" ? [e] : Array.isArray(e) ? e : [];
102
+ return !i.length || !n ? a[0] + o : (i.map((c) => c.replace(/([\\(){}[\]^$+\-*?|])/g, "\\$1")), (r + "?" + n.replace(new RegExp("(?:^|&)(?:" + i.join("|") + ")=[^&$]+", "g"), "").replace(/^&/, "")).replace(/\?$/, "") + o);
102
103
  }
103
- function ae(t, e, n = !1) {
104
- const s = typeof e == "string" ? e : Object.keys(e).map((i) => `${i}=${encodeURIComponent(e[i])}`).join("&");
104
+ function ae(t, e, a = !1) {
105
+ const s = typeof e == "string" ? e : Object.keys(e).map((o) => `${o}=${encodeURIComponent(e[o])}`).join("&");
105
106
  if (!s)
106
107
  return t;
107
108
  const r = t.split("#");
108
- n && (r[0] = N(
109
+ a && (r[0] = N(
109
110
  r[0],
110
- (s.match(/([^=&#?]+)=[^&#]+/g) || []).map((i) => i.replace(/=.+$/, ""))
111
+ (s.match(/([^=&#?]+)=[^&#]+/g) || []).map((o) => o.replace(/=.+$/, ""))
111
112
  ));
112
- const a = r[0].indexOf("?") + 1 ? "&" : "?";
113
- return (r[0] + a + s + (r.length > 1 ? "#" + r[1] : "")).replace(/\?&/, "?");
113
+ const n = r[0].indexOf("?") + 1 ? "&" : "?";
114
+ return (r[0] + n + s + (r.length > 1 ? "#" + r[1] : "")).replace(/\?&/, "?");
114
115
  }
115
116
  const E = "data", y = "message";
116
- function J(t, e, n, s, r) {
117
- const a = r || s;
118
- return j(t) ? z(a.ok || s.ok, t, e, n) : G(a.failed || s.failed, e, n);
117
+ function q(t, e, a, s, r) {
118
+ const n = r || s;
119
+ return j(t) ? X(n.ok || s.ok, t, e, a) : G(n.failed || s.failed, e, a);
119
120
  }
120
- const re = function(t) {
121
- const e = [], n = t.failed || { resolve: "json" };
122
- switch (e.push("- 当http状态码 <200 或者 >=400 时"), n.resolve) {
121
+ const ne = function(t) {
122
+ const e = [], a = t.failed || { resolve: "json" };
123
+ switch (e.push("- 当http状态码 <200 或者 >=400 时"), a.resolve) {
123
124
  case "body":
124
125
  e.push(" 将响应内容格式化为字符串并作为错误消息");
125
126
  break;
126
127
  case "json":
127
- e.push(" 将响应解析为json,并读取 " + (n.messageField || y) + " 作为错误消息");
128
+ e.push(" 将响应解析为json,并读取 " + (a.messageField || y) + " 作为错误消息");
128
129
  break;
129
130
  }
130
131
  const s = t.ok || { resolve: "body" };
@@ -141,139 +142,139 @@ const re = function(t) {
141
142
  return e.join(`
142
143
  `);
143
144
  };
144
- function G(t, e, n) {
145
+ function G(t, e, a) {
145
146
  const s = t || { resolve: "json", messageField: y }, r = {
146
147
  ok: !1,
147
148
  code: e,
148
- message: n,
149
+ message: a,
149
150
  data: null
150
151
  };
151
152
  switch (s.resolve) {
152
153
  case "body":
153
- r.message = v(n) || n;
154
+ r.message = F(a) || a;
154
155
  break;
155
156
  case "json":
156
- const { code: a, message: i } = V(n, s.statusField, s.messageField);
157
- r.code = a || e, r.message = v(n) || i;
157
+ const { code: n, message: o } = J(a, s.statusField, s.messageField);
158
+ r.code = n || e, r.message = F(a) || o;
158
159
  break;
159
160
  }
160
161
  return r;
161
162
  }
162
- function V(t, e, n = y) {
163
+ function J(t, e, a = y) {
163
164
  if (!M(t))
164
165
  return { message: "" };
165
166
  const s = p(t);
166
- return !s || !T(s) ? { message: t } : {
167
+ return !s || !k(s) ? { message: t } : {
167
168
  code: e ? w(s, e) : "",
168
- message: w(s, n) || t
169
+ message: w(s, a) || t
169
170
  };
170
171
  }
171
172
  function w(t, e) {
172
- const n = Array.isArray(e) ? e : [e];
173
- for (const s of n)
173
+ const a = Array.isArray(e) ? e : [e];
174
+ for (const s of a)
174
175
  if (s in t)
175
- return W(t[s]);
176
+ return _(t[s]);
176
177
  return "";
177
178
  }
178
- function W(t) {
179
+ function _(t) {
179
180
  return t ? typeof t == "string" ? t : JSON.stringify(t) : "";
180
181
  }
181
- const Q = /<title>([^<]+)<\/title>/i, Z = /<message>([^<]+)<\/message>/i;
182
- function v(t) {
183
- const e = t.match(Q);
182
+ const V = /<title>([^<]+)<\/title>/i, W = /<message>([^<]+)<\/message>/i;
183
+ function F(t) {
184
+ const e = t.match(V);
184
185
  if (e)
185
186
  return e[1];
186
- const n = t.match(Z);
187
- return n ? n[1] : "";
187
+ const a = t.match(W);
188
+ return a ? a[1] : "";
188
189
  }
189
- function z(t, e, n, s) {
190
- const r = t || { resolve: "body" }, a = {
190
+ function X(t, e, a, s) {
191
+ const r = t || { resolve: "body" }, n = {
191
192
  ok: !0,
192
- code: n,
193
+ code: a,
193
194
  message: "",
194
195
  data: null
195
196
  };
196
197
  if (e === 202 || e === 204 || !s)
197
- return a;
198
+ return n;
198
199
  if (r.resolve === "body")
199
- return a.data = M(s) ? p(s) : s, a;
200
- const i = p(s);
201
- if (!i || !T(i))
202
- return a.ok = !1, a.code = "ResponseFormatError", a.message = "响应内容无法格式化为 Object", a;
203
- const o = r.statusField, c = r.statusOKValue || "", d = r.dataField || E, l = r.messageField || y, u = r.ignoreMessage || "";
204
- if (o && !(o in i))
205
- return a.ok = !1, a.code = "ResponseFieldMissing", a.message = "响应内容找不到状态字段 " + o, a;
206
- const g = o ? i[o] + "" : "";
207
- return a.ok = o ? g === c : !0, a.code = g || n, a.data = d === !0 ? i : d in i ? i[d] : null, a.message = w(i, l), u && a.message && (Array.isArray(u) && u.includes(a.message) || typeof u == "string" && a.message === u) && (a.message = ""), a;
200
+ return n.data = M(s) ? p(s) : s, n;
201
+ const o = p(s);
202
+ if (!o || !k(o))
203
+ return n.ok = !1, n.code = "ResponseFormatError", n.message = "响应内容无法格式化为 Object", n;
204
+ const i = r.statusField, c = r.statusOKValue || "", d = r.dataField || E, l = r.messageField || y, u = r.ignoreMessage || "";
205
+ if (i && !(i in o))
206
+ return n.ok = !1, n.code = "ResponseFieldMissing", n.message = "响应内容找不到状态字段 " + i, n;
207
+ const g = i ? o[i] + "" : "";
208
+ return n.ok = i ? g === c : !0, n.code = g || a, n.data = d === !0 ? o : d in o ? o[d] : null, n.message = w(o, l), u && n.message && (Array.isArray(u) && u.includes(n.message) || typeof u == "string" && n.message === u) && (n.message = ""), n;
208
209
  }
209
210
  function j(t) {
210
211
  return t >= 200 && t < 400;
211
212
  }
212
- async function X(t, e, n, s, r) {
213
- const a = r || 0, i = Math.max(0, Math.min(10, (s == null ? void 0 : s.maxRetry) ?? n.get("maxRetry") ?? 0)), o = (s == null ? void 0 : s.retryResolve) ?? n.get("retryResolve"), c = n.get("logHandler") || x;
213
+ async function Y(t, e, a, s, r) {
214
+ const n = r || 0, o = Math.max(0, Math.min(10, (s == null ? void 0 : s.maxRetry) ?? a.get("maxRetry") ?? 0)), i = (s == null ? void 0 : s.retryResolve) ?? a.get("retryResolve"), c = a.get("logHandler") || x;
214
215
  c({
215
216
  type: "prepear",
216
217
  url: e,
217
218
  method: (s == null ? void 0 : s.method) || "GET",
218
- retry: a,
219
- maxRetry: i,
220
- message: a === 0 ? "start" : `retry ${a}/${i} start`,
219
+ retry: n,
220
+ maxRetry: o,
221
+ message: n === 0 ? "start" : `retry ${n}/${o} start`,
221
222
  headers: s == null ? void 0 : s.headers,
222
223
  options: s
223
224
  });
224
- const d = Date.now(), l = await t(e, n, s), u = l.status, g = Date.now() - d, m = `[cost ${g}][${u}] ${u < 0 ? l.body : ""}`;
225
+ const d = Date.now(), l = await t(e, a, s), u = l.status, g = Date.now() - d, m = `[cost ${g}][${u}] ${u < 0 ? l.body : ""}`;
225
226
  c({
226
227
  type: "finished",
227
228
  url: e,
228
229
  method: l.method,
229
- retry: a,
230
- maxRetry: i,
231
- message: a === 0 ? `finish ${m}` : `retry ${a}/${i} finish ${m}`,
230
+ retry: n,
231
+ maxRetry: o,
232
+ message: n === 0 ? `finish ${m}` : `retry ${n}/${o} finish ${m}`,
232
233
  response: l,
233
234
  headers: l.headers,
234
235
  cost: g
235
236
  });
236
237
  const b = j(u);
237
- if (!i || o === "network" && u > 0 || o === "status" && b || Array.isArray(o) && !o.includes(u) || typeof o == "function" && o(l, a) !== !0 || a >= i)
238
+ if (!o || i === "network" && u > 0 || i === "status" && b || Array.isArray(i) && !i.includes(u) || typeof i == "function" && i(l, n) !== !0 || n >= o)
238
239
  return l;
239
- const h = (s == null ? void 0 : s.retryInterval) ?? n.get("retryInterval") ?? 1e3;
240
- return await L(
240
+ const h = (s == null ? void 0 : s.retryInterval) ?? a.get("retryInterval") ?? 1e3;
241
+ return await U(
241
242
  Math.max(
242
243
  100,
243
- h === "2EB" ? Math.pow(2, a) * 1e3 : typeof h == "function" ? h(a + 1) || 0 : h
244
+ h === "2EB" ? Math.pow(2, n) * 1e3 : typeof h == "function" ? h(n + 1) || 0 : h
244
245
  )
245
- ), await X(t, e, n, s, a + 1);
246
+ ), await Y(t, e, a, s, n + 1);
246
247
  }
247
- function ie(t, e, n, s) {
248
- var i, o;
248
+ function re(t, e, a, s) {
249
+ var o, i;
249
250
  if (t.status < 0)
250
- return k(
251
+ return T(
251
252
  { ok: !1, status: t.status, code: t.statusText, headers: {}, message: "", data: null },
252
253
  `${t.method} ${e} ${t.statusText}`,
253
254
  t.method,
254
255
  e,
255
- n,
256
+ a,
256
257
  s
257
258
  );
258
- j(t.status) || (i = n.get("errorHandler")) == null || i(t.status, t.method, e);
259
+ j(t.status) || (o = a.get("errorHandler")) == null || o(t.status, t.method, e);
259
260
  const r = {
260
- ...J(t.status, t.statusText, t.body, n.get("responseRule"), s == null ? void 0 : s.responseRule),
261
+ ...q(t.status, t.statusText, t.body, a.get("responseRule"), s == null ? void 0 : s.responseRule),
261
262
  status: t.status,
262
263
  headers: Object.fromEntries(Object.entries(t.headers || {}).map(([c, d]) => [c.toLowerCase(), d]))
263
264
  };
264
- (o = n.get("responseHandler")) == null || o({ ...r }, t.method, e);
265
- const a = r.ok ? r.message : `${t.method} ${e} [${r.code || t.statusText}] ${r.message || t.statusText}`;
266
- return k(r, a, t.method, e, n, s);
267
- }
268
- function k(t, e, n, s, r, a) {
269
- const i = r.get("message"), o = i === !1 || (a == null ? void 0 : a.message) === !1 ? !1 : (a == null ? void 0 : a.message) || i;
270
- if (o !== !1) {
271
- const c = typeof o == "function" ? o(t, n, s, e) : e;
265
+ (i = a.get("responseHandler")) == null || i({ ...r }, t.method, e);
266
+ const n = r.ok ? r.message : `${t.method} ${e} [${r.code || t.statusText}] ${r.message || t.statusText}`;
267
+ return T(r, n, t.method, e, a, s);
268
+ }
269
+ function T(t, e, a, s, r, n) {
270
+ const o = r.get("message"), i = o === !1 || (n == null ? void 0 : n.message) === !1 ? !1 : (n == null ? void 0 : n.message) || o;
271
+ if (i !== !1) {
272
+ const c = typeof i == "function" ? i(t, a, s, e) : e;
272
273
  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);
273
274
  }
274
275
  return t;
275
276
  }
276
- class Y {
277
+ class z {
277
278
  constructor(e) {
278
279
  // 保存的配置需要部分字段强制设置默认值
279
280
  f(this, "config", {
@@ -309,18 +310,18 @@ class Y {
309
310
  return e.startsWith("/") ? $(e) : $(e, this.config.baseURL);
310
311
  }
311
312
  /** 提示消息 */
312
- showMessage(e, n) {
313
- this.config.messageHandler && n && this.config.messageHandler(e, n);
313
+ showMessage(e, a) {
314
+ this.config.messageHandler && a && this.config.messageHandler(e, a);
314
315
  }
315
316
  }
316
- class _ {
317
+ class Q {
317
318
  constructor(e = 500) {
318
319
  f(this, "ttl");
319
320
  f(this, "cache");
320
321
  this.cache = {}, this.ttl = Math.max(e, 0);
321
322
  }
322
- getKey(e, n) {
323
- const s = Object.keys(n || {}).sort().map((r) => `${r}#${n == null ? void 0 : n[r]}`);
323
+ getKey(e, a) {
324
+ const s = Object.keys(a || {}).sort().map((r) => `${r}#${a == null ? void 0 : a[r]}`);
324
325
  return e + s.join(",");
325
326
  }
326
327
  updateTTL(e) {
@@ -329,41 +330,41 @@ class _ {
329
330
  get(e) {
330
331
  if (this.ttl === 0)
331
332
  return null;
332
- const n = this.cache[e];
333
- return n ? n.ttl < Date.now() ? (delete this.cache[e], null) : n.res : null;
333
+ const a = this.cache[e];
334
+ return a ? a.ttl < Date.now() ? (delete this.cache[e], null) : a.res : null;
334
335
  }
335
- set(e, n) {
336
+ set(e, a) {
336
337
  this.ttl !== 0 && (this.cache[e] = {
337
338
  ttl: Date.now() + this.ttl,
338
- res: n
339
+ res: a
339
340
  });
340
341
  }
341
342
  }
342
- function ee(t, e, n, s) {
343
- if (e.ok && !I(e.data) && s) {
344
- const r = q(s, "响应数据未能正确识别");
345
- return r.guard(e.data) || (console.error("ResponseCheckFaild", t, e.data), n.showMessage(!0, `${t} ${r.message}`), e.data = null), e;
343
+ function Z(t, e, a, s) {
344
+ if (e.ok && !S(e.data) && s) {
345
+ const r = I(s, "响应数据未能正确识别");
346
+ return r.guard(e.data) || (console.error("ResponseCheckFaild", t, e.data), a.showMessage(!0, `${t} ${r.message}`), e.data = null), e;
346
347
  }
347
348
  return e;
348
349
  }
349
350
  class oe {
350
- constructor(e, n) {
351
+ constructor(e, a) {
351
352
  f(this, "agent");
352
353
  f(this, "config");
353
354
  f(this, "cache");
354
- this.config = new Y(n), this.agent = e, this.cache = new _(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);
355
+ this.config = new z(a), this.agent = e, this.cache = new Q(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);
355
356
  }
356
357
  /**
357
358
  * 执行网络请求
358
359
  */
359
- async exec(e, n) {
360
- return await this.agent(e, this.config, n);
360
+ async exec(e, a) {
361
+ return await this.agent(e, this.config, a);
361
362
  }
362
363
  /**
363
364
  * 检查响应的数据类型
364
365
  */
365
- async guard(e, n, s) {
366
- return ee(e, n, this.config, s);
366
+ async guard(e, a, s) {
367
+ return Z(e, a, this.config, s);
367
368
  }
368
369
  /**
369
370
  * 修改默认请求配置: baesURL / timeout / credentials / errorHandler / messageHandler / responseHandler / logHandler / responseRule
@@ -380,45 +381,47 @@ class oe {
380
381
  /**
381
382
  * 发送一个 HEAD 请求,并且不处理响应 body
382
383
  */
383
- async head(e, n) {
384
- const s = Object.assign({}, n || null);
384
+ async head(e, a) {
385
+ const s = Object.assign({}, a || null);
385
386
  return s.method = "HEAD", this.guard(e, await this.exec(e, s), null);
386
387
  }
387
- async get(e, n, s) {
388
+ async get(e, a, s) {
388
389
  const r = Object.assign({}, s || null);
389
390
  r.method = "GET";
390
- const a = this.cache.getKey(e, r.params), i = this.cache.get(a);
391
- if (i)
392
- return this.guard(e, await i, n || null);
393
- const o = this.exec(e, r);
394
- return this.cache.set(a, o), this.guard(e, await o, n || null);
391
+ const n = this.cache.getKey(e, r.params), o = this.cache.get(n);
392
+ if (o)
393
+ return this.guard(e, await o, a || null);
394
+ const i = this.exec(e, r);
395
+ return this.cache.set(n, i), this.guard(e, await i, a || null);
395
396
  }
396
- async post(e, n, s, r) {
397
- const a = Object.assign({}, r || null);
398
- return a.method = "POST", a.body = n, this.guard(e, await this.exec(e, a), s || null);
397
+ async post(e, a, s, r) {
398
+ const n = Object.assign({}, r || null);
399
+ return n.method = "POST", n.body = a, this.guard(e, await this.exec(e, n), s || null);
399
400
  }
400
- async del(e, n, s) {
401
+ async del(e, a, s) {
401
402
  const r = Object.assign({}, s || null);
402
- return r.method = "DELETE", this.guard(e, await this.exec(e, r), n || null);
403
+ return r.method = "DELETE", this.guard(e, await this.exec(e, r), a || null);
403
404
  }
404
- async put(e, n, s, r) {
405
- const a = Object.assign({}, r || null);
406
- return a.method = "PUT", a.body = n, this.guard(e, await this.exec(e, a), s || null);
405
+ async put(e, a, s, r) {
406
+ const n = Object.assign({}, r || null);
407
+ return n.method = "PUT", n.body = a, this.guard(e, await this.exec(e, n), s || null);
407
408
  }
408
- async patch(e, n, s, r) {
409
- const a = Object.assign({}, r || null);
410
- return a.method = "PATCH", a.body = n, this.guard(e, await this.exec(e, a), s || null);
409
+ async patch(e, a, s, r) {
410
+ const n = Object.assign({}, r || null);
411
+ return n.method = "PATCH", n.body = a, this.guard(e, await this.exec(e, n), s || null);
411
412
  }
412
413
  }
414
+ const ie = "1.5.4";
413
415
  export {
414
416
  oe as N,
415
- Y as R,
416
- R as S,
417
- ne as U,
418
- ie as a,
419
- X as b,
420
- se as c,
421
- re as g,
422
- x as h,
423
- ae as r
417
+ x as O,
418
+ z as R,
419
+ R as a,
420
+ te as c,
421
+ ne as g,
422
+ re as h,
423
+ Y as r,
424
+ se as s,
425
+ ie as v,
426
+ ae as w
424
427
  };
@@ -0,0 +1 @@
1
+ export declare const version = "1.5.4";
package/dist/wx.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./main-CFU3RpxD.cjs"),l=async function(t,n,r){return o.handleResponse(await o.retryRequest(f,t,n,r),t,n,r)},f=async function(t,n,r){const e=await o.convertOptions(t,n,r),u=e.method==="PATCH"?"POST":e.method,a=o.rt(e.url,e.params);return globalThis.wx?new Promise(d=>{wx.request({url:a,data:e.body,header:e.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:e.method==="HEAD"?"":p(c.data)})}})}):{url:a,method:u,status:-1,statusText:"NotSupport",body:"NotFound namespace of wx"}};function p(t){return typeof t=="string"?t:t instanceof ArrayBuffer&&"TextDecoder"in globalThis?new TextDecoder().decode(t):JSON.stringify(t)}function i(t){return new o.NetRequestHandler(l,t)}const s=i(),g=s.setConfig,h=s.head,y=s.get,T=s.post,b=s.del,x=s.put;exports.NetRequest=i;exports.del=b;exports.get=y;exports.head=h;exports.post=T;exports.put=x;exports.setGlobalConfig=g;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./version-B09aAqk-.cjs"),l=async function(t,n,r){return s.handleResponse(await s.retryRequest(f,t,n,r),t,n,r)},f=async function(t,n,r){const e=await s.convertOptions(t,n,r),u=e.method==="PATCH"?"POST":e.method,a=s.wt(e.url,e.params);return globalThis.wx?new Promise(i=>{wx.request({url:a,data:e.body,header:e.headers,method:u,dataType:"string",responseType:"text",fail(){i({url:a,method:u,status:-1,statusText:"NetworkError",body:""})},success(c){i({url:a,method:u,status:c.statusCode,statusText:c.statusCode+"",headers:{...c.header},body:e.method==="HEAD"?"":p(c.data)})}})}):{url:a,method:u,status:-1,statusText:"NotSupport",body:"NotFound namespace of wx"}};function p(t){return typeof t=="string"?t:t instanceof ArrayBuffer&&"TextDecoder"in globalThis?new TextDecoder().decode(t):JSON.stringify(t)}function d(t){return new s.NetRequestHandler(l,t)}const o=d(),g=o.setConfig,h=o.head,y=o.get,T=o.post,b=o.del,w=o.put;exports.version=s.version;exports.NetRequest=d;exports.del=b;exports.get=y;exports.head=h;exports.post=T;exports.put=w;exports.setGlobalConfig=g;
package/dist/wx.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { NetRequestHandler } from "./inc/main";
2
2
  import type { IRequestGlobalConfig } from "./inc/type";
3
+ export * from "./version";
3
4
  export type { IRequestGlobalConfig } from "./inc/type";
4
5
  /**
5
6
  * 创建新的实例空间,配置和缓存跟全局默认实例是隔离的
package/dist/wx.js CHANGED
@@ -1,8 +1,9 @@
1
- import { a as d, b as i, c as l, r as f, N as p } from "./main-DS7dDlqb.js";
1
+ import { h as d, r as i, c as f, w as l, N as p } from "./version-BXzKbsH3.js";
2
+ import { v as A } from "./version-BXzKbsH3.js";
2
3
  const h = async function(t, o, r) {
3
4
  return d(await i(x, t, o, r), t, o, r);
4
5
  }, x = async function(t, o, r) {
5
- const e = await l(t, o, r), n = e.method === "PATCH" ? "POST" : e.method, a = f(e.url, e.params);
6
+ const e = await f(t, o, r), n = e.method === "PATCH" ? "POST" : e.method, a = l(e.url, e.params);
6
7
  return globalThis.wx ? new Promise((c) => {
7
8
  wx.request({
8
9
  url: a,
@@ -27,7 +28,7 @@ const h = async function(t, o, r) {
27
28
  status: u.statusCode,
28
29
  statusText: u.statusCode + "",
29
30
  headers: { ...u.header },
30
- body: e.method === "HEAD" ? "" : y(u.data)
31
+ body: e.method === "HEAD" ? "" : w(u.data)
31
32
  });
32
33
  }
33
34
  });
@@ -39,19 +40,20 @@ const h = async function(t, o, r) {
39
40
  body: "NotFound namespace of wx"
40
41
  };
41
42
  };
42
- function y(t) {
43
+ function w(t) {
43
44
  return typeof t == "string" ? t : t instanceof ArrayBuffer && "TextDecoder" in globalThis ? new TextDecoder().decode(t) : JSON.stringify(t);
44
45
  }
45
- function T(t) {
46
+ function y(t) {
46
47
  return new p(h, t);
47
48
  }
48
- const s = T(), m = s.setConfig, w = s.head, b = s.get, q = s.post, N = s.del, R = s.put;
49
+ const s = y(), T = s.setConfig, g = s.head, b = s.get, q = s.post, N = s.del, R = s.put;
49
50
  export {
50
- T as NetRequest,
51
+ y as NetRequest,
51
52
  N as del,
52
53
  b as get,
53
- w as head,
54
+ g as head,
54
55
  q as post,
55
56
  R as put,
56
- m as setGlobalConfig
57
+ T as setGlobalConfig,
58
+ A as version
57
59
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-web/request",
3
- "version": "1.5.2",
3
+ "version": "1.5.4",
4
4
  "description": "requst tools for seayoo web",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -42,7 +42,7 @@
42
42
  "node": ">=18"
43
43
  },
44
44
  "scripts": {
45
- "build": "vite build && tsc --emitDeclarationOnly",
45
+ "build": "node scripts/emitVersion.mjs && vite build && tsc --emitDeclarationOnly",
46
46
  "emit-types": "tsc --emitDeclarationOnly",
47
47
  "clear": "rimraf dist && rimraf node_modules",
48
48
  "type-check": "tsc --noEmit",
@@ -74,14 +74,14 @@
74
74
  "eslint-plugin-prettier": "^5.1.3",
75
75
  "happy-dom": "^12.10.3",
76
76
  "lint-staged": "^14.0.1",
77
- "msw": "^2.2.2",
77
+ "msw": "^2.2.3",
78
78
  "rimraf": "^5.0.5",
79
- "simple-git-hooks": "^2.9.0",
79
+ "simple-git-hooks": "^2.10.0",
80
80
  "typescript": "~5.2.2",
81
- "vite": "^5.1.4",
81
+ "vite": "^5.1.6",
82
82
  "vitest": "^1.3.1"
83
83
  },
84
84
  "dependencies": {
85
- "@seayoo-web/utils": "^1.14.1"
85
+ "@seayoo-web/utils": "^1.15.2"
86
86
  }
87
87
  }
@@ -1,2 +0,0 @@
1
- "use strict";var U=Object.defineProperty;var L=(t,e,n)=>e in t?U(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var f=(t,e,n)=>(L(t,typeof e!="symbol"?e+"":e,n),n);async function x(t,e,n){var b;const s=Object.assign({method:"GET"},n),r="FormData"in globalThis?s.body instanceof FormData:!1,a=r?"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 i=Object.assign(r?{}:{"Content-Type":"Blob"in globalThis&&s.body instanceof Blob?s.body.type||"application/octet-stream":"application/json;charset=utf-8"},s.headers),o=s.params||{},c={};Object.keys(o).forEach(h=>{o[h]!==void 0&&(c[h]=B(o[h]))});const d=e.getFullUrl(t),l=H(s.body),u=s.timeout||e.get("timeout"),g=await async function(){var O;const h=e.get("requestTransformer");return h?await h({headers:i,params:c,method:a,url:d,body:l}):await((O=e.get("requestHandler"))==null?void 0:O(i,c,a,t))}(),m=typeof g=="string"&&g?g:d;return(b=e.get("logHandler"))==null||b({type:"ready",url:m,method:a,headers:i,timeout:u,body:l}),{url:m,method:a,body:l,params:c,headers:i,timeout:u,abort:s.abort,credentials:s.credentials||e.get("credentials")}}function B(t){return typeof t=="string"?t:Array.isArray(t)?t.join(","):t+""}function H(t){if(t)return typeof t=="string"||t instanceof URLSearchParams||t instanceof ArrayBuffer||"Blob"in globalThis&&t instanceof Blob||"FormData"in globalThis&&t instanceof FormData?t:JSON.stringify(t)}function q(t){return new Promise(e=>setTimeout(e,Math.max(0,t)))}function T(){}function R(t,e){try{const n=JSON.parse(t);return e?e(n)?n:null:n}catch{return null}}const K=/^(?:https?:)?\/\/.+/i,P=/^https?:\/\//i,S=/^\{[\d\D]*\}$/,I=/^\[[\d\D]*\]$/;function p(t,e=!1){return e?K.test(t):P.test(t)}function N(t){return t==null}function G(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function M(t){return G(t)&&Object.keys(t).every(e=>typeof e=="string")}function E(t){return S.test(t)||I.test(t)}async function J(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 $(t,e=""){return!e||p(t,!0)?F(t):(F(e)+"/"+t).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function F(t){return p(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 W(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]:"",i=n.length>1?"#"+n[1]:"",o=typeof e=="string"?[e]:Array.isArray(e)?e:[];return!o.length||!a?n[0]+i:(o.map(c=>c.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(r+"?"+a.replace(new RegExp("(?:^|&)(?:"+o.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+i)}function Q(t,e,n=!1){const s=typeof e=="string"?e:Object.keys(e).map(i=>`${i}=${encodeURIComponent(e[i])}`).join("&");if(!s)return t;const r=t.split("#");n&&(r[0]=W(r[0],(s.match(/([^=&#?]+)=[^&#]+/g)||[]).map(i=>i.replace(/=.+$/,""))));const a=r[0].indexOf("?")+1?"&":"?";return(r[0]+a+s+(r.length>1?"#"+r[1]:"")).replace(/\?&/,"?")}const C="data",y="message";function Z(t,e,n,s,r){const a=r||s;return j(t)?se(a.ok||s.ok,t,e,n):X(a.failed||s.failed,e,n)}const z=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||y)+" 作为错误消息");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||C)+" 作为响应数据,读取 "+(s.messageField||y)+" 作为提示消息"),s.statusField&&e.push(" 当 "+s.statusField+" 为 "+(s.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),s.ignoreMessage&&e.push(" 并忽略以下消息:"+s.ignoreMessage);break}return e.join(`
2
- `)};function X(t,e,n){const s=t||{resolve:"json",messageField:y},r={ok:!1,code:e,message:n,data:null};switch(s.resolve){case"body":r.message=v(n)||n;break;case"json":const{code:a,message:i}=Y(n,s.statusField,s.messageField);r.code=a||e,r.message=v(n)||i;break}return r}function Y(t,e,n=y){if(!E(t))return{message:""};const s=R(t);return!s||!M(s)?{message:t}:{code:e?w(s,e):"",message:w(s,n)||t}}function w(t,e){const n=Array.isArray(e)?e:[e];for(const s of n)if(s in t)return _(t[s]);return""}function _(t){return t?typeof t=="string"?t:JSON.stringify(t):""}const ee=/<title>([^<]+)<\/title>/i,te=/<message>([^<]+)<\/message>/i;function v(t){const e=t.match(ee);if(e)return e[1];const n=t.match(te);return n?n[1]:""}function se(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=E(s)?R(s):s,a;const i=R(s);if(!i||!M(i))return a.ok=!1,a.code="ResponseFormatError",a.message="响应内容无法格式化为 Object",a;const o=r.statusField,c=r.statusOKValue||"",d=r.dataField||C,l=r.messageField||y,u=r.ignoreMessage||"";if(o&&!(o in i))return a.ok=!1,a.code="ResponseFieldMissing",a.message="响应内容找不到状态字段 "+o,a;const g=o?i[o]+"":"";return a.ok=o?g===c:!0,a.code=g||n,a.data=d===!0?i:d in i?i[d]:null,a.message=w(i,l),u&&a.message&&(Array.isArray(u)&&u.includes(a.message)||typeof u=="string"&&a.message===u)&&(a.message=""),a}function j(t){return t>=200&&t<400}async function A(t,e,n,s,r){const a=r||0,i=Math.max(0,Math.min(10,(s==null?void 0:s.maxRetry)??n.get("maxRetry")??0)),o=(s==null?void 0:s.retryResolve)??n.get("retryResolve"),c=n.get("logHandler")||T;c({type:"prepear",url:e,method:(s==null?void 0:s.method)||"GET",retry:a,maxRetry:i,message:a===0?"start":`retry ${a}/${i} 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,m=`[cost ${g}][${u}] ${u<0?l.body:""}`;c({type:"finished",url:e,method:l.method,retry:a,maxRetry:i,message:a===0?`finish ${m}`:`retry ${a}/${i} finish ${m}`,response:l,headers:l.headers,cost:g});const b=j(u);if(!i||o==="network"&&u>0||o==="status"&&b||Array.isArray(o)&&!o.includes(u)||typeof o=="function"&&o(l,a)!==!0||a>=i)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 A(t,e,n,s,a+1)}function ne(t,e,n,s){var i,o;if(t.status<0)return k({ok:!1,status:t.status,code:t.statusText,headers:{},message:"",data:null},`${t.method} ${e} ${t.statusText}`,t.method,e,n,s);j(t.status)||(i=n.get("errorHandler"))==null||i(t.status,t.method,e);const r={...Z(t.status,t.statusText,t.body,n.get("responseRule"),s==null?void 0:s.responseRule),status:t.status,headers:Object.fromEntries(Object.entries(t.headers||{}).map(([c,d])=>[c.toLowerCase(),d]))};(o=n.get("responseHandler"))==null||o({...r},t.method,e);const a=r.ok?r.message:`${t.method} ${e} [${r.code||t.statusText}] ${r.message||t.statusText}`;return k(r,a,t.method,e,n,s)}function k(t,e,n,s,r,a){const i=r.get("message"),o=i===!1||(a==null?void 0:a.message)===!1?!1:(a==null?void 0:a.message)||i;if(o!==!1){const c=typeof o=="function"?o(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 D{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)&&!p(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("/")?$(e):$(e,this.config.baseURL)}showMessage(e,n){this.config.messageHandler&&n&&this.config.messageHandler(e,n)}}class ae{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 re(t,e,n,s){if(e.ok&&!N(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 ie{constructor(e,n){f(this,"agent");f(this,"config");f(this,"cache");this.config=new D(n),this.agent=e,this.cache=new ae(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){return await this.agent(e,this.config,n)}async guard(e,n,s){return re(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),i=this.cache.get(a);if(i)return this.guard(e,await i,n||null);const o=this.exec(e,r);return this.cache.set(a,o),this.guard(e,await o,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)}}exports.NetRequestHandler=ie;exports.RequestGlobalConfig=D;exports.S=p;exports.Ut=J;exports.convertOptions=x;exports.getResponseRulesDescription=z;exports.handleResponse=ne;exports.ht=T;exports.retryRequest=A;exports.rt=Q;