@seayoo-web/request 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/dist/inc/type.d.ts +12 -2
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/node.cjs +1 -1
- package/dist/node.js +1 -1
- package/dist/wx.cjs +1 -1
- package/dist/wx.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -295,6 +295,14 @@ status 表示网络错误或者http 状态码错误时重试;
|
|
|
295
295
|
|
|
296
296
|
同全局配置,仅本次请求有效,默认 5000
|
|
297
297
|
|
|
298
|
+
### abort
|
|
299
|
+
|
|
300
|
+
类型:AbortSignal,用于主动中断请求;
|
|
301
|
+
|
|
302
|
+
- 当请求结束时无效;
|
|
303
|
+
- 仅浏览器环境有效,
|
|
304
|
+
- 不支持 AbortSignal 的浏览器可以引入 https://www.npmjs.com/package/abortcontroller-polyfill
|
|
305
|
+
|
|
298
306
|
### message
|
|
299
307
|
|
|
300
308
|
同全局配置,仅本次请求有效,可以设定 false 关闭消息提示,也可以传递函数自定义消息内容;
|
package/dist/inc/type.d.ts
CHANGED
|
@@ -42,8 +42,18 @@ export interface IRetryRequestOptions {
|
|
|
42
42
|
retryInterval?: number | "2EB" | ((retryIndex: number) => number);
|
|
43
43
|
}
|
|
44
44
|
export interface IOtherRequestOptions {
|
|
45
|
-
/**
|
|
46
|
-
|
|
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 @@
|
|
|
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.onabort=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)}))})}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=new XMLHttpRequest;s.open(o,i,!0),s.upload.addEventListener("progress",function(e){t=e.total,a({total:e.total,loaded:e.loaded})}),s.addEventListener("load",function(){null!==r&&clearTimeout(r),a({loaded:t,total:t}),e({url:i,method:o,status:s.status,statusText:s.statusText,headers:p(s),body:"HEAD"===o?"":s.responseText})}),s.addEventListener("error",function(){null!==r&&clearTimeout(r),e({url:i,method:o,status:-1,statusText:"Failed",body:""})}),s.addEventListener("abort",function(){null!==r&&clearTimeout(r),e({url:i,method:o,status:-1,statusText:"Aborted",body:""})}),Object.entries(n.headers).forEach(function(e){s.setRequestHeader(e[0],e[1])}),"include"===n.credentials&&(s.withCredentials=!0),s.send(n.body||void 0),function(){if(n.abort||!(n.timeout<=0)){var e=!1,t=function(){e||(s.abort(),e=!0)};n.abort&&(n.abort.onabort=t),n.timeout>0&&(r=setTimeout(t,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,O=T.head,R=T.get,E=T.post,k=T.del,L=T.put,S=T.patch;exports.NetRequest=w,exports.del=k,exports.get=R,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=O,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=E,exports.put=L,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
|
+
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);if(!1!==i){var u="function"==typeof i?i(e,r,n,t):t;u instanceof Error?o.showMessage(!0,u.message):u&&"object"==typeof u&&"message"in u?o.showMessage(!1,u.message):o.showMessage(!e.ok,u)}return 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)}};
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
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.onabort=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)}))})}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 x(n,o,s,a){var i,u;if(n.status<0)return O({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),O(y,y.ok?y.message:n.method+" "+o+" ["+(y.code||n.statusText)+"] "+(y.message||n.statusText),n.method,o,s,a)}function O(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 E=/*#__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=new XMLHttpRequest;i.open(o,a,!0),i.upload.addEventListener("progress",function(e){r=e.total,s({total:e.total,loaded:e.loaded})}),i.addEventListener("load",function(){null!==n&&clearTimeout(n),s({loaded:r,total:r}),e({url:a,method:o,status:i.status,statusText:i.statusText,headers:k(i),body:"HEAD"===o?"":i.responseText})}),i.addEventListener("error",function(){null!==n&&clearTimeout(n),e({url:a,method:o,status:-1,statusText:"Failed",body:""})}),i.addEventListener("abort",function(){null!==n&&clearTimeout(n),e({url:a,method:o,status:-1,statusText:"Aborted",body:""})}),Object.entries(t.headers).forEach(function(e){i.setRequestHeader(e[0],e[1])}),"include"===t.credentials&&(i.withCredentials=!0),i.send(t.body||void 0),function(){if(t.abort||!(t.timeout<=0)){var e=!1,r=function(){e||(i.abort(),e=!0)};t.abort&&(t.abort.onabort=r),t.timeout>0&&(n=setTimeout(r,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 H=function(e,t,r){try{return Promise.resolve(T(m,e,t,r)).then(function(n){return x(n,e,t,r)})}catch(e){return Promise.reject(e)}},A=function(e,t,r){try{return Promise.resolve(T(R,e,t,r)).then(function(n){return x(n,e,t,r)})}catch(e){return Promise.reject(e)}},L=/*#__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 E(t),this.agent=e,this.cache=new L(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 E(n);return Promise.resolve(R(e,u,d({},r,{method:"POST",body:o}))).then(function(t){return x(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(H,e):new F(A,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{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);if(!1!==i){var u="function"==typeof i?i(e,r,n,t):t;u instanceof Error?o.showMessage(!0,u.message):u&&"object"==typeof u&&"message"in u?o.showMessage(!1,u.message):o.showMessage(!e.ok,u)}return 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)}},M=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)}},S=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 D(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=D(),B=U.setConfig,q=U.head,I=U.get,G=U.post,K=U.del,N=U.put,J=U.patch;export{D as NetRequest,K as del,I as get,y as getResponseRulesDescription,q as head,M as jsonp,C as jsonx,J as patch,G as post,N as put,B as setGlobalConfig,S as upload};
|
package/dist/node.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=require("node:http"),t=require("node:https"),r=require("@seayoo-web/utils");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=/*#__PURE__*/n(e),o=/*#__PURE__*/n(t);function a(){return a=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},a.apply(this,arguments)}function i(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 u="message";function c(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 i(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)?i(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 s=r.value;if(s in e)return(o=e[s])?"string"==typeof o?o:JSON.stringify(o):""}var o;return""}var l=/<title>([^<]+)<\/title>/i,h=/<message>([^<]+)<\/message>/i;function d(e){var t=e.match(l);if(t)return t[1];var r=e.match(h);return r?r[1]:""}function f(e){return e>=200&&e<400}var m=function e(t,n,s,o,a){try{var i,u,c,l=a||0,h=Math.max(0,Math.min(10,null!=(i=null!=(u=null==o?void 0:o.maxRetry)?u:s.get("maxRetry"))?i:0)),d=null!=(c=null==o?void 0:o.retryResolve)?c:s.get("retryResolve"),m=s.get("logHandler")||r.noop;m({type:"prepear",url:n,method:(null==o?void 0:o.method)||"GET",retry:l,maxRetry:h,message:0===l?"start":"retry "+l+"/"+h+" start",headers:null==o?void 0:o.headers,options:o});var g=Date.now();return Promise.resolve(t(n,s,o)).then(function(a){var i,u,c=a.status,v=Date.now()-g,y="[cost "+v+"]["+c+"] "+(c<0?a.body:"");m({type:"finished",url:n,method:a.method,retry:l,maxRetry:h,message:0===l?"finish "+y:"retry "+l+"/"+h+" finish "+y,response:a,headers:a.headers,cost:v});var p=f(c);if(!h||"network"===d&&c>0||"status"===d&&p||Array.isArray(d)&&!d.includes(c)||"function"==typeof d&&!0!==d(a,l)||l>=h)return a;var b=null!=(i=null!=(u=null==o?void 0:o.retryInterval)?u:s.get("retryInterval"))?i:1e3;return Promise.resolve(r.sleep(Math.max(100,"2EB"===b?1e3*Math.pow(2,l):"function"==typeof b?b(l+1)||0:b))).then(function(){return Promise.resolve(e(t,n,s,o,l+1))})})}catch(e){return Promise.reject(e)}};function g(e,t,r,n,s,o){var a=s.get("message"),i=!1!==a&&!1!==(null==o?void 0:o.message)&&((null==o?void 0:o.message)||a);return!1!==i&&s.showMessage(!e.ok,"function"==typeof i?i(e,r,n,t):t),e}var v=function(e,t,n){try{return Promise.resolve(m(y,e,t,n)).then(function(s){return function(e,t,n,s){var o,i;if(e.status<0)return g({ok:!1,status:e.status,code:e.statusText,headers:{},message:"",data:null},e.method+" "+t+" "+e.statusText,e.method,t,n,s);f(e.status)||null==(i=n.get("errorHandler"))||i(e.status,e.method,t);var l,h,m,v,y,p=a({},(l=e.status,h=e.statusText,m=e.body,v=n.get("responseRule"),y=(null==s?void 0:s.responseRule)||v,f(l)?function(e,t,n,s){var o=e||{resolve:"body"},a={ok:!0,code:n,message:"",data:null};if(202===t||204===t||!s)return a;if("body"===o.resolve)return a.data=r.isJsonLike(s)?r.parseJSON(s):s,a;var i=r.parseJSON(s);if(!i||!r.isStringRecord(i))return a.ok=!1,a.code="ResponseFormatError",a.message="响应内容无法格式化为 Object",a;var l=o.statusField,h=o.statusOKValue||"",d=o.dataField||"data",f=o.messageField||u,m=o.ignoreMessage||"";if(l&&!(l in i))return a.ok=!1,a.code="ResponseFieldMissing",a.message="响应内容找不到状态字段 "+l,a;var g=l?i[l]+"":"";return a.ok=!l||g===h,a.code=g||n,a.data=!0===d?i:d in i?i[d]:null,a.message=c(i,f),m&&a.message&&(Array.isArray(m)&&m.includes(a.message)||"string"==typeof m&&a.message===m)&&(a.message=""),a}(y.ok||v.ok,l,h,m):function(e,t,n){var s=e||{resolve:"json",messageField:u},o={ok:!1,code:t,message:n,data:null};switch(s.resolve){case"body":o.message=d(n)||n;break;case"json":var a=function(e,t,n){if(void 0===n&&(n=u),!r.isJsonLike(e))return{message:""};var s=r.parseJSON(e);return s&&r.isStringRecord(s)?{code:t?c(s,t):"",message:c(s,n)||e}:{message:e}}(n,s.statusField,s.messageField),i=a.message;o.code=a.code||t,o.message=d(n)||i}return o}(y.failed||v.failed,h,m)),{status:e.status,headers:Object.fromEntries(Object.entries(e.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return null==(o=n.get("responseHandler"))||o(a({},p),e.method,t),g(p,p.ok?p.message:e.method+" "+t+" ["+(p.code||e.statusText)+"] "+(p.message||e.statusText),e.method,t,n,s)}(s,e,t,n)})}catch(e){return Promise.reject(e)}},y=function(e,t,n){try{return Promise.resolve(function(e,t,r){try{var n=Object.assign({method:"GET"},r),s="FormData"in globalThis&&n.body instanceof FormData,o=s?"POST":n.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(s?{}:{"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 c=t.getFullUrl(e),l=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),h=n.timeout||t.get("timeout");return Promise.resolve(function(r){try{var n=function(n){var s;return r?n:Promise.resolve(null==(s=t.get("requestHandler"))?void 0:s(a,u,o,e))},s=t.get("requestTransformer"),i=function(){if(s)return Promise.resolve(s({headers:a,params:u,method:o,url:c,body:l})).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,s="string"==typeof e&&e?e:c;return null==(r=t.get("logHandler"))||r({type:"ready",url:s,method:o,headers:a,timeout:h,body:l}),{url:s,method:o,body:l,params:u,headers:a,timeout:h,abort:n.abort,credentials:n.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(e,t,n)).then(function(e){if(!r.isFullURL(e.url))return{url:e.url,method:e.method,status:-1,statusText:"URLFormatError",headers:{},body:""};var t=/^https:\/\//i.test(e.url)?o.default:s.default,n=new URL(e.url),a=e.params;a instanceof Object&&Object.keys(a).forEach(function(e){return n.searchParams.set(e,a[e])});var i="HEAD"===e.method;return new Promise(function(r){var s=t.request(n,{headers:e.headers,method:e.method,timeout:e.timeout>0?e.timeout:void 0},function(t){var s=[];t.on("data",function(e){return s.push(e)}),t.on("end",function(){var o=Object.fromEntries(Object.entries(t.headers).map(function(e){var t=e[1];return[e[0].toLowerCase(),Array.isArray(t)?t.join(","):t]}));r({url:n.toString(),method:e.method,status:t.statusCode||-1,statusText:t.statusMessage||"Unknown",headers:o,body:i?"":Buffer.concat(s).toString("utf-8")})})});s.on("error",function(t){r({url:n.toString(),method:e.method,status:-1,statusText:t.name||"Unknown",body:t.message})}),s.on("timeout",function(){r({url:n.toString(),method:e.method,status:-1,statusText:"Timeout",body:""})}),e.body&&s.write(e.body),s.end()})})}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}(),b=/*#__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)&&!r.isFullURL(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("/")?r.getFullURL(e):r.getFullURL(e,this.config.baseURL)},t.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},e}(),j=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new b(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 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,n){try{return Promise.resolve(function(e,t,n,s){if(t.ok&&!r.isEmpty(t.data)&&s){var o=r.getTypeGuard(s,"响应数据未能正确识别");return o.guard(t.data)||(console.error("ResponseCheckFaild",e,t.data),n.showMessage(!0,e+" "+o.message),t.data=null),t}return t}(e,t,this.config,n))}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 s=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return s.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},t.get=function(e,t,r){try{var n,s=function(r){if(n)return r;var s=o.exec(e,a);o.cache.set(i,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var a=r.call(o,e,s,t||null);return n=1,a})}}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},t.post=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="POST",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.del=function(e,t,r){try{var n=this,s=Object.assign({},r||null);s.method="DELETE";var o=n.guard;return Promise.resolve(n.exec(e,s)).then(function(r){return o.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},t.put=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PUT",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PATCH",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function P(e){return new j(v,e)}var T=P(),x=T.setConfig,O=T.head,w=T.get,R=T.post,L=T.del,E=T.put,k=T.patch;exports.NetRequest=P,exports.del=L,exports.get=w,exports.head=O,exports.patch=k,exports.post=R,exports.put=E,exports.setGlobalConfig=x;
|
|
1
|
+
var e=require("node:http"),t=require("node:https"),r=require("@seayoo-web/utils");function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var s=/*#__PURE__*/n(e),o=/*#__PURE__*/n(t);function a(){return a=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},a.apply(this,arguments)}function i(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 u="message";function c(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 i(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)?i(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 s=r.value;if(s in e)return(o=e[s])?"string"==typeof o?o:JSON.stringify(o):""}var o;return""}var l=/<title>([^<]+)<\/title>/i,h=/<message>([^<]+)<\/message>/i;function d(e){var t=e.match(l);if(t)return t[1];var r=e.match(h);return r?r[1]:""}function f(e){return e>=200&&e<400}var m=function e(t,n,s,o,a){try{var i,u,c,l=a||0,h=Math.max(0,Math.min(10,null!=(i=null!=(u=null==o?void 0:o.maxRetry)?u:s.get("maxRetry"))?i:0)),d=null!=(c=null==o?void 0:o.retryResolve)?c:s.get("retryResolve"),m=s.get("logHandler")||r.noop;m({type:"prepear",url:n,method:(null==o?void 0:o.method)||"GET",retry:l,maxRetry:h,message:0===l?"start":"retry "+l+"/"+h+" start",headers:null==o?void 0:o.headers,options:o});var g=Date.now();return Promise.resolve(t(n,s,o)).then(function(a){var i,u,c=a.status,v=Date.now()-g,y="[cost "+v+"]["+c+"] "+(c<0?a.body:"");m({type:"finished",url:n,method:a.method,retry:l,maxRetry:h,message:0===l?"finish "+y:"retry "+l+"/"+h+" finish "+y,response:a,headers:a.headers,cost:v});var p=f(c);if(!h||"network"===d&&c>0||"status"===d&&p||Array.isArray(d)&&!d.includes(c)||"function"==typeof d&&!0!==d(a,l)||l>=h)return a;var b=null!=(i=null!=(u=null==o?void 0:o.retryInterval)?u:s.get("retryInterval"))?i:1e3;return Promise.resolve(r.sleep(Math.max(100,"2EB"===b?1e3*Math.pow(2,l):"function"==typeof b?b(l+1)||0:b))).then(function(){return Promise.resolve(e(t,n,s,o,l+1))})})}catch(e){return Promise.reject(e)}};function g(e,t,r,n,s,o){var a=s.get("message"),i=!1!==a&&!1!==(null==o?void 0:o.message)&&((null==o?void 0:o.message)||a);if(!1!==i){var u="function"==typeof i?i(e,r,n,t):t;u instanceof Error?s.showMessage(!0,u.message):u&&"object"==typeof u&&"message"in u?s.showMessage(!1,u.message):s.showMessage(!e.ok,u)}return e}var v=function(e,t,n){try{return Promise.resolve(m(y,e,t,n)).then(function(s){return function(e,t,n,s){var o,i;if(e.status<0)return g({ok:!1,status:e.status,code:e.statusText,headers:{},message:"",data:null},e.method+" "+t+" "+e.statusText,e.method,t,n,s);f(e.status)||null==(i=n.get("errorHandler"))||i(e.status,e.method,t);var l,h,m,v,y,p=a({},(l=e.status,h=e.statusText,m=e.body,v=n.get("responseRule"),y=(null==s?void 0:s.responseRule)||v,f(l)?function(e,t,n,s){var o=e||{resolve:"body"},a={ok:!0,code:n,message:"",data:null};if(202===t||204===t||!s)return a;if("body"===o.resolve)return a.data=r.isJsonLike(s)?r.parseJSON(s):s,a;var i=r.parseJSON(s);if(!i||!r.isStringRecord(i))return a.ok=!1,a.code="ResponseFormatError",a.message="响应内容无法格式化为 Object",a;var l=o.statusField,h=o.statusOKValue||"",d=o.dataField||"data",f=o.messageField||u,m=o.ignoreMessage||"";if(l&&!(l in i))return a.ok=!1,a.code="ResponseFieldMissing",a.message="响应内容找不到状态字段 "+l,a;var g=l?i[l]+"":"";return a.ok=!l||g===h,a.code=g||n,a.data=!0===d?i:d in i?i[d]:null,a.message=c(i,f),m&&a.message&&(Array.isArray(m)&&m.includes(a.message)||"string"==typeof m&&a.message===m)&&(a.message=""),a}(y.ok||v.ok,l,h,m):function(e,t,n){var s=e||{resolve:"json",messageField:u},o={ok:!1,code:t,message:n,data:null};switch(s.resolve){case"body":o.message=d(n)||n;break;case"json":var a=function(e,t,n){if(void 0===n&&(n=u),!r.isJsonLike(e))return{message:""};var s=r.parseJSON(e);return s&&r.isStringRecord(s)?{code:t?c(s,t):"",message:c(s,n)||e}:{message:e}}(n,s.statusField,s.messageField),i=a.message;o.code=a.code||t,o.message=d(n)||i}return o}(y.failed||v.failed,h,m)),{status:e.status,headers:Object.fromEntries(Object.entries(e.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return null==(o=n.get("responseHandler"))||o(a({},p),e.method,t),g(p,p.ok?p.message:e.method+" "+t+" ["+(p.code||e.statusText)+"] "+(p.message||e.statusText),e.method,t,n,s)}(s,e,t,n)})}catch(e){return Promise.reject(e)}},y=function(e,t,n){try{return Promise.resolve(function(e,t,r){try{var n=Object.assign({method:"GET"},r),s="FormData"in globalThis&&n.body instanceof FormData,o=s?"POST":n.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(s?{}:{"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 c=t.getFullUrl(e),l=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),h=n.timeout||t.get("timeout");return Promise.resolve(function(r){try{var n=function(n){var s;return r?n:Promise.resolve(null==(s=t.get("requestHandler"))?void 0:s(a,u,o,e))},s=t.get("requestTransformer"),i=function(){if(s)return Promise.resolve(s({headers:a,params:u,method:o,url:c,body:l})).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,s="string"==typeof e&&e?e:c;return null==(r=t.get("logHandler"))||r({type:"ready",url:s,method:o,headers:a,timeout:h,body:l}),{url:s,method:o,body:l,params:u,headers:a,timeout:h,abort:n.abort,credentials:n.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(e,t,n)).then(function(e){if(!r.isFullURL(e.url))return{url:e.url,method:e.method,status:-1,statusText:"URLFormatError",headers:{},body:""};var t=/^https:\/\//i.test(e.url)?o.default:s.default,n=new URL(e.url),a=e.params;a instanceof Object&&Object.keys(a).forEach(function(e){return n.searchParams.set(e,a[e])});var i="HEAD"===e.method;return new Promise(function(r){var s=t.request(n,{headers:e.headers,method:e.method,timeout:e.timeout>0?e.timeout:void 0},function(t){var s=[];t.on("data",function(e){return s.push(e)}),t.on("end",function(){var o=Object.fromEntries(Object.entries(t.headers).map(function(e){var t=e[1];return[e[0].toLowerCase(),Array.isArray(t)?t.join(","):t]}));r({url:n.toString(),method:e.method,status:t.statusCode||-1,statusText:t.statusMessage||"Unknown",headers:o,body:i?"":Buffer.concat(s).toString("utf-8")})})});s.on("error",function(t){r({url:n.toString(),method:e.method,status:-1,statusText:t.name||"Unknown",body:t.message})}),s.on("timeout",function(){r({url:n.toString(),method:e.method,status:-1,statusText:"Timeout",body:""})}),e.body&&s.write(e.body),s.end()})})}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}(),b=/*#__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)&&!r.isFullURL(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("/")?r.getFullURL(e):r.getFullURL(e,this.config.baseURL)},t.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},e}(),j=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new b(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 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,n){try{return Promise.resolve(function(e,t,n,s){if(t.ok&&!r.isEmpty(t.data)&&s){var o=r.getTypeGuard(s,"响应数据未能正确识别");return o.guard(t.data)||(console.error("ResponseCheckFaild",e,t.data),n.showMessage(!0,e+" "+o.message),t.data=null),t}return t}(e,t,this.config,n))}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 s=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return s.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},t.get=function(e,t,r){try{var n,s=function(r){if(n)return r;var s=o.exec(e,a);o.cache.set(i,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var a=r.call(o,e,s,t||null);return n=1,a})}}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},t.post=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="POST",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.del=function(e,t,r){try{var n=this,s=Object.assign({},r||null);s.method="DELETE";var o=n.guard;return Promise.resolve(n.exec(e,s)).then(function(r){return o.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},t.put=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PUT",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PATCH",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function P(e){return new j(v,e)}var T=P(),x=T.setConfig,w=T.head,O=T.get,R=T.post,E=T.del,L=T.put,k=T.patch;exports.NetRequest=P,exports.del=E,exports.get=O,exports.head=w,exports.patch=k,exports.post=R,exports.put=L,exports.setGlobalConfig=x;
|
package/dist/node.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"node:http";import t from"node:https";import{isJsonLike as r,parseJSON as n,isStringRecord as s,noop as o,sleep as a,isFullURL as i,isEmpty as u,getTypeGuard as c,getFullURL as l}from"@seayoo-web/utils";function h(){return h=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},h.apply(this,arguments)}function d(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="message";function m(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 d(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)?d(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 s=r.value;if(s in e)return(o=e[s])?"string"==typeof o?o:JSON.stringify(o):""}var o;return""}var g=/<title>([^<]+)<\/title>/i,v=/<message>([^<]+)<\/message>/i;function y(e){var t=e.match(g);if(t)return t[1];var r=e.match(v);return r?r[1]:""}function b(e){return e>=200&&e<400}var p=function e(t,r,n,s,i){try{var u,c,l,h=i||0,d=Math.max(0,Math.min(10,null!=(u=null!=(c=null==s?void 0:s.maxRetry)?c:n.get("maxRetry"))?u:0)),f=null!=(l=null==s?void 0:s.retryResolve)?l:n.get("retryResolve"),m=n.get("logHandler")||o;m({type:"prepear",url:r,method:(null==s?void 0:s.method)||"GET",retry:h,maxRetry:d,message:0===h?"start":"retry "+h+"/"+d+" start",headers:null==s?void 0:s.headers,options:s});var g=Date.now();return Promise.resolve(t(r,n,s)).then(function(o){var i,u,c=o.status,l=Date.now()-g,v="[cost "+l+"]["+c+"] "+(c<0?o.body:"");m({type:"finished",url:r,method:o.method,retry:h,maxRetry:d,message:0===h?"finish "+v:"retry "+h+"/"+d+" finish "+v,response:o,headers:o.headers,cost:l});var y=b(c);if(!d||"network"===f&&c>0||"status"===f&&y||Array.isArray(f)&&!f.includes(c)||"function"==typeof f&&!0!==f(o,h)||h>=d)return o;var p=null!=(i=null!=(u=null==s?void 0:s.retryInterval)?u:n.get("retryInterval"))?i:1e3;return Promise.resolve(a(Math.max(100,"2EB"===p?1e3*Math.pow(2,h):"function"==typeof p?p(h+1)||0:p))).then(function(){return Promise.resolve(e(t,r,n,s,h+1))})})}catch(e){return Promise.reject(e)}};function j(e,t,r,n,s,o){var a=s.get("message"),i=!1!==a&&!1!==(null==o?void 0:o.message)&&((null==o?void 0:o.message)||a);return!1!==i&&s.showMessage(!e.ok,"function"==typeof i?i(e,r,n,t):t),e}var P=function(e,t,o){try{return Promise.resolve(p(T,e,t,o)).then(function(a){return function(e,t,o,a){var i,u;if(e.status<0)return j({ok:!1,status:e.status,code:e.statusText,headers:{},message:"",data:null},e.method+" "+t+" "+e.statusText,e.method,t,o,a);b(e.status)||null==(u=o.get("errorHandler"))||u(e.status,e.method,t);var c,l,d,g,v,p=h({},(c=e.status,l=e.statusText,d=e.body,g=o.get("responseRule"),v=(null==a?void 0:a.responseRule)||g,b(c)?function(e,t,o,a){var i=e||{resolve:"body"},u={ok:!0,code:o,message:"",data:null};if(202===t||204===t||!a)return u;if("body"===i.resolve)return u.data=r(a)?n(a):a,u;var c=n(a);if(!c||!s(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=i.statusField,h=i.statusOKValue||"",d=i.dataField||"data",g=i.messageField||f,v=i.ignoreMessage||"";if(l&&!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var y=l?c[l]+"":"";return u.ok=!l||y===h,u.code=y||o,u.data=!0===d?c:d in c?c[d]:null,u.message=m(c,g),v&&u.message&&(Array.isArray(v)&&v.includes(u.message)||"string"==typeof v&&u.message===v)&&(u.message=""),u}(v.ok||g.ok,c,l,d):function(e,t,o){var a=e||{resolve:"json",messageField:f},i={ok:!1,code:t,message:o,data:null};switch(a.resolve){case"body":i.message=y(o)||o;break;case"json":var u=function(e,t,o){if(void 0===o&&(o=f),!r(e))return{message:""};var a=n(e);return a&&s(a)?{code:t?m(a,t):"",message:m(a,o)||e}:{message:e}}(o,a.statusField,a.messageField),c=u.message;i.code=u.code||t,i.message=y(o)||c}return i}(v.failed||g.failed,l,d)),{status:e.status,headers:Object.fromEntries(Object.entries(e.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return null==(i=o.get("responseHandler"))||i(h({},p),e.method,t),j(p,p.ok?p.message:e.method+" "+t+" ["+(p.code||e.statusText)+"] "+(p.message||e.statusText),e.method,t,o,a)}(a,e,t,o)})}catch(e){return Promise.reject(e)}},T=function(r,n,s){try{return Promise.resolve(function(e,t,r){try{var n=Object.assign({method:"GET"},r),s="FormData"in globalThis&&n.body instanceof FormData,o=s?"POST":n.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(s?{}:{"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 c=t.getFullUrl(e),l=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),h=n.timeout||t.get("timeout");return Promise.resolve(function(r){try{var n=function(n){var s;return r?n:Promise.resolve(null==(s=t.get("requestHandler"))?void 0:s(a,u,o,e))},s=t.get("requestTransformer"),i=function(){if(s)return Promise.resolve(s({headers:a,params:u,method:o,url:c,body:l})).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,s="string"==typeof e&&e?e:c;return null==(r=t.get("logHandler"))||r({type:"ready",url:s,method:o,headers:a,timeout:h,body:l}),{url:s,method:o,body:l,params:u,headers:a,timeout:h,abort:n.abort,credentials:n.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(r,n,s)).then(function(r){if(!i(r.url))return{url:r.url,method:r.method,status:-1,statusText:"URLFormatError",headers:{},body:""};var n=/^https:\/\//i.test(r.url)?t:e,s=new URL(r.url),o=r.params;o instanceof Object&&Object.keys(o).forEach(function(e){return s.searchParams.set(e,o[e])});var a="HEAD"===r.method;return new Promise(function(e){var t=n.request(s,{headers:r.headers,method:r.method,timeout:r.timeout>0?r.timeout:void 0},function(t){var n=[];t.on("data",function(e){return n.push(e)}),t.on("end",function(){var o=Object.fromEntries(Object.entries(t.headers).map(function(e){var t=e[1];return[e[0].toLowerCase(),Array.isArray(t)?t.join(","):t]}));e({url:s.toString(),method:r.method,status:t.statusCode||-1,statusText:t.statusMessage||"Unknown",headers:o,body:a?"":Buffer.concat(n).toString("utf-8")})})});t.on("error",function(t){e({url:s.toString(),method:r.method,status:-1,statusText:t.name||"Unknown",body:t.message})}),t.on("timeout",function(){e({url:s.toString(),method:r.method,status:-1,statusText:"Timeout",body:""})}),r.body&&t.write(r.body),t.end()})})}catch(e){return Promise.reject(e)}},w=/*#__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}(),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)&&!i(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("/")?l(e):l(e,this.config.baseURL)},t.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},e}(),x=/*#__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 w(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 s=c(n,"响应数据未能正确识别");return s.guard(t.data)||(console.error("ResponseCheckFaild",e,t.data),r.showMessage(!0,e+" "+s.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 s=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return s.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},t.get=function(e,t,r){try{var n,s=function(r){if(n)return r;var s=o.exec(e,a);o.cache.set(i,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var a=r.call(o,e,s,t||null);return n=1,a})}}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},t.post=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="POST",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.del=function(e,t,r){try{var n=this,s=Object.assign({},r||null);s.method="DELETE";var o=n.guard;return Promise.resolve(n.exec(e,s)).then(function(r){return o.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},t.put=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PUT",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PATCH",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function R(e){return new x(P,e)}var E=R(),k=E.setConfig,A=E.head,L=E.get,F=E.post,U=E.del,C=E.put,S=E.patch;export{R as NetRequest,U as del,L as get,A as head,S as patch,F as post,C as put,k as setGlobalConfig};
|
|
1
|
+
import e from"node:http";import t from"node:https";import{isJsonLike as r,parseJSON as n,isStringRecord as s,noop as o,sleep as a,isFullURL as i,isEmpty as u,getTypeGuard as c,getFullURL as l}from"@seayoo-web/utils";function h(){return h=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},h.apply(this,arguments)}function d(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="message";function m(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 d(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)?d(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 s=r.value;if(s in e)return(o=e[s])?"string"==typeof o?o:JSON.stringify(o):""}var o;return""}var g=/<title>([^<]+)<\/title>/i,v=/<message>([^<]+)<\/message>/i;function y(e){var t=e.match(g);if(t)return t[1];var r=e.match(v);return r?r[1]:""}function b(e){return e>=200&&e<400}var p=function e(t,r,n,s,i){try{var u,c,l,h=i||0,d=Math.max(0,Math.min(10,null!=(u=null!=(c=null==s?void 0:s.maxRetry)?c:n.get("maxRetry"))?u:0)),f=null!=(l=null==s?void 0:s.retryResolve)?l:n.get("retryResolve"),m=n.get("logHandler")||o;m({type:"prepear",url:r,method:(null==s?void 0:s.method)||"GET",retry:h,maxRetry:d,message:0===h?"start":"retry "+h+"/"+d+" start",headers:null==s?void 0:s.headers,options:s});var g=Date.now();return Promise.resolve(t(r,n,s)).then(function(o){var i,u,c=o.status,l=Date.now()-g,v="[cost "+l+"]["+c+"] "+(c<0?o.body:"");m({type:"finished",url:r,method:o.method,retry:h,maxRetry:d,message:0===h?"finish "+v:"retry "+h+"/"+d+" finish "+v,response:o,headers:o.headers,cost:l});var y=b(c);if(!d||"network"===f&&c>0||"status"===f&&y||Array.isArray(f)&&!f.includes(c)||"function"==typeof f&&!0!==f(o,h)||h>=d)return o;var p=null!=(i=null!=(u=null==s?void 0:s.retryInterval)?u:n.get("retryInterval"))?i:1e3;return Promise.resolve(a(Math.max(100,"2EB"===p?1e3*Math.pow(2,h):"function"==typeof p?p(h+1)||0:p))).then(function(){return Promise.resolve(e(t,r,n,s,h+1))})})}catch(e){return Promise.reject(e)}};function j(e,t,r,n,s,o){var a=s.get("message"),i=!1!==a&&!1!==(null==o?void 0:o.message)&&((null==o?void 0:o.message)||a);if(!1!==i){var u="function"==typeof i?i(e,r,n,t):t;u instanceof Error?s.showMessage(!0,u.message):u&&"object"==typeof u&&"message"in u?s.showMessage(!1,u.message):s.showMessage(!e.ok,u)}return e}var P=function(e,t,o){try{return Promise.resolve(p(T,e,t,o)).then(function(a){return function(e,t,o,a){var i,u;if(e.status<0)return j({ok:!1,status:e.status,code:e.statusText,headers:{},message:"",data:null},e.method+" "+t+" "+e.statusText,e.method,t,o,a);b(e.status)||null==(u=o.get("errorHandler"))||u(e.status,e.method,t);var c,l,d,g,v,p=h({},(c=e.status,l=e.statusText,d=e.body,g=o.get("responseRule"),v=(null==a?void 0:a.responseRule)||g,b(c)?function(e,t,o,a){var i=e||{resolve:"body"},u={ok:!0,code:o,message:"",data:null};if(202===t||204===t||!a)return u;if("body"===i.resolve)return u.data=r(a)?n(a):a,u;var c=n(a);if(!c||!s(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=i.statusField,h=i.statusOKValue||"",d=i.dataField||"data",g=i.messageField||f,v=i.ignoreMessage||"";if(l&&!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var y=l?c[l]+"":"";return u.ok=!l||y===h,u.code=y||o,u.data=!0===d?c:d in c?c[d]:null,u.message=m(c,g),v&&u.message&&(Array.isArray(v)&&v.includes(u.message)||"string"==typeof v&&u.message===v)&&(u.message=""),u}(v.ok||g.ok,c,l,d):function(e,t,o){var a=e||{resolve:"json",messageField:f},i={ok:!1,code:t,message:o,data:null};switch(a.resolve){case"body":i.message=y(o)||o;break;case"json":var u=function(e,t,o){if(void 0===o&&(o=f),!r(e))return{message:""};var a=n(e);return a&&s(a)?{code:t?m(a,t):"",message:m(a,o)||e}:{message:e}}(o,a.statusField,a.messageField),c=u.message;i.code=u.code||t,i.message=y(o)||c}return i}(v.failed||g.failed,l,d)),{status:e.status,headers:Object.fromEntries(Object.entries(e.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return null==(i=o.get("responseHandler"))||i(h({},p),e.method,t),j(p,p.ok?p.message:e.method+" "+t+" ["+(p.code||e.statusText)+"] "+(p.message||e.statusText),e.method,t,o,a)}(a,e,t,o)})}catch(e){return Promise.reject(e)}},T=function(r,n,s){try{return Promise.resolve(function(e,t,r){try{var n=Object.assign({method:"GET"},r),s="FormData"in globalThis&&n.body instanceof FormData,o=s?"POST":n.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(s?{}:{"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 c=t.getFullUrl(e),l=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),h=n.timeout||t.get("timeout");return Promise.resolve(function(r){try{var n=function(n){var s;return r?n:Promise.resolve(null==(s=t.get("requestHandler"))?void 0:s(a,u,o,e))},s=t.get("requestTransformer"),i=function(){if(s)return Promise.resolve(s({headers:a,params:u,method:o,url:c,body:l})).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,s="string"==typeof e&&e?e:c;return null==(r=t.get("logHandler"))||r({type:"ready",url:s,method:o,headers:a,timeout:h,body:l}),{url:s,method:o,body:l,params:u,headers:a,timeout:h,abort:n.abort,credentials:n.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(r,n,s)).then(function(r){if(!i(r.url))return{url:r.url,method:r.method,status:-1,statusText:"URLFormatError",headers:{},body:""};var n=/^https:\/\//i.test(r.url)?t:e,s=new URL(r.url),o=r.params;o instanceof Object&&Object.keys(o).forEach(function(e){return s.searchParams.set(e,o[e])});var a="HEAD"===r.method;return new Promise(function(e){var t=n.request(s,{headers:r.headers,method:r.method,timeout:r.timeout>0?r.timeout:void 0},function(t){var n=[];t.on("data",function(e){return n.push(e)}),t.on("end",function(){var o=Object.fromEntries(Object.entries(t.headers).map(function(e){var t=e[1];return[e[0].toLowerCase(),Array.isArray(t)?t.join(","):t]}));e({url:s.toString(),method:r.method,status:t.statusCode||-1,statusText:t.statusMessage||"Unknown",headers:o,body:a?"":Buffer.concat(n).toString("utf-8")})})});t.on("error",function(t){e({url:s.toString(),method:r.method,status:-1,statusText:t.name||"Unknown",body:t.message})}),t.on("timeout",function(){e({url:s.toString(),method:r.method,status:-1,statusText:"Timeout",body:""})}),r.body&&t.write(r.body),t.end()})})}catch(e){return Promise.reject(e)}},w=/*#__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}(),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)&&!i(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("/")?l(e):l(e,this.config.baseURL)},t.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},e}(),x=/*#__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 w(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 s=c(n,"响应数据未能正确识别");return s.guard(t.data)||(console.error("ResponseCheckFaild",e,t.data),r.showMessage(!0,e+" "+s.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 s=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return s.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},t.get=function(e,t,r){try{var n,s=function(r){if(n)return r;var s=o.exec(e,a);o.cache.set(i,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var a=r.call(o,e,s,t||null);return n=1,a})}}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},t.post=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="POST",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.del=function(e,t,r){try{var n=this,s=Object.assign({},r||null);s.method="DELETE";var o=n.guard;return Promise.resolve(n.exec(e,s)).then(function(r){return o.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},t.put=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PUT",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PATCH",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function E(e){return new x(P,e)}var R=E(),k=R.setConfig,A=R.head,L=R.get,F=R.post,U=R.del,M=R.put,C=R.patch;export{E as NetRequest,U as del,L as get,A as head,C as patch,F as post,M as put,k as setGlobalConfig};
|
package/dist/wx.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
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="message";function s(e,t){for(var n,s=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 s=0;return function(){return s>=e.length?{done:!0}:{done:!1,value:e[s++]}}}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=s()).done;){var o=n.value;if(o in e)return(a=e[o])?"string"==typeof a?a:JSON.stringify(a):""}var a;return""}var o=/<title>([^<]+)<\/title>/i,a=/<message>([^<]+)<\/message>/i;function i(e){var t=e.match(o);if(t)return t[1];var r=e.match(a);return r?r[1]:""}function u(e){return e>=200&&e<400}var c=function t(r,n,s,o,a){try{var i,c,l,h=a||0,d=Math.max(0,Math.min(10,null!=(i=null!=(c=null==o?void 0:o.maxRetry)?c:s.get("maxRetry"))?i:0)),f=null!=(l=null==o?void 0:o.retryResolve)?l:s.get("retryResolve"),g=s.get("logHandler")||e.noop;g({type:"prepear",url:n,method:(null==o?void 0:o.method)||"GET",retry:h,maxRetry:d,message:0===h?"start":"retry "+h+"/"+d+" start",headers:null==o?void 0:o.headers,options:o});var m=Date.now();return Promise.resolve(r(n,s,o)).then(function(a){var i,c,l=a.status,v=Date.now()-m,y="[cost "+v+"]["+l+"] "+(l<0?a.body:"");g({type:"finished",url:n,method:a.method,retry:h,maxRetry:d,message:0===h?"finish "+y:"retry "+h+"/"+d+" finish "+y,response:a,headers:a.headers,cost:v});var p=u(l);if(!d||"network"===f&&l>0||"status"===f&&p||Array.isArray(f)&&!f.includes(l)||"function"==typeof f&&!0!==f(a,h)||h>=d)return a;var b=null!=(i=null!=(c=null==o?void 0:o.retryInterval)?c:s.get("retryInterval"))?i:1e3;return Promise.resolve(e.sleep(Math.max(100,"2EB"===b?1e3*Math.pow(2,h):"function"==typeof b?b(h+1)||0:b))).then(function(){return Promise.resolve(t(r,n,s,o,h+1))})})}catch(e){return Promise.reject(e)}};function l(e,t,r,n,s,o){var a=s.get("message"),i=!1!==a&&!1!==(null==o?void 0:o.message)&&((null==o?void 0:o.message)||a);return!1!==i&&s.showMessage(!e.ok,"function"==typeof i?i(e,r,n,t):t),e}var h=function(r,o,a){try{return Promise.resolve(c(d,r,o,a)).then(function(c){return function(r,o,a,c){var h,d;if(r.status<0)return l({ok:!1,status:r.status,code:r.statusText,headers:{},message:"",data:null},r.method+" "+o+" "+r.statusText,r.method,o,a,c);u(r.status)||null==(d=a.get("errorHandler"))||d(r.status,r.method,o);var f,g,m,v,y,p=t({},(f=r.status,g=r.statusText,m=r.body,v=a.get("responseRule"),y=(null==c?void 0:c.responseRule)||v,u(f)?function(t,r,o,a){var i=t||{resolve:"body"},u={ok:!0,code:o,message:"",data:null};if(202===r||204===r||!a)return u;if("body"===i.resolve)return u.data=e.isJsonLike(a)?e.parseJSON(a):a,u;var c=e.parseJSON(a);if(!c||!e.isStringRecord(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=i.statusField,h=i.statusOKValue||"",d=i.dataField||"data",f=i.messageField||n,g=i.ignoreMessage||"";if(l&&!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var m=l?c[l]+"":"";return u.ok=!l||m===h,u.code=m||o,u.data=!0===d?c:d in c?c[d]:null,u.message=s(c,f),g&&u.message&&(Array.isArray(g)&&g.includes(u.message)||"string"==typeof g&&u.message===g)&&(u.message=""),u}(y.ok||v.ok,f,g,m):function(t,r,o){var a=t||{resolve:"json",messageField:n},u={ok:!1,code:r,message:o,data:null};switch(a.resolve){case"body":u.message=i(o)||o;break;case"json":var c=function(t,r,o){if(void 0===o&&(o=n),!e.isJsonLike(t))return{message:""};var a=e.parseJSON(t);return a&&e.isStringRecord(a)?{code:r?s(a,r):"",message:s(a,o)||t}:{message:t}}(o,a.statusField,a.messageField),l=c.message;u.code=c.code||r,u.message=i(o)||l}return u}(y.failed||v.failed,g,m)),{status:r.status,headers:Object.fromEntries(Object.entries(r.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return null==(h=a.get("responseHandler"))||h(t({},p),r.method,o),l(p,p.ok?p.message:r.method+" "+o+" ["+(p.code||r.statusText)+"] "+(p.message||r.statusText),r.method,o,a,c)}(c,r,o,a)})}catch(e){return Promise.reject(e)}},d=function(r,n,s){try{return Promise.resolve(function(e,t,r){try{var n=Object.assign({method:"GET"},r),s="FormData"in globalThis&&n.body instanceof FormData,o=s?"POST":n.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(s?{}:{"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 c=t.getFullUrl(e),l=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),h=n.timeout||t.get("timeout");return Promise.resolve(function(r){try{var n=function(n){var s;return r?n:Promise.resolve(null==(s=t.get("requestHandler"))?void 0:s(a,u,o,e))},s=t.get("requestTransformer"),i=function(){if(s)return Promise.resolve(s({headers:a,params:u,method:o,url:c,body:l})).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,s="string"==typeof e&&e?e:c;return null==(r=t.get("logHandler"))||r({type:"ready",url:s,method:o,headers:a,timeout:h,body:l}),{url:s,method:o,body:l,params:u,headers:a,timeout:h,abort:n.abort,credentials:n.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(r,n,s)).then(function(r){var n="PATCH"===r.method?"POST":r.method,s=e.addParamsToString(r.url,r.params);return globalThis.wx?new Promise(function(e){wx.request({url:s,data:r.body,header:r.headers,method:n,dataType:"string",responseType:"text",fail:function(){e({url:s,method:n,status:-1,statusText:"NetworkError",body:""})},success:function(o){var a;e({url:s,method:n,status:o.statusCode,statusText:o.statusCode+"",headers:t({},o.header),body:"HEAD"===r.method?"":(a=o.data,"string"==typeof a?a:a instanceof ArrayBuffer&&"TextDecoder"in globalThis?(new TextDecoder).decode(a):JSON.stringify(a))})}})}):{url:s,method:n,status:-1,statusText:"NotSupport",body:"NotFound namespace of wx"}})}catch(e){return Promise.reject(e)}},f=/*#__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}(),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}(),m=/*#__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 f(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,s){if(r.ok&&!e.isEmpty(r.data)&&s){var o=e.getTypeGuard(s,"响应数据未能正确识别");return o.guard(r.data)||(console.error("ResponseCheckFaild",t,r.data),n.showMessage(!0,t+" "+o.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 s=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return s.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},r.get=function(e,t,r){try{var n,s=function(r){if(n)return r;var s=o.exec(e,a);o.cache.set(i,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var a=r.call(o,e,s,t||null);return n=1,a})}}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},r.post=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="POST",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.del=function(e,t,r){try{var n=this,s=Object.assign({},r||null);s.method="DELETE";var o=n.guard;return Promise.resolve(n.exec(e,s)).then(function(r){return o.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},r.put=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PUT",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.patch=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PATCH",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t}();function v(e){return new m(h,e)}var y=v(),p=y.setConfig,b=y.head,T=y.get,P=y.post,j=y.del,x=y.put;exports.NetRequest=v,exports.del=j,exports.get=T,exports.head=b,exports.post=P,exports.put=x,exports.setGlobalConfig=p;
|
|
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="message";function s(e,t){for(var n,s=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 s=0;return function(){return s>=e.length?{done:!0}:{done:!1,value:e[s++]}}}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=s()).done;){var o=n.value;if(o in e)return(a=e[o])?"string"==typeof a?a:JSON.stringify(a):""}var a;return""}var o=/<title>([^<]+)<\/title>/i,a=/<message>([^<]+)<\/message>/i;function i(e){var t=e.match(o);if(t)return t[1];var r=e.match(a);return r?r[1]:""}function u(e){return e>=200&&e<400}var c=function t(r,n,s,o,a){try{var i,c,l,h=a||0,d=Math.max(0,Math.min(10,null!=(i=null!=(c=null==o?void 0:o.maxRetry)?c:s.get("maxRetry"))?i:0)),f=null!=(l=null==o?void 0:o.retryResolve)?l:s.get("retryResolve"),g=s.get("logHandler")||e.noop;g({type:"prepear",url:n,method:(null==o?void 0:o.method)||"GET",retry:h,maxRetry:d,message:0===h?"start":"retry "+h+"/"+d+" start",headers:null==o?void 0:o.headers,options:o});var m=Date.now();return Promise.resolve(r(n,s,o)).then(function(a){var i,c,l=a.status,v=Date.now()-m,y="[cost "+v+"]["+l+"] "+(l<0?a.body:"");g({type:"finished",url:n,method:a.method,retry:h,maxRetry:d,message:0===h?"finish "+y:"retry "+h+"/"+d+" finish "+y,response:a,headers:a.headers,cost:v});var p=u(l);if(!d||"network"===f&&l>0||"status"===f&&p||Array.isArray(f)&&!f.includes(l)||"function"==typeof f&&!0!==f(a,h)||h>=d)return a;var b=null!=(i=null!=(c=null==o?void 0:o.retryInterval)?c:s.get("retryInterval"))?i:1e3;return Promise.resolve(e.sleep(Math.max(100,"2EB"===b?1e3*Math.pow(2,h):"function"==typeof b?b(h+1)||0:b))).then(function(){return Promise.resolve(t(r,n,s,o,h+1))})})}catch(e){return Promise.reject(e)}};function l(e,t,r,n,s,o){var a=s.get("message"),i=!1!==a&&!1!==(null==o?void 0:o.message)&&((null==o?void 0:o.message)||a);if(!1!==i){var u="function"==typeof i?i(e,r,n,t):t;u instanceof Error?s.showMessage(!0,u.message):u&&"object"==typeof u&&"message"in u?s.showMessage(!1,u.message):s.showMessage(!e.ok,u)}return e}var h=function(r,o,a){try{return Promise.resolve(c(d,r,o,a)).then(function(c){return function(r,o,a,c){var h,d;if(r.status<0)return l({ok:!1,status:r.status,code:r.statusText,headers:{},message:"",data:null},r.method+" "+o+" "+r.statusText,r.method,o,a,c);u(r.status)||null==(d=a.get("errorHandler"))||d(r.status,r.method,o);var f,g,m,v,y,p=t({},(f=r.status,g=r.statusText,m=r.body,v=a.get("responseRule"),y=(null==c?void 0:c.responseRule)||v,u(f)?function(t,r,o,a){var i=t||{resolve:"body"},u={ok:!0,code:o,message:"",data:null};if(202===r||204===r||!a)return u;if("body"===i.resolve)return u.data=e.isJsonLike(a)?e.parseJSON(a):a,u;var c=e.parseJSON(a);if(!c||!e.isStringRecord(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=i.statusField,h=i.statusOKValue||"",d=i.dataField||"data",f=i.messageField||n,g=i.ignoreMessage||"";if(l&&!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var m=l?c[l]+"":"";return u.ok=!l||m===h,u.code=m||o,u.data=!0===d?c:d in c?c[d]:null,u.message=s(c,f),g&&u.message&&(Array.isArray(g)&&g.includes(u.message)||"string"==typeof g&&u.message===g)&&(u.message=""),u}(y.ok||v.ok,f,g,m):function(t,r,o){var a=t||{resolve:"json",messageField:n},u={ok:!1,code:r,message:o,data:null};switch(a.resolve){case"body":u.message=i(o)||o;break;case"json":var c=function(t,r,o){if(void 0===o&&(o=n),!e.isJsonLike(t))return{message:""};var a=e.parseJSON(t);return a&&e.isStringRecord(a)?{code:r?s(a,r):"",message:s(a,o)||t}:{message:t}}(o,a.statusField,a.messageField),l=c.message;u.code=c.code||r,u.message=i(o)||l}return u}(y.failed||v.failed,g,m)),{status:r.status,headers:Object.fromEntries(Object.entries(r.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return null==(h=a.get("responseHandler"))||h(t({},p),r.method,o),l(p,p.ok?p.message:r.method+" "+o+" ["+(p.code||r.statusText)+"] "+(p.message||r.statusText),r.method,o,a,c)}(c,r,o,a)})}catch(e){return Promise.reject(e)}},d=function(r,n,s){try{return Promise.resolve(function(e,t,r){try{var n=Object.assign({method:"GET"},r),s="FormData"in globalThis&&n.body instanceof FormData,o=s?"POST":n.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(s?{}:{"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 c=t.getFullUrl(e),l=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),h=n.timeout||t.get("timeout");return Promise.resolve(function(r){try{var n=function(n){var s;return r?n:Promise.resolve(null==(s=t.get("requestHandler"))?void 0:s(a,u,o,e))},s=t.get("requestTransformer"),i=function(){if(s)return Promise.resolve(s({headers:a,params:u,method:o,url:c,body:l})).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,s="string"==typeof e&&e?e:c;return null==(r=t.get("logHandler"))||r({type:"ready",url:s,method:o,headers:a,timeout:h,body:l}),{url:s,method:o,body:l,params:u,headers:a,timeout:h,abort:n.abort,credentials:n.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(r,n,s)).then(function(r){var n="PATCH"===r.method?"POST":r.method,s=e.addParamsToString(r.url,r.params);return globalThis.wx?new Promise(function(e){wx.request({url:s,data:r.body,header:r.headers,method:n,dataType:"string",responseType:"text",fail:function(){e({url:s,method:n,status:-1,statusText:"NetworkError",body:""})},success:function(o){var a;e({url:s,method:n,status:o.statusCode,statusText:o.statusCode+"",headers:t({},o.header),body:"HEAD"===r.method?"":(a=o.data,"string"==typeof a?a:a instanceof ArrayBuffer&&"TextDecoder"in globalThis?(new TextDecoder).decode(a):JSON.stringify(a))})}})}):{url:s,method:n,status:-1,statusText:"NotSupport",body:"NotFound namespace of wx"}})}catch(e){return Promise.reject(e)}},f=/*#__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}(),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}(),m=/*#__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 f(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,s){if(r.ok&&!e.isEmpty(r.data)&&s){var o=e.getTypeGuard(s,"响应数据未能正确识别");return o.guard(r.data)||(console.error("ResponseCheckFaild",t,r.data),n.showMessage(!0,t+" "+o.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 s=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return s.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},r.get=function(e,t,r){try{var n,s=function(r){if(n)return r;var s=o.exec(e,a);o.cache.set(i,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var a=r.call(o,e,s,t||null);return n=1,a})}}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},r.post=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="POST",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.del=function(e,t,r){try{var n=this,s=Object.assign({},r||null);s.method="DELETE";var o=n.guard;return Promise.resolve(n.exec(e,s)).then(function(r){return o.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},r.put=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PUT",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.patch=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PATCH",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t}();function v(e){return new m(h,e)}var y=v(),p=y.setConfig,b=y.head,T=y.get,P=y.post,j=y.del,x=y.put;exports.NetRequest=v,exports.del=j,exports.get=T,exports.head=b,exports.post=P,exports.put=x,exports.setGlobalConfig=p;
|
package/dist/wx.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isJsonLike as e,parseJSON as t,isStringRecord as r,noop as n,sleep as s,addParamsToString as o,isEmpty as a,getTypeGuard as i,isFullURL as u,getFullURL as c}from"@seayoo-web/utils";function l(){return l=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},l.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 d="message";function f(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 s=r.value;if(s in e)return(o=e[s])?"string"==typeof o?o:JSON.stringify(o):""}var o;return""}var m=/<title>([^<]+)<\/title>/i,g=/<message>([^<]+)<\/message>/i;function v(e){var t=e.match(m);if(t)return t[1];var r=e.match(g);return r?r[1]:""}function y(e){return e>=200&&e<400}var b=function e(t,r,o,a,i){try{var u,c,l,h=i||0,d=Math.max(0,Math.min(10,null!=(u=null!=(c=null==a?void 0:a.maxRetry)?c:o.get("maxRetry"))?u:0)),f=null!=(l=null==a?void 0:a.retryResolve)?l:o.get("retryResolve"),m=o.get("logHandler")||n;m({type:"prepear",url:r,method:(null==a?void 0:a.method)||"GET",retry:h,maxRetry:d,message:0===h?"start":"retry "+h+"/"+d+" start",headers:null==a?void 0:a.headers,options:a});var g=Date.now();return Promise.resolve(t(r,o,a)).then(function(n){var i,u,c=n.status,l=Date.now()-g,v="[cost "+l+"]["+c+"] "+(c<0?n.body:"");m({type:"finished",url:r,method:n.method,retry:h,maxRetry:d,message:0===h?"finish "+v:"retry "+h+"/"+d+" finish "+v,response:n,headers:n.headers,cost:l});var b=y(c);if(!d||"network"===f&&c>0||"status"===f&&b||Array.isArray(f)&&!f.includes(c)||"function"==typeof f&&!0!==f(n,h)||h>=d)return n;var p=null!=(i=null!=(u=null==a?void 0:a.retryInterval)?u:o.get("retryInterval"))?i:1e3;return Promise.resolve(s(Math.max(100,"2EB"===p?1e3*Math.pow(2,h):"function"==typeof p?p(h+1)||0:p))).then(function(){return Promise.resolve(e(t,r,o,a,h+1))})})}catch(e){return Promise.reject(e)}};function p(e,t,r,n,s,o){var a=s.get("message"),i=!1!==a&&!1!==(null==o?void 0:o.message)&&((null==o?void 0:o.message)||a);return!1!==i&&s.showMessage(!e.ok,"function"==typeof i?i(e,r,n,t):t),e}var T=function(n,s,o){try{return Promise.resolve(b(P,n,s,o)).then(function(a){return function(n,s,o,a){var i,u;if(n.status<0)return p({ok:!1,status:n.status,code:n.statusText,headers:{},message:"",data:null},n.method+" "+s+" "+n.statusText,n.method,s,o,a);y(n.status)||null==(u=o.get("errorHandler"))||u(n.status,n.method,s);var c,h,m,g,b,T=l({},(c=n.status,h=n.statusText,m=n.body,g=o.get("responseRule"),b=(null==a?void 0:a.responseRule)||g,y(c)?function(n,s,o,a){var i=n||{resolve:"body"},u={ok:!0,code:o,message:"",data:null};if(202===s||204===s||!a)return u;if("body"===i.resolve)return u.data=e(a)?t(a):a,u;var c=t(a);if(!c||!r(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=i.statusField,h=i.statusOKValue||"",m=i.dataField||"data",g=i.messageField||d,v=i.ignoreMessage||"";if(l&&!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var y=l?c[l]+"":"";return u.ok=!l||y===h,u.code=y||o,u.data=!0===m?c:m in c?c[m]:null,u.message=f(c,g),v&&u.message&&(Array.isArray(v)&&v.includes(u.message)||"string"==typeof v&&u.message===v)&&(u.message=""),u}(b.ok||g.ok,c,h,m):function(n,s,o){var a=n||{resolve:"json",messageField:d},i={ok:!1,code:s,message:o,data:null};switch(a.resolve){case"body":i.message=v(o)||o;break;case"json":var u=function(n,s,o){if(void 0===o&&(o=d),!e(n))return{message:""};var a=t(n);return a&&r(a)?{code:s?f(a,s):"",message:f(a,o)||n}:{message:n}}(o,a.statusField,a.messageField),c=u.message;i.code=u.code||s,i.message=v(o)||c}return i}(b.failed||g.failed,h,m)),{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=o.get("responseHandler"))||i(l({},T),n.method,s),p(T,T.ok?T.message:n.method+" "+s+" ["+(T.code||n.statusText)+"] "+(T.message||n.statusText),n.method,s,o,a)}(a,n,s,o)})}catch(e){return Promise.reject(e)}},P=function(e,t,r){try{return Promise.resolve(function(e,t,r){try{var n=Object.assign({method:"GET"},r),s="FormData"in globalThis&&n.body instanceof FormData,o=s?"POST":n.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(s?{}:{"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 c=t.getFullUrl(e),l=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),h=n.timeout||t.get("timeout");return Promise.resolve(function(r){try{var n=function(n){var s;return r?n:Promise.resolve(null==(s=t.get("requestHandler"))?void 0:s(a,u,o,e))},s=t.get("requestTransformer"),i=function(){if(s)return Promise.resolve(s({headers:a,params:u,method:o,url:c,body:l})).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,s="string"==typeof e&&e?e:c;return null==(r=t.get("logHandler"))||r({type:"ready",url:s,method:o,headers:a,timeout:h,body:l}),{url:s,method:o,body:l,params:u,headers:a,timeout:h,abort:n.abort,credentials:n.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(e,t,r)).then(function(e){var t="PATCH"===e.method?"POST":e.method,r=o(e.url,e.params);return globalThis.wx?new Promise(function(n){wx.request({url:r,data:e.body,header:e.headers,method:t,dataType:"string",responseType:"text",fail:function(){n({url:r,method:t,status:-1,statusText:"NetworkError",body:""})},success:function(s){var o;n({url:r,method:t,status:s.statusCode,statusText:s.statusCode+"",headers:l({},s.header),body:"HEAD"===e.method?"":(o=s.data,"string"==typeof o?o:o instanceof ArrayBuffer&&"TextDecoder"in globalThis?(new TextDecoder).decode(o):JSON.stringify(o))})}})}):{url:r,method:t,status:-1,statusText:"NotSupport",body:"NotFound namespace of wx"}})}catch(e){return Promise.reject(e)}},j=/*#__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}(),x=/*#__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)&&!u(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("/")?c(e):c(e,this.config.baseURL)},t.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},e}(),w=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new x(t),this.agent=e,this.cache=new j(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&&!a(t.data)&&n){var s=i(n,"响应数据未能正确识别");return s.guard(t.data)||(console.error("ResponseCheckFaild",e,t.data),r.showMessage(!0,e+" "+s.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 s=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return s.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},t.get=function(e,t,r){try{var n,s=function(r){if(n)return r;var s=o.exec(e,a);o.cache.set(i,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var a=r.call(o,e,s,t||null);return n=1,a})}}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},t.post=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="POST",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.del=function(e,t,r){try{var n=this,s=Object.assign({},r||null);s.method="DELETE";var o=n.guard;return Promise.resolve(n.exec(e,s)).then(function(r){return o.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},t.put=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PUT",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PATCH",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function O(e){return new w(T,e)}var R=O(),A=R.setConfig,E=R.head,k=R.get,F=R.post,L=R.del,C=R.put;export{O as NetRequest,L as del,k as get,E as head,F as post,C as put,A as setGlobalConfig};
|
|
1
|
+
import{isJsonLike as e,parseJSON as t,isStringRecord as r,noop as n,sleep as s,addParamsToString as o,isEmpty as a,getTypeGuard as i,isFullURL as u,getFullURL as c}from"@seayoo-web/utils";function l(){return l=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},l.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 d="message";function f(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 s=r.value;if(s in e)return(o=e[s])?"string"==typeof o?o:JSON.stringify(o):""}var o;return""}var g=/<title>([^<]+)<\/title>/i,m=/<message>([^<]+)<\/message>/i;function v(e){var t=e.match(g);if(t)return t[1];var r=e.match(m);return r?r[1]:""}function y(e){return e>=200&&e<400}var b=function e(t,r,o,a,i){try{var u,c,l,h=i||0,d=Math.max(0,Math.min(10,null!=(u=null!=(c=null==a?void 0:a.maxRetry)?c:o.get("maxRetry"))?u:0)),f=null!=(l=null==a?void 0:a.retryResolve)?l:o.get("retryResolve"),g=o.get("logHandler")||n;g({type:"prepear",url:r,method:(null==a?void 0:a.method)||"GET",retry:h,maxRetry:d,message:0===h?"start":"retry "+h+"/"+d+" start",headers:null==a?void 0:a.headers,options:a});var m=Date.now();return Promise.resolve(t(r,o,a)).then(function(n){var i,u,c=n.status,l=Date.now()-m,v="[cost "+l+"]["+c+"] "+(c<0?n.body:"");g({type:"finished",url:r,method:n.method,retry:h,maxRetry:d,message:0===h?"finish "+v:"retry "+h+"/"+d+" finish "+v,response:n,headers:n.headers,cost:l});var b=y(c);if(!d||"network"===f&&c>0||"status"===f&&b||Array.isArray(f)&&!f.includes(c)||"function"==typeof f&&!0!==f(n,h)||h>=d)return n;var p=null!=(i=null!=(u=null==a?void 0:a.retryInterval)?u:o.get("retryInterval"))?i:1e3;return Promise.resolve(s(Math.max(100,"2EB"===p?1e3*Math.pow(2,h):"function"==typeof p?p(h+1)||0:p))).then(function(){return Promise.resolve(e(t,r,o,a,h+1))})})}catch(e){return Promise.reject(e)}};function p(e,t,r,n,s,o){var a=s.get("message"),i=!1!==a&&!1!==(null==o?void 0:o.message)&&((null==o?void 0:o.message)||a);if(!1!==i){var u="function"==typeof i?i(e,r,n,t):t;u instanceof Error?s.showMessage(!0,u.message):u&&"object"==typeof u&&"message"in u?s.showMessage(!1,u.message):s.showMessage(!e.ok,u)}return e}var T=function(n,s,o){try{return Promise.resolve(b(P,n,s,o)).then(function(a){return function(n,s,o,a){var i,u;if(n.status<0)return p({ok:!1,status:n.status,code:n.statusText,headers:{},message:"",data:null},n.method+" "+s+" "+n.statusText,n.method,s,o,a);y(n.status)||null==(u=o.get("errorHandler"))||u(n.status,n.method,s);var c,h,g,m,b,T=l({},(c=n.status,h=n.statusText,g=n.body,m=o.get("responseRule"),b=(null==a?void 0:a.responseRule)||m,y(c)?function(n,s,o,a){var i=n||{resolve:"body"},u={ok:!0,code:o,message:"",data:null};if(202===s||204===s||!a)return u;if("body"===i.resolve)return u.data=e(a)?t(a):a,u;var c=t(a);if(!c||!r(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=i.statusField,h=i.statusOKValue||"",g=i.dataField||"data",m=i.messageField||d,v=i.ignoreMessage||"";if(l&&!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var y=l?c[l]+"":"";return u.ok=!l||y===h,u.code=y||o,u.data=!0===g?c:g in c?c[g]:null,u.message=f(c,m),v&&u.message&&(Array.isArray(v)&&v.includes(u.message)||"string"==typeof v&&u.message===v)&&(u.message=""),u}(b.ok||m.ok,c,h,g):function(n,s,o){var a=n||{resolve:"json",messageField:d},i={ok:!1,code:s,message:o,data:null};switch(a.resolve){case"body":i.message=v(o)||o;break;case"json":var u=function(n,s,o){if(void 0===o&&(o=d),!e(n))return{message:""};var a=t(n);return a&&r(a)?{code:s?f(a,s):"",message:f(a,o)||n}:{message:n}}(o,a.statusField,a.messageField),c=u.message;i.code=u.code||s,i.message=v(o)||c}return i}(b.failed||m.failed,h,g)),{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=o.get("responseHandler"))||i(l({},T),n.method,s),p(T,T.ok?T.message:n.method+" "+s+" ["+(T.code||n.statusText)+"] "+(T.message||n.statusText),n.method,s,o,a)}(a,n,s,o)})}catch(e){return Promise.reject(e)}},P=function(e,t,r){try{return Promise.resolve(function(e,t,r){try{var n=Object.assign({method:"GET"},r),s="FormData"in globalThis&&n.body instanceof FormData,o=s?"POST":n.method;"GET"!==o&&"HEAD"!==o&&"DELETE"!==o||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var a=Object.assign(s?{}:{"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 c=t.getFullUrl(e),l=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),h=n.timeout||t.get("timeout");return Promise.resolve(function(r){try{var n=function(n){var s;return r?n:Promise.resolve(null==(s=t.get("requestHandler"))?void 0:s(a,u,o,e))},s=t.get("requestTransformer"),i=function(){if(s)return Promise.resolve(s({headers:a,params:u,method:o,url:c,body:l})).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,s="string"==typeof e&&e?e:c;return null==(r=t.get("logHandler"))||r({type:"ready",url:s,method:o,headers:a,timeout:h,body:l}),{url:s,method:o,body:l,params:u,headers:a,timeout:h,abort:n.abort,credentials:n.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(e,t,r)).then(function(e){var t="PATCH"===e.method?"POST":e.method,r=o(e.url,e.params);return globalThis.wx?new Promise(function(n){wx.request({url:r,data:e.body,header:e.headers,method:t,dataType:"string",responseType:"text",fail:function(){n({url:r,method:t,status:-1,statusText:"NetworkError",body:""})},success:function(s){var o;n({url:r,method:t,status:s.statusCode,statusText:s.statusCode+"",headers:l({},s.header),body:"HEAD"===e.method?"":(o=s.data,"string"==typeof o?o:o instanceof ArrayBuffer&&"TextDecoder"in globalThis?(new TextDecoder).decode(o):JSON.stringify(o))})}})}):{url:r,method:t,status:-1,statusText:"NotSupport",body:"NotFound namespace of wx"}})}catch(e){return Promise.reject(e)}},j=/*#__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}(),w=/*#__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)&&!u(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("/")?c(e):c(e,this.config.baseURL)},t.showMessage=function(e,t){this.config.messageHandler&&t&&this.config.messageHandler(e,t)},e}(),x=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new w(t),this.agent=e,this.cache=new j(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&&!a(t.data)&&n){var s=i(n,"响应数据未能正确识别");return s.guard(t.data)||(console.error("ResponseCheckFaild",e,t.data),r.showMessage(!0,e+" "+s.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 s=r.guard;return Promise.resolve(r.exec(e,n)).then(function(t){return s.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},t.get=function(e,t,r){try{var n,s=function(r){if(n)return r;var s=o.exec(e,a);o.cache.set(i,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,a=Object.assign({},r||null);a.method="GET";var i=o.cache.getKey(e,a.params),u=o.cache.get(i),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var a=r.call(o,e,s,t||null);return n=1,a})}}();return Promise.resolve(c&&c.then?c.then(s):s(c))}catch(e){return Promise.reject(e)}},t.post=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="POST",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.del=function(e,t,r){try{var n=this,s=Object.assign({},r||null);s.method="DELETE";var o=n.guard;return Promise.resolve(n.exec(e,s)).then(function(r){return o.call(n,e,r,t||null)})}catch(e){return Promise.reject(e)}},t.put=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PUT",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r,n){try{var s=this,o=Object.assign({},n||null);o.method="PATCH",o.body=t;var a=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return a.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function O(e){return new x(T,e)}var E=O(),R=E.setConfig,A=E.head,k=E.get,F=E.post,L=E.del,C=E.put;export{O as NetRequest,L as del,k as get,A as head,F as post,C as put,R as setGlobalConfig};
|