@seayoo-web/request 1.4.1 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -139,9 +139,20 @@ setConfig({ timeout: 5000 })
139
139
 
140
140
  ### message
141
141
 
142
- 类型:false | ((result: IResponseResult, method: string, url: string, defaultMessage: string) => string | false)
142
+ 类型:false | ((
143
+ result: IResponseResult,
144
+ method: string,
145
+ url: string,
146
+ defaultMessage: string
147
+ ) => string | false | Error | {message: string})
143
148
 
144
- 说明:默认情况下,工具函数会输出 message 消息用于提示,当不需要提示时可以设置为 false;如果需要自定义提示内容,可以传递一个函数,并返回 false 或 字符串;
149
+ 说明:默认情况下,工具函数会输出 message 消息用于提示,当不需要提示时可以设置为 false
150
+
151
+ 如果需要自定义提示内容,可以传递一个函数,并返回 false 或 字符串;
152
+ 如果需要指定提示的类型,可以选择返回:
153
+
154
+ - Error 对象,则消息格式会被强制以 error 方式提示
155
+ - { message: string } ,则消息格式会被强制以 success 方式提示
145
156
 
146
157
  ### responseRule
147
158
 
@@ -4,7 +4,7 @@ export declare class RequestGlobalConfig {
4
4
  private config;
5
5
  constructor(config?: IRequestGlobalConfig);
6
6
  set(config: Partial<IRequestGlobalConfig>): void;
7
- get<T extends keyof IRequestGlobalConfig>(key: T): SomeRequired<IRequestGlobalConfig, "credentials" | "timeout" | "maxRetry" | "retryResolve" | "retryInterval" | "responseRule" | "baseURL" | "cacheTTL">[T];
7
+ get<T extends keyof IRequestGlobalConfig>(key: T): SomeRequired<IRequestGlobalConfig, "timeout" | "credentials" | "baseURL" | "maxRetry" | "cacheTTL" | "responseRule" | "retryInterval" | "retryResolve">[T];
8
8
  /** 基于 baseURL 返回完整的 url 地址, 如果 url 地址以 / 开头则表示忽略 baseURL 的值 */
9
9
  getFullUrl(url: string): string;
10
10
  /** 提示消息 */
@@ -21,7 +21,7 @@ export declare class NetRequestHandler {
21
21
  /**
22
22
  * 读取默认的请求配置
23
23
  */
24
- getConfig<T extends keyof IRequestGlobalConfig>(key: T): import("@seayoo-web/utils").SomeRequired<IRequestGlobalConfig, "credentials" | "timeout" | "maxRetry" | "retryResolve" | "retryInterval" | "responseRule" | "baseURL" | "cacheTTL">[T];
24
+ getConfig<T extends keyof IRequestGlobalConfig>(key: T): import("@seayoo-web/utils").SomeRequired<IRequestGlobalConfig, "timeout" | "credentials" | "baseURL" | "maxRetry" | "cacheTTL" | "responseRule" | "retryInterval" | "retryResolve">[T];
25
25
  /**
26
26
  * 发送一个 HEAD 请求,并且不处理响应 body
27
27
  */
@@ -42,8 +42,18 @@ export interface IRetryRequestOptions {
42
42
  retryInterval?: number | "2EB" | ((retryIndex: number) => number);
43
43
  }
44
44
  export interface IOtherRequestOptions {
45
- /** 如果设置为 false 则关闭通用提示,设置函数可以自定义提示,函数返回 falsly 则不提示 */
46
- message?: false | ((result: IResponseResult, method: string, url: string, defaultMessage: string) => string | false);
45
+ /**
46
+ * 如果设置为 false 则关闭通用提示
47
+ *
48
+ * 设置函数可以自定义提示,函数返回 falsly 则不提示
49
+ *
50
+ * 如果返回 Error 则强制以 error 方式提示 Error.message
51
+ *
52
+ * 如果返回 { message } 则强制以 success 方式提示 message
53
+ */
54
+ message?: false | ((result: IResponseResult, method: string, url: string, defaultMessage: string) => string | false | Error | {
55
+ message: string;
56
+ });
47
57
  /** 自定义 ajax response 解析策略 */
48
58
  responseRule?: IResponseRule;
49
59
  }
package/dist/index.cjs CHANGED
@@ -1 +1,2 @@
1
- var e=require("@seayoo-web/utils");function t(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},t.apply(this,arguments)}function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var n=function(e,t,r){try{var n=Object.assign({method:"GET"},r),o="FormData"in globalThis&&n.body instanceof FormData,s=o?"POST":n.method;"GET"!==s&&"HEAD"!==s&&"DELETE"!==s||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(o?{}:{"Content-Type":"Blob"in globalThis&&n.body instanceof Blob?n.body.type||"application/octet-stream":"application/json;charset=utf-8"},n.headers),i=n.params||{},u={};Object.keys(i).forEach(function(e){var t;void 0!==i[e]&&(u[e]="string"==typeof(t=i[e])?t:Array.isArray(t)?t.join(","):t+"")});var l=t.getFullUrl(e),c=function(e){if(e)return"string"==typeof e||e instanceof URLSearchParams||e instanceof ArrayBuffer||"Blob"in globalThis&&e instanceof Blob||"FormData"in globalThis&&e instanceof FormData?e:JSON.stringify(e)}(n.body),d=n.timeout||t.get("timeout");return Promise.resolve(function(r){try{var n=function(n){var o;return r?n:Promise.resolve(null==(o=t.get("requestHandler"))?void 0:o(a,u,s,e))},o=t.get("requestTransformer"),i=function(){if(o)return Promise.resolve(o({headers:a,params:u,method:s,url:l,body:c})).then(function(e){return r=1,e})}();return Promise.resolve(i&&i.then?i.then(n):n(i))}catch(e){return Promise.reject(e)}}()).then(function(e){var r,o="string"==typeof e&&e?e:l;return null==(r=t.get("logHandler"))||r({type:"ready",url:o,method:s,headers:a,timeout:d,body:c}),{url:o,method:s,body:c,params:u,headers:a,timeout:d,abort:n.abort,credentials:n.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}},o=function(e,t,r){try{return Promise.resolve(n(e,t,r)).then(function(e){var t=new URL(e.url),r=e.params;function n(){o.signal.aborted||o.abort()}r instanceof Object&&Object.keys(r).forEach(function(e){return t.searchParams.set(e,r[e])});var o=new AbortController;e.abort&&e.abort.addEventListener("abort",n);var s=e.timeout>0?setTimeout(n,e.timeout):null,a=new Request(t,{method:e.method,headers:new Headers(e.headers),body:e.body,credentials:e.credentials,signal:o.signal,redirect:"follow"});return Promise.resolve(fetch(a).then(function(r){try{var n=function(e){return{url:u,method:i,status:a,statusText:s,headers:o,body:e}},o=Object.fromEntries(r.headers.entries()),s=r.statusText,a=r.status,i=e.method,u=t.toString();return Promise.resolve("HEAD"===e.method?n(""):Promise.resolve(r.text()).then(n))}catch(e){return Promise.reject(e)}}).catch(function(r){return{url:t.toString(),method:e.method,status:-1,statusText:"NetworkError",body:String(r)}}).finally(function(){null!==s&&clearTimeout(s),e.abort&&e.abort.removeEventListener("abort",n)}))})}catch(e){return Promise.reject(e)}},s="data",a="message";function i(e,t){for(var n,o=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return r(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(e,t):void 0}}(e))){n&&(e=n);var o=0;return function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(Array.isArray(t)?t:[t]);!(n=o()).done;){var s=n.value;if(s in e)return(a=e[s])?"string"==typeof a?a:JSON.stringify(a):""}var a;return""}var u=/<title>([^<]+)<\/title>/i,l=/<message>([^<]+)<\/message>/i;function c(e){var t=e.match(u);if(t)return t[1];var r=e.match(l);return r?r[1]:""}function d(e){return e>=200&&e<400}var h=function t(r,n,o,s,a){try{var i,u,l,c=a||0,h=Math.max(0,Math.min(10,null!=(i=null!=(u=null==s?void 0:s.maxRetry)?u:o.get("maxRetry"))?i:0)),f=null!=(l=null==s?void 0:s.retryResolve)?l:o.get("retryResolve"),m=o.get("logHandler")||e.noop;m({type:"prepear",url:n,method:(null==s?void 0:s.method)||"GET",retry:c,maxRetry:h,message:0===c?"start":"retry "+c+"/"+h+" start",headers:null==s?void 0:s.headers,options:s});var g=Date.now();return Promise.resolve(r(n,o,s)).then(function(a){var i,u,l=a.status,v=Date.now()-g,p="[cost "+v+"]["+l+"] "+(l<0?a.body:"");m({type:"finished",url:n,method:a.method,retry:c,maxRetry:h,message:0===c?"finish "+p:"retry "+c+"/"+h+" finish "+p,response:a,headers:a.headers,cost:v});var y=d(l);if(!h||"network"===f&&l>0||"status"===f&&y||Array.isArray(f)&&!f.includes(l)||"function"==typeof f&&!0!==f(a,c)||c>=h)return a;var b=null!=(i=null!=(u=null==s?void 0:s.retryInterval)?u:o.get("retryInterval"))?i:1e3;return Promise.resolve(e.sleep(Math.max(100,"2EB"===b?1e3*Math.pow(2,c):"function"==typeof b?b(c+1)||0:b))).then(function(){return Promise.resolve(t(r,n,o,s,c+1))})})}catch(e){return Promise.reject(e)}};function f(r,n,o,u){var l,h;if(r.status<0)return m({ok:!1,status:r.status,code:r.statusText,headers:{},message:"",data:null},r.method+" "+n+" "+r.statusText,r.method,n,o,u);d(r.status)||null==(h=o.get("errorHandler"))||h(r.status,r.method,n);var f,g,v,p,y,b=t({},(f=r.status,g=r.statusText,v=r.body,p=o.get("responseRule"),y=(null==u?void 0:u.responseRule)||p,d(f)?function(t,r,n,o){var u=t||{resolve:"body"},l={ok:!0,code:n,message:"",data:null};if(202===r||204===r||!o)return l;if("body"===u.resolve)return l.data=e.isJsonLike(o)?e.parseJSON(o):o,l;var c=e.parseJSON(o);if(!c||!e.isStringRecord(c))return l.ok=!1,l.code="ResponseFormatError",l.message="响应内容无法格式化为 Object",l;var d=u.statusField,h=u.statusOKValue||"",f=u.dataField||s,m=u.messageField||a,g=u.ignoreMessage||"";if(d&&!(d in c))return l.ok=!1,l.code="ResponseFieldMissing",l.message="响应内容找不到状态字段 "+d,l;var v=d?c[d]+"":"";return l.ok=!d||v===h,l.code=v||n,l.data=!0===f?c:f in c?c[f]:null,l.message=i(c,m),g&&l.message&&(Array.isArray(g)&&g.includes(l.message)||"string"==typeof g&&l.message===g)&&(l.message=""),l}(y.ok||p.ok,f,g,v):function(t,r,n){var o=t||{resolve:"json",messageField:a},s={ok:!1,code:r,message:n,data:null};switch(o.resolve){case"body":s.message=c(n)||n;break;case"json":var u=function(t,r,n){if(void 0===n&&(n=a),!e.isJsonLike(t))return{message:""};var o=e.parseJSON(t);return o&&e.isStringRecord(o)?{code:r?i(o,r):"",message:i(o,n)||t}:{message:t}}(n,o.statusField,o.messageField),l=u.message;s.code=u.code||r,s.message=c(n)||l}return s}(y.failed||p.failed,g,v)),{status:r.status,headers:Object.fromEntries(Object.entries(r.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return null==(l=o.get("responseHandler"))||l(t({},b),r.method,n),m(b,b.ok?b.message:r.method+" "+n+" ["+(b.code||r.statusText)+"] "+(b.message||r.statusText),r.method,n,o,u)}function m(e,t,r,n,o,s){var a=o.get("message"),i=!1!==a&&!1!==(null==s?void 0:s.message)&&((null==s?void 0:s.message)||a);return!1!==i&&o.showMessage(!e.ok,"function"==typeof i?i(e,r,n,t):t),e}var g=/*#__PURE__*/function(){function t(e){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)}var r=t.prototype;return r.set=function(t){if(t.baseURL&&!/^\/.+/.test(t.baseURL)&&!e.isFullURL(t.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,t)},r.get=function(e){return this.config[e]},r.getFullUrl=function(t){return t.startsWith("/")?e.getFullURL(t):e.getFullURL(t,this.config.baseURL)},r.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},t}(),v=function(r,o,s){try{return Promise.resolve(n(r,o,s)).then(function(r){var n=t({},r,{onUploadProgress:null==s?void 0:s.onUploadProgress}),o=n.method,a=n.onUploadProgress||e.noop,i=e.addParamsToString(n.url,n.params);return Promise.resolve(new Promise(function(e){var t=1,r=null,s=!1,u=function(){s||(c.abort(),s=!0)};function l(){null!==r&&clearTimeout(r),n.abort&&n.abort.removeEventListener("abort",u)}var c=new XMLHttpRequest;c.open(o,i,!0),c.upload.addEventListener("progress",function(e){t=e.total,a({total:e.total,loaded:e.loaded})}),c.addEventListener("load",function(){l(),a({loaded:t,total:t}),e({url:i,method:o,status:c.status,statusText:c.statusText,headers:p(c),body:"HEAD"===o?"":c.responseText})}),c.addEventListener("error",function(){l(),e({url:i,method:o,status:-1,statusText:"Failed",body:""})}),c.addEventListener("abort",function(){l(),e({url:i,method:o,status:-1,statusText:"Aborted",body:""})}),Object.entries(n.headers).forEach(function(e){c.setRequestHeader(e[0],e[1])}),"include"===n.credentials&&(c.withCredentials=!0),c.send(n.body||void 0),n.abort&&n.abort.addEventListener("abort",u),n.timeout>0&&(r=setTimeout(u,n.timeout))}))})}catch(e){return Promise.reject(e)}};function p(e){var t={};if(!e)return t;var r=e.getAllResponseHeaders();return r&&"null"!==r&&r.replace(/\r/g,"").split("\n").forEach(function(e){var r=e.trim();if(r){var n=r.split(":"),o=n[0].trim();o&&(t[o]=(n[1]||"").trim())}}),t}var y=function(e,t,r){try{return Promise.resolve(h(o,e,t,r)).then(function(n){return f(n,e,t,r)})}catch(e){return Promise.reject(e)}},b=function(e,t,r){try{return Promise.resolve(h(v,e,t,r)).then(function(n){return f(n,e,t,r)})}catch(e){return Promise.reject(e)}},P=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),j=/*#__PURE__*/function(){function t(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new g(t),this.agent=e,this.cache=new P(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)}var r=t.prototype;return r.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},r.guard=function(t,r,n){try{return Promise.resolve(function(t,r,n,o){if(r.ok&&!e.isEmpty(r.data)&&o){var s=e.getTypeGuard(o,"响应数据未能正确识别");return s.guard(r.data)||(console.error("ResponseCheckFaild",t,r.data),n.showMessage(!0,t+" "+s.message),r.data=null),r}return r}(t,r,this.config,n))}catch(e){return Promise.reject(e)}},r.setConfig=function(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))},r.getConfig=function(e){return this.config.get(e)},r.head=function(e,t){try{var r=this,n=Object.assign({},t||null);n.method="HEAD";var o=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return o.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},r.get=function(e,t,r){try{var n,o=function(r){if(n)return r;var o=s.exec(e,a);s.cache.set(i,o);var u=s.guard;return Promise.resolve(o).then(function(r){return u.call(s,e,r,t||null)})},s=this,a=Object.assign({},r||null);a.method="GET";var i=s.cache.getKey(e,a.params),u=s.cache.get(i),l=function(){if(u){var r=s.guard;return Promise.resolve(u).then(function(o){var a=r.call(s,e,o,t||null);return n=1,a})}}();return Promise.resolve(l&&l.then?l.then(o):o(l))}catch(e){return Promise.reject(e)}},r.post=function(e,t,r,n){try{var o=this,s=Object.assign({},n||null);s.method="POST",s.body=t;var a=o.guard;return Promise.resolve(o.exec(e,s)).then(function(t){return a.call(o,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.del=function(e,t,r){try{var n=this,o=Object.assign({},r||null);o.method="DELETE";var s=n.guard;return Promise.resolve(n.exec(e,o)).then(function(r){return s.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},r.put=function(e,t,r,n){try{var o=this,s=Object.assign({},n||null);s.method="PUT",s.body=t;var a=o.guard;return Promise.resolve(o.exec(e,s)).then(function(t){return a.call(o,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.patch=function(e,t,r,n){try{var o=this,s=Object.assign({},n||null);s.method="PATCH",s.body=t;var a=o.guard;return Promise.resolve(o.exec(e,s)).then(function(t){return a.call(o,e,t,r||null)})}catch(e){return Promise.reject(e)}},t}();function w(e){if("window"in globalThis)return"fetch"in window?new j(y,e):new j(b,e);throw new Error("Default Module Only Support In Browser")}var T=w(),x=T.setConfig,E=T.head,O=T.get,R=T.post,L=T.del,k=T.put,S=T.patch;exports.NetRequest=w,exports.del=L,exports.get=O,exports.getResponseRulesDescription=function(e){var t=[],r=e.failed||{resolve:"json"};switch(t.push("- 当http状态码 <200 或者 >=400 时"),r.resolve){case"body":t.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":t.push(" 将响应解析为json,并读取 "+(r.messageField||a)+" 作为错误消息")}var n=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":t.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(n.dataField||s)+" 作为响应数据,读取 "+(n.messageField||a)+" 作为提示消息"),n.statusField&&t.push(" 当 "+n.statusField+" 为 "+(n.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&t.push(" 并忽略以下消息:"+n.ignoreMessage)}return t.join("\n")},exports.head=E,exports.jsonp=function(t,r,n){void 0===n&&(n={});try{var o=window;"callback"in n||(n.callback="jsonxData"+Math.random().toString(16).slice(2));var s=n.callback+"";if(!t)return Promise.resolve(null);var a=e.addParamsToString(t,n,!0);return Promise.resolve(new Promise(function(n){o[s]=function(e){if(s in window&&delete o[s],r(e))return e;console.warn("response type check faild",t,e),n(null)},e.loadJS(a).catch(function(){n(null),delete o[s]})}))}catch(e){return Promise.reject(e)}},exports.jsonx=function(t,r,n){void 0===n&&(n={});try{var o=window;return"var"in n||(n.var="jsonxData"+Math.random().toString(16).slice(2)),Promise.resolve(t?e.loadJS(e.addParamsToString(t,n,!0)).then(function(){var e=o[n.var+""];return r(e)?e:(console.warn("response type check faild",t,e),null)}).catch(function(){return null}):null)}catch(e){return Promise.reject(e)}},exports.patch=S,exports.post=R,exports.put=k,exports.setGlobalConfig=x,exports.upload=function(e,r,n){try{return Promise.resolve(function(e,r,n,o){try{var s=new FormData,a=null==n?void 0:n.body,i=t({},r);for(var u in a instanceof Object&&Object.entries(a).forEach(function(e){var t=e[0],r=e[1];r instanceof Blob?i[t]=r:Array.isArray(r)?r.forEach(function(e,r){s.append(t+"["+r+"]",String(e))}):s.append(t,String(r))}),i)s.append(u,i[u]);var l=new g(o);return Promise.resolve(v(e,l,t({},n,{method:"POST",body:s}))).then(function(t){return f(t,e,l,n)})}catch(e){return Promise.reject(e)}}(e,r,n,{baseURL:T.getConfig("baseURL"),logHandler:T.getConfig("logHandler"),errorHandler:T.getConfig("errorHandler"),requestHandler:T.getConfig("requestHandler"),messageHandler:T.getConfig("messageHandler"),responseHandler:T.getConfig("responseHandler")}))}catch(e){return Promise.reject(e)}};
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;
package/dist/index.d.ts CHANGED
@@ -32,9 +32,9 @@ export declare const get: {
32
32
  * 发送一个 POST 请求,可选 typeGuard 用于检查数据类型
33
33
  */
34
34
  export declare const post: {
35
- (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
36
- (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
37
- <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
35
+ (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
36
+ (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
37
+ <T>(url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
38
38
  };
39
39
  /**
40
40
  * 发送一个 DELETE 请求,可选 typeGuard 用于检查数据类型
@@ -48,15 +48,15 @@ export declare const del: {
48
48
  * 发送一个 PUT 请求,可选 typeGuard 用于检查数据类型
49
49
  */
50
50
  export declare const put: {
51
- (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
52
- (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
53
- <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
51
+ (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
52
+ (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
53
+ <T>(url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
54
54
  };
55
55
  /**
56
56
  * 发送一个 PATCH 请求,可选 typeGuard 用于检查数据类型
57
57
  */
58
58
  export declare const patch: {
59
- (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
60
- (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
61
- <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
59
+ (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
60
+ (url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
61
+ <T>(url: string, data: string | object | unknown[] | ArrayBuffer | Blob | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
62
62
  };
package/dist/index.js CHANGED
@@ -1 +1,171 @@
1
- import{isJsonLike as e,parseJSON as t,isStringRecord as r,noop as n,sleep as o,isFullURL as s,getFullURL as a,addParamsToString as i,isEmpty as u,getTypeGuard as l,loadJS as c}from"@seayoo-web/utils";function d(){return d=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},d.apply(this,arguments)}function h(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var f=function(e,t,r){try{var n=Object.assign({method:"GET"},r),o="FormData"in globalThis&&n.body instanceof FormData,s=o?"POST":n.method;"GET"!==s&&"HEAD"!==s&&"DELETE"!==s||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(o?{}:{"Content-Type":"Blob"in globalThis&&n.body instanceof Blob?n.body.type||"application/octet-stream":"application/json;charset=utf-8"},n.headers),i=n.params||{},u={};Object.keys(i).forEach(function(e){var t;void 0!==i[e]&&(u[e]="string"==typeof(t=i[e])?t:Array.isArray(t)?t.join(","):t+"")});var l=t.getFullUrl(e),c=function(e){if(e)return"string"==typeof e||e instanceof URLSearchParams||e instanceof ArrayBuffer||"Blob"in globalThis&&e instanceof Blob||"FormData"in globalThis&&e instanceof FormData?e:JSON.stringify(e)}(n.body),d=n.timeout||t.get("timeout");return Promise.resolve(function(r){try{var n=function(n){var o;return r?n:Promise.resolve(null==(o=t.get("requestHandler"))?void 0:o(a,u,s,e))},o=t.get("requestTransformer"),i=function(){if(o)return Promise.resolve(o({headers:a,params:u,method:s,url:l,body:c})).then(function(e){return r=1,e})}();return Promise.resolve(i&&i.then?i.then(n):n(i))}catch(e){return Promise.reject(e)}}()).then(function(e){var r,o="string"==typeof e&&e?e:l;return null==(r=t.get("logHandler"))||r({type:"ready",url:o,method:s,headers:a,timeout:d,body:c}),{url:o,method:s,body:c,params:u,headers:a,timeout:d,abort:n.abort,credentials:n.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}},m=function(e,t,r){try{return Promise.resolve(f(e,t,r)).then(function(e){var t=new URL(e.url),r=e.params;function n(){o.signal.aborted||o.abort()}r instanceof Object&&Object.keys(r).forEach(function(e){return t.searchParams.set(e,r[e])});var o=new AbortController;e.abort&&e.abort.addEventListener("abort",n);var s=e.timeout>0?setTimeout(n,e.timeout):null,a=new Request(t,{method:e.method,headers:new Headers(e.headers),body:e.body,credentials:e.credentials,signal:o.signal,redirect:"follow"});return Promise.resolve(fetch(a).then(function(r){try{var n=function(e){return{url:u,method:i,status:a,statusText:s,headers:o,body:e}},o=Object.fromEntries(r.headers.entries()),s=r.statusText,a=r.status,i=e.method,u=t.toString();return Promise.resolve("HEAD"===e.method?n(""):Promise.resolve(r.text()).then(n))}catch(e){return Promise.reject(e)}}).catch(function(r){return{url:t.toString(),method:e.method,status:-1,statusText:"NetworkError",body:String(r)}}).finally(function(){null!==s&&clearTimeout(s),e.abort&&e.abort.removeEventListener("abort",n)}))})}catch(e){return Promise.reject(e)}},g="data",v="message",y=function(e){var t=[],r=e.failed||{resolve:"json"};switch(t.push("- 当http状态码 <200 或者 >=400 时"),r.resolve){case"body":t.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":t.push(" 将响应解析为json,并读取 "+(r.messageField||v)+" 作为错误消息")}var n=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":t.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(n.dataField||g)+" 作为响应数据,读取 "+(n.messageField||v)+" 作为提示消息"),n.statusField&&t.push(" 当 "+n.statusField+" 为 "+(n.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&t.push(" 并忽略以下消息:"+n.ignoreMessage)}return t.join("\n")};function b(e,t){for(var r,n=function(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return h(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?h(e,t):void 0}}(e))){r&&(e=r);var n=0;return function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}(Array.isArray(t)?t:[t]);!(r=n()).done;){var o=r.value;if(o in e)return(s=e[o])?"string"==typeof s?s:JSON.stringify(s):""}var s;return""}var p=/<title>([^<]+)<\/title>/i,P=/<message>([^<]+)<\/message>/i;function j(e){var t=e.match(p);if(t)return t[1];var r=e.match(P);return r?r[1]:""}function w(e){return e>=200&&e<400}var T=function e(t,r,s,a,i){try{var u,l,c,d=i||0,h=Math.max(0,Math.min(10,null!=(u=null!=(l=null==a?void 0:a.maxRetry)?l:s.get("maxRetry"))?u:0)),f=null!=(c=null==a?void 0:a.retryResolve)?c:s.get("retryResolve"),m=s.get("logHandler")||n;m({type:"prepear",url:r,method:(null==a?void 0:a.method)||"GET",retry:d,maxRetry:h,message:0===d?"start":"retry "+d+"/"+h+" start",headers:null==a?void 0:a.headers,options:a});var g=Date.now();return Promise.resolve(t(r,s,a)).then(function(n){var i,u,l=n.status,c=Date.now()-g,v="[cost "+c+"]["+l+"] "+(l<0?n.body:"");m({type:"finished",url:r,method:n.method,retry:d,maxRetry:h,message:0===d?"finish "+v:"retry "+d+"/"+h+" finish "+v,response:n,headers:n.headers,cost:c});var y=w(l);if(!h||"network"===f&&l>0||"status"===f&&y||Array.isArray(f)&&!f.includes(l)||"function"==typeof f&&!0!==f(n,d)||d>=h)return n;var b=null!=(i=null!=(u=null==a?void 0:a.retryInterval)?u:s.get("retryInterval"))?i:1e3;return Promise.resolve(o(Math.max(100,"2EB"===b?1e3*Math.pow(2,d):"function"==typeof b?b(d+1)||0:b))).then(function(){return Promise.resolve(e(t,r,s,a,d+1))})})}catch(e){return Promise.reject(e)}};function E(n,o,s,a){var i,u;if(n.status<0)return x({ok:!1,status:n.status,code:n.statusText,headers:{},message:"",data:null},n.method+" "+o+" "+n.statusText,n.method,o,s,a);w(n.status)||null==(u=s.get("errorHandler"))||u(n.status,n.method,o);var l,c,h,f,m,y=d({},(l=n.status,c=n.statusText,h=n.body,f=s.get("responseRule"),m=(null==a?void 0:a.responseRule)||f,w(l)?function(n,o,s,a){var i=n||{resolve:"body"},u={ok:!0,code:s,message:"",data:null};if(202===o||204===o||!a)return u;if("body"===i.resolve)return u.data=e(a)?t(a):a,u;var l=t(a);if(!l||!r(l))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var c=i.statusField,d=i.statusOKValue||"",h=i.dataField||g,f=i.messageField||v,m=i.ignoreMessage||"";if(c&&!(c in l))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+c,u;var y=c?l[c]+"":"";return u.ok=!c||y===d,u.code=y||s,u.data=!0===h?l:h in l?l[h]:null,u.message=b(l,f),m&&u.message&&(Array.isArray(m)&&m.includes(u.message)||"string"==typeof m&&u.message===m)&&(u.message=""),u}(m.ok||f.ok,l,c,h):function(n,o,s){var a=n||{resolve:"json",messageField:v},i={ok:!1,code:o,message:s,data:null};switch(a.resolve){case"body":i.message=j(s)||s;break;case"json":var u=function(n,o,s){if(void 0===s&&(s=v),!e(n))return{message:""};var a=t(n);return a&&r(a)?{code:o?b(a,o):"",message:b(a,s)||n}:{message:n}}(s,a.statusField,a.messageField),l=u.message;i.code=u.code||o,i.message=j(s)||l}return i}(m.failed||f.failed,c,h)),{status:n.status,headers:Object.fromEntries(Object.entries(n.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return null==(i=s.get("responseHandler"))||i(d({},y),n.method,o),x(y,y.ok?y.message:n.method+" "+o+" ["+(y.code||n.statusText)+"] "+(y.message||n.statusText),n.method,o,s,a)}function x(e,t,r,n,o,s){var a=o.get("message"),i=!1!==a&&!1!==(null==s?void 0:s.message)&&((null==s?void 0:s.message)||a);return!1!==i&&o.showMessage(!e.ok,"function"==typeof i?i(e,r,n,t):t),e}var O=/*#__PURE__*/function(){function e(e){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)}var t=e.prototype;return t.set=function(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!s(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)},t.get=function(e){return this.config[e]},t.getFullUrl=function(e){return e.startsWith("/")?a(e):a(e,this.config.baseURL)},t.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},e}(),R=function(e,t,r){try{return Promise.resolve(f(e,t,r)).then(function(e){var t=d({},e,{onUploadProgress:null==r?void 0:r.onUploadProgress}),o=t.method,s=t.onUploadProgress||n,a=i(t.url,t.params);return Promise.resolve(new Promise(function(e){var r=1,n=null,i=!1,u=function(){i||(c.abort(),i=!0)};function l(){null!==n&&clearTimeout(n),t.abort&&t.abort.removeEventListener("abort",u)}var c=new XMLHttpRequest;c.open(o,a,!0),c.upload.addEventListener("progress",function(e){r=e.total,s({total:e.total,loaded:e.loaded})}),c.addEventListener("load",function(){l(),s({loaded:r,total:r}),e({url:a,method:o,status:c.status,statusText:c.statusText,headers:k(c),body:"HEAD"===o?"":c.responseText})}),c.addEventListener("error",function(){l(),e({url:a,method:o,status:-1,statusText:"Failed",body:""})}),c.addEventListener("abort",function(){l(),e({url:a,method:o,status:-1,statusText:"Aborted",body:""})}),Object.entries(t.headers).forEach(function(e){c.setRequestHeader(e[0],e[1])}),"include"===t.credentials&&(c.withCredentials=!0),c.send(t.body||void 0),t.abort&&t.abort.addEventListener("abort",u),t.timeout>0&&(n=setTimeout(u,t.timeout))}))})}catch(e){return Promise.reject(e)}};function k(e){var t={};if(!e)return t;var r=e.getAllResponseHeaders();return r&&"null"!==r&&r.replace(/\r/g,"").split("\n").forEach(function(e){var r=e.trim();if(r){var n=r.split(":"),o=n[0].trim();o&&(t[o]=(n[1]||"").trim())}}),t}var L=function(e,t,r){try{return Promise.resolve(T(m,e,t,r)).then(function(n){return E(n,e,t,r)})}catch(e){return Promise.reject(e)}},H=function(e,t,r){try{return Promise.resolve(T(R,e,t,r)).then(function(n){return E(n,e,t,r)})}catch(e){return Promise.reject(e)}},A=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),F=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new O(t),this.agent=e,this.cache=new A(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)}var t=e.prototype;return t.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},t.guard=function(e,t,r){try{return Promise.resolve(function(e,t,r,n){if(t.ok&&!u(t.data)&&n){var o=l(n,"响应数据未能正确识别");return o.guard(t.data)||(console.error("ResponseCheckFaild",e,t.data),r.showMessage(!0,e+" "+o.message),t.data=null),t}return t}(e,t,this.config,r))}catch(e){return Promise.reject(e)}},t.setConfig=function(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))},t.getConfig=function(e){return this.config.get(e)},t.head=function(e,t){try{var r=this,n=Object.assign({},t||null);n.method="HEAD";var o=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return o.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},t.get=function(e,t,r){try{var n,o=function(r){if(n)return r;var o=s.exec(e,a);s.cache.set(i,o);var u=s.guard;return Promise.resolve(o).then(function(r){return u.call(s,e,r,t||null)})},s=this,a=Object.assign({},r||null);a.method="GET";var i=s.cache.getKey(e,a.params),u=s.cache.get(i),l=function(){if(u){var r=s.guard;return Promise.resolve(u).then(function(o){var a=r.call(s,e,o,t||null);return n=1,a})}}();return Promise.resolve(l&&l.then?l.then(o):o(l))}catch(e){return Promise.reject(e)}},t.post=function(e,t,r,n){try{var o=this,s=Object.assign({},n||null);s.method="POST",s.body=t;var a=o.guard;return Promise.resolve(o.exec(e,s)).then(function(t){return a.call(o,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.del=function(e,t,r){try{var n=this,o=Object.assign({},r||null);o.method="DELETE";var s=n.guard;return Promise.resolve(n.exec(e,o)).then(function(r){return s.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},t.put=function(e,t,r,n){try{var o=this,s=Object.assign({},n||null);s.method="PUT",s.body=t;var a=o.guard;return Promise.resolve(o.exec(e,s)).then(function(t){return a.call(o,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r,n){try{var o=this,s=Object.assign({},n||null);s.method="PATCH",s.body=t;var a=o.guard;return Promise.resolve(o.exec(e,s)).then(function(t){return a.call(o,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}(),C=function(e,t,r){void 0===r&&(r={});try{var n=window;return"var"in r||(r.var="jsonxData"+Math.random().toString(16).slice(2)),Promise.resolve(e?c(i(e,r,!0)).then(function(){var o=n[r.var+""];return t(o)?o:(console.warn("response type check faild",e,o),null)}).catch(function(){return null}):null)}catch(e){return Promise.reject(e)}},S=function(e,t,r){void 0===r&&(r={});try{var n=window;"callback"in r||(r.callback="jsonxData"+Math.random().toString(16).slice(2));var o=r.callback+"";if(!e)return Promise.resolve(null);var s=i(e,r,!0);return Promise.resolve(new Promise(function(r){n[o]=function(s){if(o in window&&delete n[o],t(s))return s;console.warn("response type check faild",e,s),r(null)},c(s).catch(function(){r(null),delete n[o]})}))}catch(e){return Promise.reject(e)}},D=function(e,t,r){try{return Promise.resolve(function(e,t,r,n){try{var o=new FormData,s=null==r?void 0:r.body,a=d({},t);for(var i in s instanceof Object&&Object.entries(s).forEach(function(e){var t=e[0],r=e[1];r instanceof Blob?a[t]=r:Array.isArray(r)?r.forEach(function(e,r){o.append(t+"["+r+"]",String(e))}):o.append(t,String(r))}),a)o.append(i,a[i]);var u=new O(n);return Promise.resolve(R(e,u,d({},r,{method:"POST",body:o}))).then(function(t){return E(t,e,u,r)})}catch(e){return Promise.reject(e)}}(e,t,r,{baseURL:U.getConfig("baseURL"),logHandler:U.getConfig("logHandler"),errorHandler:U.getConfig("errorHandler"),requestHandler:U.getConfig("requestHandler"),messageHandler:U.getConfig("messageHandler"),responseHandler:U.getConfig("responseHandler")}))}catch(e){return Promise.reject(e)}};function M(e){if("window"in globalThis)return"fetch"in window?new F(L,e):new F(H,e);throw new Error("Default Module Only Support In Browser")}var U=M(),B=U.setConfig,q=U.head,I=U.get,G=U.post,K=U.del,N=U.put,J=U.patch;export{M as NetRequest,K as del,I as get,y as getResponseRulesDescription,q as head,S as jsonp,C as jsonx,J as patch,G as post,N as put,B as setGlobalConfig,D as upload};
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) {
4
+ const t = await R(n, o, e), r = new URL(t.url), c = t.params;
5
+ c instanceof Object && Object.keys(c).forEach((a) => r.searchParams.set(a, c[a]));
6
+ const s = new AbortController();
7
+ function i() {
8
+ s.signal.aborted || s.abort();
9
+ }
10
+ t.abort && t.abort.addEventListener("abort", i);
11
+ const f = t.timeout > 0 ? setTimeout(i, t.timeout) : null, u = new Request(r, {
12
+ method: t.method,
13
+ headers: new Headers(t.headers),
14
+ body: t.body,
15
+ credentials: t.credentials,
16
+ signal: s.signal,
17
+ redirect: "follow"
18
+ });
19
+ return await fetch(u).then(async (a) => ({
20
+ url: r.toString(),
21
+ method: t.method,
22
+ status: a.status,
23
+ statusText: a.statusText,
24
+ headers: Object.fromEntries(a.headers.entries()),
25
+ body: t.method === "HEAD" ? "" : await a.text()
26
+ })).catch((a) => ({
27
+ url: r.toString(),
28
+ method: t.method,
29
+ status: -1,
30
+ statusText: "NetworkError",
31
+ body: String(a)
32
+ })).finally(() => {
33
+ f !== null && clearTimeout(f), t.abort && t.abort.removeEventListener("abort", i);
34
+ });
35
+ }, x = async function(n, o, e) {
36
+ const t = {
37
+ ...await R(n, o, e),
38
+ onUploadProgress: e == null ? void 0 : e.onUploadProgress
39
+ }, r = t.method, c = t.onUploadProgress || q, s = m(t.url, t.params);
40
+ return await new Promise((i) => {
41
+ let f = 1;
42
+ function u(h) {
43
+ f = h.total, c({ total: h.total, loaded: h.loaded });
44
+ }
45
+ let a = null, g = !1;
46
+ const b = function() {
47
+ g || (l.abort(), g = !0);
48
+ };
49
+ function w() {
50
+ a !== null && clearTimeout(a), t.abort && t.abort.removeEventListener("abort", b);
51
+ }
52
+ const l = new XMLHttpRequest();
53
+ l.open(r, s, !0), l.upload.addEventListener("progress", u), l.addEventListener("load", () => {
54
+ w(), c({ loaded: f, total: f }), i({
55
+ url: s,
56
+ method: r,
57
+ status: l.status,
58
+ statusText: l.statusText,
59
+ headers: C(l),
60
+ body: r === "HEAD" ? "" : l.responseText
61
+ });
62
+ }), l.addEventListener("error", () => {
63
+ w(), i({
64
+ url: s,
65
+ method: r,
66
+ status: -1,
67
+ statusText: "Failed",
68
+ body: ""
69
+ });
70
+ }), l.addEventListener("abort", () => {
71
+ w(), i({
72
+ url: s,
73
+ method: r,
74
+ status: -1,
75
+ statusText: "Aborted",
76
+ body: ""
77
+ });
78
+ }), Object.entries(t.headers).forEach(([h, T]) => {
79
+ l.setRequestHeader(h, T);
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
+ });
82
+ };
83
+ function C(n) {
84
+ const o = {};
85
+ if (!n)
86
+ return o;
87
+ const e = n.getAllResponseHeaders();
88
+ return e && e !== "null" && e.replace(/\r/g, "").split(`
89
+ `).forEach((t) => {
90
+ const r = t.trim();
91
+ if (!r)
92
+ return;
93
+ const c = r.split(":"), s = c[0].trim();
94
+ s && (o[s] = (c[1] || "").trim());
95
+ }), o;
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);
101
+ };
102
+ async function v(n, o, e, t) {
103
+ const r = new FormData(), c = e == null ? void 0 : e.body, s = { ...o };
104
+ c instanceof Object && Object.entries(c).forEach(([u, a]) => {
105
+ a instanceof Blob ? s[u] = a : Array.isArray(a) ? a.forEach((g, b) => {
106
+ r.append(`${u}[${b}]`, String(g));
107
+ }) : r.append(u, String(a));
108
+ });
109
+ for (const u in s)
110
+ r.append(u, s[u]);
111
+ const i = new L(t), f = await x(n, i, {
112
+ ...e,
113
+ method: "POST",
114
+ body: r
115
+ });
116
+ return p(f, n, i, e);
117
+ }
118
+ async function D(n, o, e = {}) {
119
+ const t = window;
120
+ "callback" in e || (e.callback = "jsonxData" + Math.random().toString(16).slice(2));
121
+ const r = e.callback + "";
122
+ if (!n)
123
+ return null;
124
+ const c = m(n, e, !0);
125
+ return new Promise((s) => {
126
+ t[r] = function(i) {
127
+ if (r in window && delete t[r], o(i))
128
+ return i;
129
+ console.warn("response type check faild", n, i), s(null);
130
+ }, E(c).catch(function() {
131
+ s(null), delete t[r];
132
+ });
133
+ });
134
+ }
135
+ async function A(n, o, e = {}) {
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(() => {
138
+ const r = t[e.var + ""];
139
+ return o(r) ? r : (console.warn("response type check faild", n, r), null);
140
+ }).catch(() => null) : null;
141
+ }
142
+ const P = async function(n, o, e) {
143
+ return await v(n, o, e, {
144
+ baseURL: d.getConfig("baseURL"),
145
+ logHandler: d.getConfig("logHandler"),
146
+ errorHandler: d.getConfig("errorHandler"),
147
+ requestHandler: d.getConfig("requestHandler"),
148
+ messageHandler: d.getConfig("messageHandler"),
149
+ responseHandler: d.getConfig("responseHandler")
150
+ });
151
+ };
152
+ function O(n) {
153
+ if ("window" in globalThis)
154
+ return "fetch" in window ? new y(S, n) : new y(j, n);
155
+ throw new Error("Default Module Only Support In Browser");
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;
158
+ export {
159
+ O as NetRequest,
160
+ B as del,
161
+ F as get,
162
+ J as getResponseRulesDescription,
163
+ N as head,
164
+ D as jsonp,
165
+ A as jsonx,
166
+ I as patch,
167
+ X as post,
168
+ G as put,
169
+ M as setGlobalConfig,
170
+ P as upload
171
+ };
@@ -0,0 +1,2 @@
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;