@seayoo-web/request 1.1.1 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -113,6 +113,8 @@ setConfig({ timeout: 5000 })
113
113
  1. 请求时传入的 url 为完整 url,即以 http:// 或 https:// 开头
114
114
  2. 请求时传入的 url 以 / 开头
115
115
 
116
+ > node 环境仅仅支持完整 url 地址
117
+
116
118
  ### credentials
117
119
 
118
120
  类型:"omit" | "same-origin" | "include"
@@ -354,7 +356,7 @@ type TypeGuardParam<T> = TypeGuard<T> | TypeGuardFn<T>
354
356
 
355
357
  ### get\<T\>(url: string, typeGard?: TypeGuardParam\<T\> | null, options?: IRequestOptions)
356
358
 
357
- - **url**: 请求的资源路径,如果需要跳过全局 baseURL 设置,可以传递完整 url 地址,或者以 / 开头
359
+ - **url**: 请求的资源路径,如果需要跳过全局 baseURL 设置,可以传递完整 url 地址,或者以 / 开头,node 环境仅仅支持完整 url 地址
358
360
  - **typeGuard**: 可选类型守卫,如果设置为 null,则返回的内容为 unkonwn,否则就是经过类型守卫检查后的类型化数据,推荐传递类型守卫
359
361
  - **options**: 可选请求配置参数
360
362
 
@@ -362,7 +364,7 @@ type TypeGuardParam<T> = TypeGuard<T> | TypeGuardFn<T>
362
364
 
363
365
  ### post(url: string, data: RequstBody, typeGard?: TypeGuardParam\<T\> | null, options?: IRequestOptions)
364
366
 
365
- - **url**: 请求的资源路径,如果需要跳过全局 baseURL 设置,可以传递完整 url 地址,或者以 / 开头
367
+ - **url**: 请求的资源路径,如果需要跳过全局 baseURL 设置,可以传递完整 url 地址,或者以 / 开头,node 环境仅仅支持完整 url 地址
366
368
  - **data**: 请求发送的数据,等同于 IRequestOptions.body
367
369
  - **typeGuard**: 可选类型守卫,如果设置为 null,则返回的内容为 unkonwn,否则就是经过类型守卫检查后的类型化数据,推荐传递类型守卫,除非对响应内容不关心(比如 httpStatus 为 204 或 202)
368
370
  - **options**: 可选请求配置参数
@@ -398,3 +400,53 @@ type TypeGuardParam<T> = TypeGuard<T> | TypeGuardFn<T>
398
400
  以 script 方式加载远程资源,并通过 var(全局变量)接收远程数据,必须提供类型守卫;
399
401
 
400
402
  > 通常情况下,并不推荐使用 jsonp 和 jsonx 来请求数据,跨域请求请优先使用后端 CORS 方案;
403
+
404
+ ## 更多示例
405
+
406
+ 使用 `form` 发送数据(所有数据均可以序列化为字符串)
407
+
408
+ ```typescript
409
+ const encodeFormData: string[]
410
+ for(const key in data) {
411
+ encodeFormData.push(`${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`);
412
+ }
413
+ // 需要手工指定Content-Type
414
+ const { ok, data } = await post(url, encodeFormData.join("&"), typeGuard, {
415
+ headers: {
416
+ "Content-Type": "application/x-www-form-urlencoded"
417
+ }
418
+ });
419
+ ```
420
+
421
+ 使用 `formData` 发送数据(可以含有二进制文件),如果是想要带进度的上传,可以使用 `upload` 方法
422
+
423
+ ```typescript
424
+ const formData = new FormData();
425
+ for(const key in data) {
426
+ formData.append(key, data[key]);
427
+ }
428
+ // 传递 FormData 实例时,无须手工指定 Content-Type
429
+ const { ok, data } = await post(url, formData, typeGuard);
430
+ ```
431
+
432
+ 修改默认的异常提示
433
+
434
+ ```typescript
435
+ setGlobalConfig({
436
+ message: function({ code, status }:IResponseResult, method: string, url: string, defaultMsg: string){
437
+ if(code === "NetworkError" || code === "Failed" || code === "Aborted") {
438
+ return "⚠️ 网络错误,请检查网络";
439
+ }
440
+ if(status === 404) {
441
+ return `${method} ${url} 接口未定义`;
442
+ }
443
+ if(status >= 500 && status <= 599) {
444
+ return "🚨 服务器错误,请稍候再试";
445
+ }
446
+ if(code === "Unknown") {
447
+ return `⛔ ${url} 出现未知错误,请稍候再试`;
448
+ }
449
+ return defaultMsg;
450
+ }
451
+ })
452
+ ```
@@ -1,4 +1,3 @@
1
- import type { IResponseResult } from "./type";
1
+ import type { IResponseResult, TypeGuardParam } from "./type";
2
2
  import type { RequestGlobalConfig } from "./config";
3
- import type { TypeGuard, TypeGuardFn } from "@seayoo-web/utils";
4
- export declare function checkTypedDataResult<T>(url: string, result: IResponseResult, config: RequestGlobalConfig, typeGard: TypeGuard<T> | TypeGuardFn<T> | null): IResponseResult<T | null>;
3
+ export declare function checkTypedDataResult<T>(url: string, result: IResponseResult, config: RequestGlobalConfig, typeGard: TypeGuardParam<T> | null): IResponseResult<T | null | unknown>;
@@ -1,6 +1,4 @@
1
- import type { TypeGuard, TypeGuardFn } from "@seayoo-web/utils";
2
- import type { IRequestOptions, IRequestGlobalConfig, NetRequestAgent, ResponseWithType, ResponseWithoutType } from "./type";
3
- type TypeGuardParam<T> = TypeGuard<T> | TypeGuardFn<T>;
1
+ import type { TypeGuardParam, IRequestOptions, IRequestGlobalConfig, NetRequestAgent, ResponseWithType, ResponseWithoutType } from "./type";
4
2
  type RequestBody = NonNullable<IRequestOptions["body"]>;
5
3
  /** 工具函数主类 */
6
4
  export declare class NetRequestHandler {
@@ -27,7 +25,7 @@ export declare class NetRequestHandler {
27
25
  /**
28
26
  * 发送一个 HEAD 请求,并且不处理响应 body
29
27
  */
30
- head(url: string, options?: IRequestOptions): ResponseWithType<null>;
28
+ head(url: string, options?: IRequestOptions): ResponseWithoutType;
31
29
  /**
32
30
  * 发送一个 GET 请求,请求自带 500ms 缓冲控制以应对并发场景
33
31
  */
@@ -1,4 +1,4 @@
1
- import type { MaybePromise } from "@seayoo-web/utils";
1
+ import type { MaybePromise, TypeGuard, TypeGuardFn } from "@seayoo-web/utils";
2
2
  import type { RequestGlobalConfig } from "./config";
3
3
  export type IBaseRequestBody = Blob | ArrayBuffer | FormData | URLSearchParams | string;
4
4
  /** 通用网络请求工具的基本配置 */
@@ -154,3 +154,4 @@ export type IRequestLog = {
154
154
  /** 请求响应的内容 */
155
155
  response: IRequestBaseResponse;
156
156
  });
157
+ export type TypeGuardParam<T> = TypeGuard<T> | TypeGuardFn<T>;
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,o=Object.assign({method:"GET"},r),a=o.body instanceof FormData,i=a?"POST":o.method;"GET"!==i&&"HEAD"!==i&&"DELETE"!==i||void 0!==o.body&&(console.warn("request body is invalid with method get, head, delete"),delete o.body);var u=Object.assign(a?{}:{"Content-Type":"application/json;charset=utf-8"},o.headers),c=o.params||{},l={};return Object.keys(c).forEach(function(e){var t;void 0!==c[e]&&(l[e]="string"==typeof(t=c[e])?t:Array.isArray(t)?t.join(","):t+"")}),Promise.resolve(null==(n=t.get("requestHandler"))?void 0:n(u,l,i,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:i,body:s(o.body),params:l,headers:u,timeout:o.timeout||t.get("timeout"),credentials:o.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}};function s(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var o=function(e,t,r){try{return Promise.resolve(n(e,t,r)).then(function(r){var n=new URL(t.getFullUrl(r.url||e)),s=r.params;s instanceof Object&&Object.keys(s).forEach(function(e){return n.searchParams.set(e,s[e])});var o=new AbortController,a=r.timeout>0?setTimeout(function(){return o.abort()},r.timeout):null,i=new Request(n,{method:r.method,headers:new Headers(r.headers),body:r.body,credentials:r.credentials,signal:r.timeout>0?o.signal:null,redirect:"follow"});return Promise.resolve(fetch(i).then(function(e){try{var t=function(e){return{url:u,method:i,status:a,statusText:o,headers:s,body:e}},s=Object.fromEntries(e.headers.entries()),o=e.statusText,a=e.status,i=r.method,u=n.toString();return Promise.resolve("HEAD"===r.method?t(""):Promise.resolve(e.text()).then(t))}catch(e){return Promise.reject(e)}}).catch(function(e){return{url:n.toString(),method:r.method,status:-1,statusText:"NetworkError",body:String(e)}}).finally(function(){null!==a&&clearTimeout(a)}))})}catch(e){return Promise.reject(e)}},a="data",i="message";function u(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 c=/<title>([^<]+)<\/title>/i,l=/<message>([^<]+)<\/message>/i;function d(e){var t=e.match(c);if(t)return t[1];var r=e.match(l);return r?r[1]:""}function h(e){return e>=200&&e<400}var f=function t(r,n,s,o,a){try{var i,u,c=a||0,l=Math.min(10,null!=(i=null==o?void 0:o.maxRetry)?i:s.get("maxRetry")),d=null!=(u=null==o?void 0:o.retryResolve)?u:s.get("retryResolve"),f=s.get("logHandler")||e.noop;f({type:"prepear",url:n,method:(null==o?void 0:o.method)||"GET",retry:c,maxRetry:l,message:0===c?"start":"retry "+c+"/"+l+" start",options:o});var m=Date.now();return Promise.resolve(r(n,s,o)).then(function(a){var i,u=a.status,g=Date.now()-m,v="[cost "+g+"]["+u+"] "+(u<0?a.body:"");f({type:"finished",url:n,method:a.method,retry:c,maxRetry:l,message:0===c?"finish "+v:"retry "+c+"/"+l+" finish "+v,response:a,cost:g});var p=h(u);if(!l||"network"===d&&u>0||"status"===d&&p||c>=l)return a;var y=null!=(i=null==o?void 0:o.retryInterval)?i:s.get("retryInterval");return Promise.resolve(e.sleep(Math.max(100,"function"==typeof y?y(c+1):y))).then(function(){return Promise.resolve(t(r,n,s,o,c+1))})})}catch(e){return Promise.reject(e)}};function m(r,n,s,o){var c,l;if(r.status<0)return g({ok:!1,status:r.status,code:r.statusText,headers:{},message:"",data:null},r.method+" "+n+" "+r.statusText,r.method,n,s,o);h(r.status)||null==(l=s.get("errorHandler"))||l(r.status,r.method,n);var f,m,v,p,y,b=t({},(f=r.status,m=r.statusText,v=r.body,p=s.get("responseRule"),y=(null==o?void 0:o.responseRule)||p,h(f)?function(t,r,n,s){var o=t||{resolve:"body"},c={ok:!0,code:n,message:"",data:null};if(202===r||204===r||!s)return c;if("body"===o.resolve)return c.data=e.isJsonLike(s)?e.parseJSON(s):s,c;var l=e.parseJSON(s);if(!l||!e.isStringRecord(l))return c.ok=!1,c.code="ResponseFormatError",c.message="响应内容无法格式化为 Object",c;var d=o.statusField,h=o.statusOKValue||"",f=o.dataField||a,m=o.messageField||i,g=o.ignoreMessage||"";if(d&&!(d in l))return c.ok=!1,c.code="ResponseFieldMissing",c.message="响应内容找不到状态字段 "+d,c;var v=d?l[d]+"":"";return c.ok=!d||v===h,c.code=v||n,c.data=f in l?l[f]:null,c.message=u(l,m),g&&c.message&&(Array.isArray(g)&&g.includes(c.message)||"string"==typeof g&&c.message===g)&&(c.message=""),c}(y.ok||p.ok,f,m,v):function(t,r,n){var s=t||{resolve:"json",messageField:i},o={ok:!1,code:r,message:n,data:null};switch(s.resolve){case"body":o.message=d(n)||n;break;case"json":o.message=d(n)||function(t,r){if(void 0===r&&(r=i),!e.isJsonLike(t))return"";var n=e.parseJSON(t);return n&&e.isStringRecord(n)&&u(n,r)||t}(n,s.messageField)}return o}(y.failed||p.failed,m,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==(c=s.get("responseHandler"))||c(t({},b),r.method,n),g(b,b.ok?b.message:r.method+" "+n+" ["+(b.code||r.statusText)+"] "+(b.message||r.statusText),r.method,n,s,o)}function g(e,t,r,n,s,o){return!1!==(null==o?void 0:o.message)&&s.showMessage(!e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,n,t):t),e}var v=/*#__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}(),p=function(r,s,o){try{return Promise.resolve(n(r,s,o)).then(function(n){var a=t({},n,{onUploadProgress:null==o?void 0:o.onUploadProgress}),i=a.method,u=a.onUploadProgress||function(){return 0},c=e.addParamsToString(s.getFullUrl(a.url||r),a.params);return Promise.resolve(new Promise(function(e){var t=1,n=0,s=new XMLHttpRequest;s.upload.addEventListener("progress",function(e){t=e.total,u({total:e.total,loaded:e.loaded})}),s.addEventListener("load",function(){n&&clearTimeout(n),u({loaded:t,total:t}),e({url:c,method:i,status:s.status,statusText:s.statusText,headers:y(s),body:"HEAD"===i?"":s.responseText})}),s.addEventListener("error",function(){n&&clearTimeout(n),e({url:c,method:i,status:-2,statusText:"Failed",body:"Request "+i+" "+r+" Failed"})}),s.addEventListener("abort",function(){n&&clearTimeout(n),e({url:c,method:i,status:-3,statusText:"Aborted",body:"Request "+i+" "+r+" Aborted"})}),Object.entries(a.headers).forEach(function(e){s.setRequestHeader(e[0],e[1])}),"include"===a.credentials&&(s.withCredentials=!0),s.open(i,c,!0),a.body&&s.send(a.body),a.timeout>0&&(n=setTimeout(function(){s.abort()},a.timeout))}))})}catch(e){return Promise.reject(e)}};function y(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(":"),s=n[0].trim();s&&(t[s]=(n[1]||"").trim())}}),t}var b=function(e,t,r){try{return Promise.resolve(f(o,e,t,r)).then(function(n){return m(n,e,t,r)})}catch(e){return Promise.reject(e)}},j=function(e,t,r){try{return Promise.resolve(f(p,e,t,r)).then(function(n){return m(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}(),w=/*#__PURE__*/function(){function t(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new v(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,s){if(r.ok&&!e.isEmpty(r.data)&&null!==s){var o=e.getTypeGuard(s,"响应数据未能正确识别");if(o.guard(r.data))return r;console.error("response type check faild",t,r.data),n.showMessage(!0,t+" "+o.message)}return r.data=null,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 T(e){return"fetch"in window?new w(b,e):new w(j,e)}var x=T(),R=x.setConfig,O=x.head,E=x.get,k=x.post,L=x.del,S=x.put,H=x.patch;exports.NetRequest=T,exports.del=L,exports.get=E,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||i)+" 作为错误消息")}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||a)+" 作为响应数据,读取 "+(n.messageField||i)+" 作为提示消息"),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 s=window;"callback"in n||(n.callback="jsonxData"+Math.random().toString(16).slice(2));var o=n.callback+"";if(!t)return Promise.resolve(null);var a=e.addParamsToString(t,n,!0);return Promise.resolve(new Promise(function(n){s[o]=function(e){if(o in window&&delete s[o],r(e))return e;console.warn("response type check faild",t,e),n(null)},e.loadJS(a).catch(function(){n(null),delete s[o]})}))}catch(e){return Promise.reject(e)}},exports.jsonx=function(t,r,n){void 0===n&&(n={});try{var s=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=s[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=H,exports.post=k,exports.put=S,exports.setGlobalConfig=R,exports.upload=function(e,r,n){try{return Promise.resolve(function(e,r,n,s){try{var o=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){o.append(t+"["+r+"]",String(e))}):o.append(t,String(r))}),i)o.append(u,i[u]);var c=new v(s);return Promise.resolve(p(e,c,t({},n,{method:"POST",body:o}))).then(function(t){return m(t,e,c,n)})}catch(e){return Promise.reject(e)}}(e,r,n,{baseURL:x.getConfig("baseURL"),logHandler:x.getConfig("logHandler"),errorHandler:x.getConfig("errorHandler"),requestHandler:x.getConfig("requestHandler"),messageHandler:x.getConfig("messageHandler"),responseHandler:x.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,o=Object.assign({method:"GET"},r),a=o.body instanceof FormData,i=a?"POST":o.method;"GET"!==i&&"HEAD"!==i&&"DELETE"!==i||void 0!==o.body&&(console.warn("request body is invalid with method get, head, delete"),delete o.body);var u=Object.assign(a?{}:{"Content-Type":"application/json;charset=utf-8"},o.headers),c=o.params||{},l={};return Object.keys(c).forEach(function(e){var t;void 0!==c[e]&&(l[e]="string"==typeof(t=c[e])?t:Array.isArray(t)?t.join(","):t+"")}),Promise.resolve(null==(n=t.get("requestHandler"))?void 0:n(u,l,i,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:i,body:s(o.body),params:l,headers:u,timeout:o.timeout||t.get("timeout"),credentials:o.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}};function s(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var o=function(e,t,r){try{return Promise.resolve(n(e,t,r)).then(function(r){var n=new URL(t.getFullUrl(r.url||e)),s=r.params;s instanceof Object&&Object.keys(s).forEach(function(e){return n.searchParams.set(e,s[e])});var o=new AbortController,a=r.timeout>0?setTimeout(function(){return o.abort()},r.timeout):null,i=new Request(n,{method:r.method,headers:new Headers(r.headers),body:r.body,credentials:r.credentials,signal:r.timeout>0?o.signal:null,redirect:"follow"});return Promise.resolve(fetch(i).then(function(e){try{var t=function(e){return{url:u,method:i,status:a,statusText:o,headers:s,body:e}},s=Object.fromEntries(e.headers.entries()),o=e.statusText,a=e.status,i=r.method,u=n.toString();return Promise.resolve("HEAD"===r.method?t(""):Promise.resolve(e.text()).then(t))}catch(e){return Promise.reject(e)}}).catch(function(e){return{url:n.toString(),method:r.method,status:-1,statusText:"NetworkError",body:String(e)}}).finally(function(){null!==a&&clearTimeout(a)}))})}catch(e){return Promise.reject(e)}},a="data",i="message";function u(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 c=/<title>([^<]+)<\/title>/i,l=/<message>([^<]+)<\/message>/i;function d(e){var t=e.match(c);if(t)return t[1];var r=e.match(l);return r?r[1]:""}function h(e){return e>=200&&e<400}var f=function t(r,n,s,o,a){try{var i,u,c=a||0,l=Math.min(10,null!=(i=null==o?void 0:o.maxRetry)?i:s.get("maxRetry")),d=null!=(u=null==o?void 0:o.retryResolve)?u:s.get("retryResolve"),f=s.get("logHandler")||e.noop;f({type:"prepear",url:n,method:(null==o?void 0:o.method)||"GET",retry:c,maxRetry:l,message:0===c?"start":"retry "+c+"/"+l+" start",options:o});var m=Date.now();return Promise.resolve(r(n,s,o)).then(function(a){var i,u=a.status,g=Date.now()-m,v="[cost "+g+"]["+u+"] "+(u<0?a.body:"");f({type:"finished",url:n,method:a.method,retry:c,maxRetry:l,message:0===c?"finish "+v:"retry "+c+"/"+l+" finish "+v,response:a,cost:g});var p=h(u);if(!l||"network"===d&&u>0||"status"===d&&p||c>=l)return a;var y=null!=(i=null==o?void 0:o.retryInterval)?i:s.get("retryInterval");return Promise.resolve(e.sleep(Math.max(100,"function"==typeof y?y(c+1):y))).then(function(){return Promise.resolve(t(r,n,s,o,c+1))})})}catch(e){return Promise.reject(e)}};function m(r,n,s,o){var c,l;if(r.status<0)return g({ok:!1,status:r.status,code:r.statusText,headers:{},message:"",data:null},r.method+" "+n+" "+r.statusText,r.method,n,s,o);h(r.status)||null==(l=s.get("errorHandler"))||l(r.status,r.method,n);var f,m,v,p,y,b=t({},(f=r.status,m=r.statusText,v=r.body,p=s.get("responseRule"),y=(null==o?void 0:o.responseRule)||p,h(f)?function(t,r,n,s){var o=t||{resolve:"body"},c={ok:!0,code:n,message:"",data:null};if(202===r||204===r||!s)return c;if("body"===o.resolve)return c.data=e.isJsonLike(s)?e.parseJSON(s):s,c;var l=e.parseJSON(s);if(!l||!e.isStringRecord(l))return c.ok=!1,c.code="ResponseFormatError",c.message="响应内容无法格式化为 Object",c;var d=o.statusField,h=o.statusOKValue||"",f=o.dataField||a,m=o.messageField||i,g=o.ignoreMessage||"";if(d&&!(d in l))return c.ok=!1,c.code="ResponseFieldMissing",c.message="响应内容找不到状态字段 "+d,c;var v=d?l[d]+"":"";return c.ok=!d||v===h,c.code=v||n,c.data=f in l?l[f]:null,c.message=u(l,m),g&&c.message&&(Array.isArray(g)&&g.includes(c.message)||"string"==typeof g&&c.message===g)&&(c.message=""),c}(y.ok||p.ok,f,m,v):function(t,r,n){var s=t||{resolve:"json",messageField:i},o={ok:!1,code:r,message:n,data:null};switch(s.resolve){case"body":o.message=d(n)||n;break;case"json":o.message=d(n)||function(t,r){if(void 0===r&&(r=i),!e.isJsonLike(t))return"";var n=e.parseJSON(t);return n&&e.isStringRecord(n)&&u(n,r)||t}(n,s.messageField)}return o}(y.failed||p.failed,m,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==(c=s.get("responseHandler"))||c(t({},b),r.method,n),g(b,b.ok?b.message:r.method+" "+n+" ["+(b.code||r.statusText)+"] "+(b.message||r.statusText),r.method,n,s,o)}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=/*#__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}(),p=function(r,s,o){try{return Promise.resolve(n(r,s,o)).then(function(n){var a=t({},n,{onUploadProgress:null==o?void 0:o.onUploadProgress}),i=a.method,u=a.onUploadProgress||e.noop,c=e.addParamsToString(s.getFullUrl(a.url||r),a.params);return Promise.resolve(new Promise(function(e){var t=1,n=0,s=new XMLHttpRequest;s.upload.addEventListener("progress",function(e){t=e.total,u({total:e.total,loaded:e.loaded})}),s.addEventListener("load",function(){n&&clearTimeout(n),u({loaded:t,total:t}),e({url:c,method:i,status:s.status,statusText:s.statusText,headers:y(s),body:"HEAD"===i?"":s.responseText})}),s.addEventListener("error",function(){n&&clearTimeout(n),e({url:c,method:i,status:-2,statusText:"Failed",body:"Request "+i+" "+r+" Failed"})}),s.addEventListener("abort",function(){n&&clearTimeout(n),e({url:c,method:i,status:-3,statusText:"Aborted",body:"Request "+i+" "+r+" Aborted"})}),Object.entries(a.headers).forEach(function(e){s.setRequestHeader(e[0],e[1])}),"include"===a.credentials&&(s.withCredentials=!0),s.open(i,c,!0),a.body&&s.send(a.body),a.timeout>0&&(n=setTimeout(function(){s.abort()},a.timeout))}))})}catch(e){return Promise.reject(e)}};function y(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(":"),s=n[0].trim();s&&(t[s]=(n[1]||"").trim())}}),t}var b=function(e,t,r){try{return Promise.resolve(f(o,e,t,r)).then(function(n){return m(n,e,t,r)})}catch(e){return Promise.reject(e)}},j=function(e,t,r){try{return Promise.resolve(f(p,e,t,r)).then(function(n){return m(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}(),w=/*#__PURE__*/function(){function t(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new v(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,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 T(e){return"fetch"in window?new w(b,e):new w(j,e)}var x=T(),R=x.setConfig,O=x.head,E=x.get,k=x.post,L=x.del,S=x.put,F=x.patch;exports.NetRequest=T,exports.del=L,exports.get=E,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||i)+" 作为错误消息")}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||a)+" 作为响应数据,读取 "+(n.messageField||i)+" 作为提示消息"),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 s=window;"callback"in n||(n.callback="jsonxData"+Math.random().toString(16).slice(2));var o=n.callback+"";if(!t)return Promise.resolve(null);var a=e.addParamsToString(t,n,!0);return Promise.resolve(new Promise(function(n){s[o]=function(e){if(o in window&&delete s[o],r(e))return e;console.warn("response type check faild",t,e),n(null)},e.loadJS(a).catch(function(){n(null),delete s[o]})}))}catch(e){return Promise.reject(e)}},exports.jsonx=function(t,r,n){void 0===n&&(n={});try{var s=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=s[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=F,exports.post=k,exports.put=S,exports.setGlobalConfig=R,exports.upload=function(e,r,n){try{return Promise.resolve(function(e,r,n,s){try{var o=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){o.append(t+"["+r+"]",String(e))}):o.append(t,String(r))}),i)o.append(u,i[u]);var c=new v(s);return Promise.resolve(p(e,c,t({},n,{method:"POST",body:o}))).then(function(t){return m(t,e,c,n)})}catch(e){return Promise.reject(e)}}(e,r,n,{baseURL:x.getConfig("baseURL"),logHandler:x.getConfig("logHandler"),errorHandler:x.getConfig("errorHandler"),requestHandler:x.getConfig("requestHandler"),messageHandler:x.getConfig("messageHandler"),responseHandler:x.getConfig("responseHandler")}))}catch(e){return Promise.reject(e)}};
package/dist/index.d.ts CHANGED
@@ -19,14 +19,14 @@ export declare const setGlobalConfig: (config: IRequestGlobalConfig) => void;
19
19
  /**
20
20
  * 发送一个 HEAD 请求
21
21
  */
22
- export declare const head: (url: string, options?: import("./inc/type").IRequestOptions | undefined) => import("./inc/type").ResponseWithType<null>;
22
+ export declare const head: (url: string, options?: import("./inc/type").IRequestOptions | undefined) => import("./inc/type").ResponseWithoutType;
23
23
  /**
24
24
  * 发送一个 GET 请求,请求自带 500ms 缓冲控制以应对并发场景,可选 typeGuard 用于检查数据类型
25
25
  */
26
26
  export declare const get: {
27
27
  (url: string): import("./inc/type").ResponseWithoutType;
28
28
  (url: string, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
29
- <T>(url: string, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
29
+ <T>(url: string, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
30
30
  };
31
31
  /**
32
32
  * 发送一个 POST 请求,可选 typeGuard 用于检查数据类型
@@ -34,7 +34,7 @@ export declare const get: {
34
34
  export declare const post: {
35
35
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
36
36
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
37
- <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
37
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
38
38
  };
39
39
  /**
40
40
  * 发送一个 DELETE 请求,可选 typeGuard 用于检查数据类型
@@ -42,7 +42,7 @@ export declare const post: {
42
42
  export declare const del: {
43
43
  (url: string): import("./inc/type").ResponseWithoutType;
44
44
  (url: string, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
45
- <T>(url: string, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
45
+ <T>(url: string, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
46
46
  };
47
47
  /**
48
48
  * 发送一个 PUT 请求,可选 typeGuard 用于检查数据类型
@@ -50,7 +50,7 @@ export declare const del: {
50
50
  export declare const put: {
51
51
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
52
52
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
53
- <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
53
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
54
54
  };
55
55
  /**
56
56
  * 发送一个 PATCH 请求,可选 typeGuard 用于检查数据类型
@@ -58,5 +58,5 @@ export declare const put: {
58
58
  export declare const patch: {
59
59
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
60
60
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
61
- <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
61
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
62
62
  };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{isJsonLike as e,parseJSON as t,isStringRecord as r,noop as n,sleep as s,isFullURL as o,getFullURL as a,addParamsToString as i,isEmpty as u,getTypeGuard as c,loadJS as l}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,s=Object.assign({method:"GET"},r),o=s.body instanceof FormData,a=o?"POST":s.method;"GET"!==a&&"HEAD"!==a&&"DELETE"!==a||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var i=Object.assign(o?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),u=s.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),Promise.resolve(null==(n=t.get("requestHandler"))?void 0:n(i,c,a,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:a,body:m(s.body),params:c,headers:i,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}};function m(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var g=function(e,t,r){try{return Promise.resolve(f(e,t,r)).then(function(r){var n=new URL(t.getFullUrl(r.url||e)),s=r.params;s instanceof Object&&Object.keys(s).forEach(function(e){return n.searchParams.set(e,s[e])});var o=new AbortController,a=r.timeout>0?setTimeout(function(){return o.abort()},r.timeout):null,i=new Request(n,{method:r.method,headers:new Headers(r.headers),body:r.body,credentials:r.credentials,signal:r.timeout>0?o.signal:null,redirect:"follow"});return Promise.resolve(fetch(i).then(function(e){try{var t=function(e){return{url:u,method:i,status:a,statusText:o,headers:s,body:e}},s=Object.fromEntries(e.headers.entries()),o=e.statusText,a=e.status,i=r.method,u=n.toString();return Promise.resolve("HEAD"===r.method?t(""):Promise.resolve(e.text()).then(t))}catch(e){return Promise.reject(e)}}).catch(function(e){return{url:n.toString(),method:r.method,status:-1,statusText:"NetworkError",body:String(e)}}).finally(function(){null!==a&&clearTimeout(a)}))})}catch(e){return Promise.reject(e)}},v="data",y="message",p=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||y)+" 作为错误消息")}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||v)+" 作为响应数据,读取 "+(n.messageField||y)+" 作为提示消息"),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 s=r.value;if(s in e)return(o=e[s])?"string"==typeof o?o:JSON.stringify(o):""}var o;return""}var j=/<title>([^<]+)<\/title>/i,P=/<message>([^<]+)<\/message>/i;function w(e){var t=e.match(j);if(t)return t[1];var r=e.match(P);return r?r[1]:""}function T(e){return e>=200&&e<400}var x=function e(t,r,o,a,i){try{var u,c,l=i||0,d=Math.min(10,null!=(u=null==a?void 0:a.maxRetry)?u:o.get("maxRetry")),h=null!=(c=null==a?void 0:a.retryResolve)?c:o.get("retryResolve"),f=o.get("logHandler")||n;f({type:"prepear",url:r,method:(null==a?void 0:a.method)||"GET",retry:l,maxRetry:d,message:0===l?"start":"retry "+l+"/"+d+" start",options:a});var m=Date.now();return Promise.resolve(t(r,o,a)).then(function(n){var i,u=n.status,c=Date.now()-m,g="[cost "+c+"]["+u+"] "+(u<0?n.body:"");f({type:"finished",url:r,method:n.method,retry:l,maxRetry:d,message:0===l?"finish "+g:"retry "+l+"/"+d+" finish "+g,response:n,cost:c});var v=T(u);if(!d||"network"===h&&u>0||"status"===h&&v||l>=d)return n;var y=null!=(i=null==a?void 0:a.retryInterval)?i:o.get("retryInterval");return Promise.resolve(s(Math.max(100,"function"==typeof y?y(l+1):y))).then(function(){return Promise.resolve(e(t,r,o,a,l+1))})})}catch(e){return Promise.reject(e)}};function O(n,s,o,a){var i,u;if(n.status<0)return E({ok:!1,status:n.status,code:n.statusText,headers:{},message:"",data:null},n.method+" "+s+" "+n.statusText,n.method,s,o,a);T(n.status)||null==(u=o.get("errorHandler"))||u(n.status,n.method,s);var c,l,h,f,m,g=d({},(c=n.status,l=n.statusText,h=n.body,f=o.get("responseRule"),m=(null==a?void 0:a.responseRule)||f,T(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,d=i.statusOKValue||"",h=i.dataField||v,f=i.messageField||y,m=i.ignoreMessage||"";if(l&&!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var g=l?c[l]+"":"";return u.ok=!l||g===d,u.code=g||o,u.data=h in c?c[h]:null,u.message=b(c,f),m&&u.message&&(Array.isArray(m)&&m.includes(u.message)||"string"==typeof m&&u.message===m)&&(u.message=""),u}(m.ok||f.ok,c,l,h):function(n,s,o){var a=n||{resolve:"json",messageField:y},i={ok:!1,code:s,message:o,data:null};switch(a.resolve){case"body":i.message=w(o)||o;break;case"json":i.message=w(o)||function(n,s){if(void 0===s&&(s=y),!e(n))return"";var o=t(n);return o&&r(o)&&b(o,s)||n}(o,a.messageField)}return i}(m.failed||f.failed,l,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=o.get("responseHandler"))||i(d({},g),n.method,s),E(g,g.ok?g.message:n.method+" "+s+" ["+(g.code||n.statusText)+"] "+(g.message||n.statusText),n.method,s,o,a)}function E(e,t,r,n,s,o){return!1!==(null==o?void 0:o.message)&&s.showMessage(!e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,n,t):t),e}var R=/*#__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)&&!o(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}(),k=function(e,t,r){try{return Promise.resolve(f(e,t,r)).then(function(n){var s=d({},n,{onUploadProgress:null==r?void 0:r.onUploadProgress}),o=s.method,a=s.onUploadProgress||function(){return 0},u=i(t.getFullUrl(s.url||e),s.params);return Promise.resolve(new Promise(function(t){var r=1,n=0,i=new XMLHttpRequest;i.upload.addEventListener("progress",function(e){r=e.total,a({total:e.total,loaded:e.loaded})}),i.addEventListener("load",function(){n&&clearTimeout(n),a({loaded:r,total:r}),t({url:u,method:o,status:i.status,statusText:i.statusText,headers:H(i),body:"HEAD"===o?"":i.responseText})}),i.addEventListener("error",function(){n&&clearTimeout(n),t({url:u,method:o,status:-2,statusText:"Failed",body:"Request "+o+" "+e+" Failed"})}),i.addEventListener("abort",function(){n&&clearTimeout(n),t({url:u,method:o,status:-3,statusText:"Aborted",body:"Request "+o+" "+e+" Aborted"})}),Object.entries(s.headers).forEach(function(e){i.setRequestHeader(e[0],e[1])}),"include"===s.credentials&&(i.withCredentials=!0),i.open(o,u,!0),s.body&&i.send(s.body),s.timeout>0&&(n=setTimeout(function(){i.abort()},s.timeout))}))})}catch(e){return Promise.reject(e)}};function H(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(":"),s=n[0].trim();s&&(t[s]=(n[1]||"").trim())}}),t}var A=function(e,t,r){try{return Promise.resolve(x(g,e,t,r)).then(function(n){return O(n,e,t,r)})}catch(e){return Promise.reject(e)}},L=function(e,t,r){try{return Promise.resolve(x(k,e,t,r)).then(function(n){return O(n,e,t,r)})}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}(),C=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new R(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 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)&&null!==n){var s=c(n,"响应数据未能正确识别");if(s.guard(t.data))return t;console.error("response type check faild",e,t.data),r.showMessage(!0,e+" "+s.message)}return t.data=null,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}(),U=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?l(i(e,r,!0)).then(function(){var s=n[r.var+""];return t(s)?s:(console.warn("response type check faild",e,s),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 s=r.callback+"";if(!e)return Promise.resolve(null);var o=i(e,r,!0);return Promise.resolve(new Promise(function(r){n[s]=function(o){if(s in window&&delete n[s],t(o))return o;console.warn("response type check faild",e,o),r(null)},l(o).catch(function(){r(null),delete n[s]})}))}catch(e){return Promise.reject(e)}},D=function(e,t,r){try{return Promise.resolve(function(e,t,r,n){try{var s=new FormData,o=null==r?void 0:r.body,a=d({},t);for(var i in o instanceof Object&&Object.entries(o).forEach(function(e){var t=e[0],r=e[1];r instanceof Blob?a[t]=r:Array.isArray(r)?r.forEach(function(e,r){s.append(t+"["+r+"]",String(e))}):s.append(t,String(r))}),a)s.append(i,a[i]);var u=new R(n);return Promise.resolve(k(e,u,d({},r,{method:"POST",body:s}))).then(function(t){return O(t,e,u,r)})}catch(e){return Promise.reject(e)}}(e,t,r,{baseURL:q.getConfig("baseURL"),logHandler:q.getConfig("logHandler"),errorHandler:q.getConfig("errorHandler"),requestHandler:q.getConfig("requestHandler"),messageHandler:q.getConfig("messageHandler"),responseHandler:q.getConfig("responseHandler")}))}catch(e){return Promise.reject(e)}};function M(e){return"fetch"in window?new C(A,e):new C(L,e)}var q=M(),I=q.setConfig,B=q.head,G=q.get,K=q.post,N=q.del,J=q.put,V=q.patch;export{M as NetRequest,N as del,G as get,p as getResponseRulesDescription,B as head,S as jsonp,U as jsonx,V as patch,K as post,J as put,I as setGlobalConfig,D as upload};
1
+ import{isJsonLike as e,parseJSON as t,isStringRecord as r,noop as n,sleep as s,isFullURL as o,getFullURL as a,addParamsToString as i,isEmpty as u,getTypeGuard as c,loadJS as l}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,s=Object.assign({method:"GET"},r),o=s.body instanceof FormData,a=o?"POST":s.method;"GET"!==a&&"HEAD"!==a&&"DELETE"!==a||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var i=Object.assign(o?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),u=s.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),Promise.resolve(null==(n=t.get("requestHandler"))?void 0:n(i,c,a,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:a,body:m(s.body),params:c,headers:i,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}};function m(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var g=function(e,t,r){try{return Promise.resolve(f(e,t,r)).then(function(r){var n=new URL(t.getFullUrl(r.url||e)),s=r.params;s instanceof Object&&Object.keys(s).forEach(function(e){return n.searchParams.set(e,s[e])});var o=new AbortController,a=r.timeout>0?setTimeout(function(){return o.abort()},r.timeout):null,i=new Request(n,{method:r.method,headers:new Headers(r.headers),body:r.body,credentials:r.credentials,signal:r.timeout>0?o.signal:null,redirect:"follow"});return Promise.resolve(fetch(i).then(function(e){try{var t=function(e){return{url:u,method:i,status:a,statusText:o,headers:s,body:e}},s=Object.fromEntries(e.headers.entries()),o=e.statusText,a=e.status,i=r.method,u=n.toString();return Promise.resolve("HEAD"===r.method?t(""):Promise.resolve(e.text()).then(t))}catch(e){return Promise.reject(e)}}).catch(function(e){return{url:n.toString(),method:r.method,status:-1,statusText:"NetworkError",body:String(e)}}).finally(function(){null!==a&&clearTimeout(a)}))})}catch(e){return Promise.reject(e)}},v="data",y="message",p=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||y)+" 作为错误消息")}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||v)+" 作为响应数据,读取 "+(n.messageField||y)+" 作为提示消息"),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 s=r.value;if(s in e)return(o=e[s])?"string"==typeof o?o:JSON.stringify(o):""}var o;return""}var j=/<title>([^<]+)<\/title>/i,P=/<message>([^<]+)<\/message>/i;function w(e){var t=e.match(j);if(t)return t[1];var r=e.match(P);return r?r[1]:""}function T(e){return e>=200&&e<400}var x=function e(t,r,o,a,i){try{var u,c,l=i||0,d=Math.min(10,null!=(u=null==a?void 0:a.maxRetry)?u:o.get("maxRetry")),h=null!=(c=null==a?void 0:a.retryResolve)?c:o.get("retryResolve"),f=o.get("logHandler")||n;f({type:"prepear",url:r,method:(null==a?void 0:a.method)||"GET",retry:l,maxRetry:d,message:0===l?"start":"retry "+l+"/"+d+" start",options:a});var m=Date.now();return Promise.resolve(t(r,o,a)).then(function(n){var i,u=n.status,c=Date.now()-m,g="[cost "+c+"]["+u+"] "+(u<0?n.body:"");f({type:"finished",url:r,method:n.method,retry:l,maxRetry:d,message:0===l?"finish "+g:"retry "+l+"/"+d+" finish "+g,response:n,cost:c});var v=T(u);if(!d||"network"===h&&u>0||"status"===h&&v||l>=d)return n;var y=null!=(i=null==a?void 0:a.retryInterval)?i:o.get("retryInterval");return Promise.resolve(s(Math.max(100,"function"==typeof y?y(l+1):y))).then(function(){return Promise.resolve(e(t,r,o,a,l+1))})})}catch(e){return Promise.reject(e)}};function O(n,s,o,a){var i,u;if(n.status<0)return E({ok:!1,status:n.status,code:n.statusText,headers:{},message:"",data:null},n.method+" "+s+" "+n.statusText,n.method,s,o,a);T(n.status)||null==(u=o.get("errorHandler"))||u(n.status,n.method,s);var c,l,h,f,m,g=d({},(c=n.status,l=n.statusText,h=n.body,f=o.get("responseRule"),m=(null==a?void 0:a.responseRule)||f,T(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,d=i.statusOKValue||"",h=i.dataField||v,f=i.messageField||y,m=i.ignoreMessage||"";if(l&&!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var g=l?c[l]+"":"";return u.ok=!l||g===d,u.code=g||o,u.data=h in c?c[h]:null,u.message=b(c,f),m&&u.message&&(Array.isArray(m)&&m.includes(u.message)||"string"==typeof m&&u.message===m)&&(u.message=""),u}(m.ok||f.ok,c,l,h):function(n,s,o){var a=n||{resolve:"json",messageField:y},i={ok:!1,code:s,message:o,data:null};switch(a.resolve){case"body":i.message=w(o)||o;break;case"json":i.message=w(o)||function(n,s){if(void 0===s&&(s=y),!e(n))return"";var o=t(n);return o&&r(o)&&b(o,s)||n}(o,a.messageField)}return i}(m.failed||f.failed,l,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=o.get("responseHandler"))||i(d({},g),n.method,s),E(g,g.ok?g.message:n.method+" "+s+" ["+(g.code||n.statusText)+"] "+(g.message||n.statusText),n.method,s,o,a)}function E(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 R=/*#__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)&&!o(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}(),k=function(e,t,r){try{return Promise.resolve(f(e,t,r)).then(function(s){var o=d({},s,{onUploadProgress:null==r?void 0:r.onUploadProgress}),a=o.method,u=o.onUploadProgress||n,c=i(t.getFullUrl(o.url||e),o.params);return Promise.resolve(new Promise(function(t){var r=1,n=0,s=new XMLHttpRequest;s.upload.addEventListener("progress",function(e){r=e.total,u({total:e.total,loaded:e.loaded})}),s.addEventListener("load",function(){n&&clearTimeout(n),u({loaded:r,total:r}),t({url:c,method:a,status:s.status,statusText:s.statusText,headers:H(s),body:"HEAD"===a?"":s.responseText})}),s.addEventListener("error",function(){n&&clearTimeout(n),t({url:c,method:a,status:-2,statusText:"Failed",body:"Request "+a+" "+e+" Failed"})}),s.addEventListener("abort",function(){n&&clearTimeout(n),t({url:c,method:a,status:-3,statusText:"Aborted",body:"Request "+a+" "+e+" Aborted"})}),Object.entries(o.headers).forEach(function(e){s.setRequestHeader(e[0],e[1])}),"include"===o.credentials&&(s.withCredentials=!0),s.open(a,c,!0),o.body&&s.send(o.body),o.timeout>0&&(n=setTimeout(function(){s.abort()},o.timeout))}))})}catch(e){return Promise.reject(e)}};function H(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(":"),s=n[0].trim();s&&(t[s]=(n[1]||"").trim())}}),t}var A=function(e,t,r){try{return Promise.resolve(x(g,e,t,r)).then(function(n){return O(n,e,t,r)})}catch(e){return Promise.reject(e)}},L=function(e,t,r){try{return Promise.resolve(x(k,e,t,r)).then(function(n){return O(n,e,t,r)})}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}(),C=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new R(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 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}(),U=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?l(i(e,r,!0)).then(function(){var s=n[r.var+""];return t(s)?s:(console.warn("response type check faild",e,s),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 s=r.callback+"";if(!e)return Promise.resolve(null);var o=i(e,r,!0);return Promise.resolve(new Promise(function(r){n[s]=function(o){if(s in window&&delete n[s],t(o))return o;console.warn("response type check faild",e,o),r(null)},l(o).catch(function(){r(null),delete n[s]})}))}catch(e){return Promise.reject(e)}},D=function(e,t,r){try{return Promise.resolve(function(e,t,r,n){try{var s=new FormData,o=null==r?void 0:r.body,a=d({},t);for(var i in o instanceof Object&&Object.entries(o).forEach(function(e){var t=e[0],r=e[1];r instanceof Blob?a[t]=r:Array.isArray(r)?r.forEach(function(e,r){s.append(t+"["+r+"]",String(e))}):s.append(t,String(r))}),a)s.append(i,a[i]);var u=new R(n);return Promise.resolve(k(e,u,d({},r,{method:"POST",body:s}))).then(function(t){return O(t,e,u,r)})}catch(e){return Promise.reject(e)}}(e,t,r,{baseURL:q.getConfig("baseURL"),logHandler:q.getConfig("logHandler"),errorHandler:q.getConfig("errorHandler"),requestHandler:q.getConfig("requestHandler"),messageHandler:q.getConfig("messageHandler"),responseHandler:q.getConfig("responseHandler")}))}catch(e){return Promise.reject(e)}};function M(e){return"fetch"in window?new C(A,e):new C(L,e)}var q=M(),I=q.setConfig,B=q.head,G=q.get,K=q.post,N=q.del,J=q.put,V=q.patch;export{M as NetRequest,N as del,G as get,p as getResponseRulesDescription,B as head,S as jsonp,U as jsonx,V as patch,K as post,J as put,I as setGlobalConfig,D 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 g=function e(t,n,s,o,a){try{var i,u,c=a||0,l=Math.min(10,null!=(i=null==o?void 0:o.maxRetry)?i:s.get("maxRetry")),h=null!=(u=null==o?void 0:o.retryResolve)?u:s.get("retryResolve"),d=s.get("logHandler")||r.noop;d({type:"prepear",url:n,method:(null==o?void 0:o.method)||"GET",retry:c,maxRetry:l,message:0===c?"start":"retry "+c+"/"+l+" start",options:o});var g=Date.now();return Promise.resolve(t(n,s,o)).then(function(a){var i,u=a.status,m=Date.now()-g,v="[cost "+m+"]["+u+"] "+(u<0?a.body:"");d({type:"finished",url:n,method:a.method,retry:c,maxRetry:l,message:0===c?"finish "+v:"retry "+c+"/"+l+" finish "+v,response:a,cost:m});var y=f(u);if(!l||"network"===h&&u>0||"status"===h&&y||c>=l)return a;var p=null!=(i=null==o?void 0:o.retryInterval)?i:s.get("retryInterval");return Promise.resolve(r.sleep(Math.max(100,"function"==typeof p?p(c+1):p))).then(function(){return Promise.resolve(e(t,n,s,o,c+1))})})}catch(e){return Promise.reject(e)}};function m(e,t,r,n,s,o){return!1!==(null==o?void 0:o.message)&&s.showMessage(!e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,n,t):t),e}function v(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var y=function(e,t,n){try{return Promise.resolve(g(p,e,t,n)).then(function(s){return function(e,t,n,s){var o,i;if(e.status<0)return m({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,g,v,y,p=a({},(l=e.status,h=e.statusText,g=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,g=o.ignoreMessage||"";if(l&&!(l in i))return a.ok=!1,a.code="ResponseFieldMissing",a.message="响应内容找不到状态字段 "+l,a;var m=l?i[l]+"":"";return a.ok=!l||m===h,a.code=m||n,a.data=d in i?i[d]:null,a.message=c(i,f),g&&a.message&&(Array.isArray(g)&&g.includes(a.message)||"string"==typeof g&&a.message===g)&&(a.message=""),a}(y.ok||v.ok,l,h,g):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":o.message=d(n)||function(e,t){if(void 0===t&&(t=u),!r.isJsonLike(e))return"";var n=r.parseJSON(e);return n&&r.isStringRecord(n)&&c(n,t)||e}(n,s.messageField)}return o}(y.failed||v.failed,h,g)),{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),m(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)}},p=function(e,t,n){try{return Promise.resolve(function(e,t,r){try{var n,s=Object.assign({method:"GET"},r),o=s.body instanceof FormData,a=o?"POST":s.method;"GET"!==a&&"HEAD"!==a&&"DELETE"!==a||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var i=Object.assign(o?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),u=s.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),Promise.resolve(null==(n=t.get("requestHandler"))?void 0:n(i,c,a,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:a,body:v(s.body),params:c,headers:i,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(e,t,n)).then(function(t){var n=t.url||e;if(!r.isFullURL(n))return{url:n,method:t.method,status:-2,statusText:"URLFormatError",headers:{},body:""};var a=/^https:\/\//i.test(n)?o.default:s.default,i=new URL(n),u=t.params;u instanceof Object&&Object.keys(u).forEach(function(e){return i.searchParams.set(e,u[e])});var c="HEAD"===t.method;return new Promise(function(e){var r=a.request(i,{headers:t.headers,method:t.method,timeout:t.timeout>0?t.timeout:void 0},function(r){var n=[];c||r.on("data",function(e){return n.push(e)}),r.on("end",function(){var s=Object.fromEntries(Object.entries(r.headers).map(function(e){var t=e[1];return[e[0].toLowerCase(),Array.isArray(t)?t.join(","):t]}));e({url:i.toString(),method:t.method,status:r.statusCode||-3,statusText:r.statusMessage||"Unknown",headers:s,body:c?"":Buffer.concat(n).toString("utf-8")})})});r.on("error",function(r){e({url:i.toString(),method:t.method,status:-1,statusText:r.name||"Unknown",body:r.message})}),t.body&&r.write(t.body),r.end()})})}catch(e){return Promise.reject(e)}},b=/*#__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 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}(),P=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new j(t),this.agent=e,this.cache=new b(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)&&null!==s){var o=r.getTypeGuard(s,"响应数据未能正确识别");if(o.guard(t.data))return t;console.error("response type check faild",e,t.data),n.showMessage(!0,e+" "+o.message)}return t.data=null,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 x(e){return new P(y,e)}var O=x(),T=O.setConfig,w=O.head,R=O.get,L=O.post,k=O.del,E=O.put,A=O.patch;exports.NetRequest=x,exports.del=k,exports.get=R,exports.head=w,exports.patch=A,exports.post=L,exports.put=E,exports.setGlobalConfig=T;
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 g=function e(t,n,s,o,a){try{var i,u,c=a||0,l=Math.min(10,null!=(i=null==o?void 0:o.maxRetry)?i:s.get("maxRetry")),h=null!=(u=null==o?void 0:o.retryResolve)?u:s.get("retryResolve"),d=s.get("logHandler")||r.noop;d({type:"prepear",url:n,method:(null==o?void 0:o.method)||"GET",retry:c,maxRetry:l,message:0===c?"start":"retry "+c+"/"+l+" start",options:o});var g=Date.now();return Promise.resolve(t(n,s,o)).then(function(a){var i,u=a.status,m=Date.now()-g,v="[cost "+m+"]["+u+"] "+(u<0?a.body:"");d({type:"finished",url:n,method:a.method,retry:c,maxRetry:l,message:0===c?"finish "+v:"retry "+c+"/"+l+" finish "+v,response:a,cost:m});var y=f(u);if(!l||"network"===h&&u>0||"status"===h&&y||c>=l)return a;var p=null!=(i=null==o?void 0:o.retryInterval)?i:s.get("retryInterval");return Promise.resolve(r.sleep(Math.max(100,"function"==typeof p?p(c+1):p))).then(function(){return Promise.resolve(e(t,n,s,o,c+1))})})}catch(e){return Promise.reject(e)}};function m(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}function v(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var y=function(e,t,n){try{return Promise.resolve(g(p,e,t,n)).then(function(s){return function(e,t,n,s){var o,i;if(e.status<0)return m({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,g,v,y,p=a({},(l=e.status,h=e.statusText,g=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,g=o.ignoreMessage||"";if(l&&!(l in i))return a.ok=!1,a.code="ResponseFieldMissing",a.message="响应内容找不到状态字段 "+l,a;var m=l?i[l]+"":"";return a.ok=!l||m===h,a.code=m||n,a.data=d in i?i[d]:null,a.message=c(i,f),g&&a.message&&(Array.isArray(g)&&g.includes(a.message)||"string"==typeof g&&a.message===g)&&(a.message=""),a}(y.ok||v.ok,l,h,g):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":o.message=d(n)||function(e,t){if(void 0===t&&(t=u),!r.isJsonLike(e))return"";var n=r.parseJSON(e);return n&&r.isStringRecord(n)&&c(n,t)||e}(n,s.messageField)}return o}(y.failed||v.failed,h,g)),{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),m(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)}},p=function(e,t,n){try{return Promise.resolve(function(e,t,r){try{var n,s=Object.assign({method:"GET"},r),o=s.body instanceof FormData,a=o?"POST":s.method;"GET"!==a&&"HEAD"!==a&&"DELETE"!==a||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var i=Object.assign(o?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),u=s.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),Promise.resolve(null==(n=t.get("requestHandler"))?void 0:n(i,c,a,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:a,body:v(s.body),params:c,headers:i,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(e,t,n)).then(function(n){var a=t.getFullUrl(n.url||e);if(!r.isFullURL(a))return{url:a,method:n.method,status:-2,statusText:"URLFormatError",headers:{},body:""};var i=/^https:\/\//i.test(a)?o.default:s.default,u=new URL(a),c=n.params;c instanceof Object&&Object.keys(c).forEach(function(e){return u.searchParams.set(e,c[e])});var l="HEAD"===n.method;return new Promise(function(e){var t=i.request(u,{headers:n.headers,method:n.method,timeout:n.timeout>0?n.timeout:void 0},function(t){var r=[];l||t.on("data",function(e){return r.push(e)}),t.on("end",function(){var s=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:u.toString(),method:n.method,status:t.statusCode||-3,statusText:t.statusMessage||"Unknown",headers:s,body:l?"":Buffer.concat(r).toString("utf-8")})})});t.on("error",function(t){e({url:u.toString(),method:n.method,status:-1,statusText:t.name||"Unknown",body:t.message})}),n.body&&t.write(n.body),t.end()})})}catch(e){return Promise.reject(e)}},b=/*#__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 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}(),P=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new j(t),this.agent=e,this.cache=new b(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 x(e){return new P(y,e)}var O=x(),R=O.setConfig,T=O.head,w=O.get,L=O.post,k=O.del,E=O.put,U=O.patch;exports.NetRequest=x,exports.del=k,exports.get=w,exports.head=T,exports.patch=U,exports.post=L,exports.put=E,exports.setGlobalConfig=R;
package/dist/node.d.ts CHANGED
@@ -12,14 +12,14 @@ export declare const setGlobalConfig: (config: IRequestGlobalConfig) => void;
12
12
  /**
13
13
  * 发送一个 HEAD 请求
14
14
  */
15
- export declare const head: (url: string, options?: import("./inc/type").IRequestOptions | undefined) => import("./inc/type").ResponseWithType<null>;
15
+ export declare const head: (url: string, options?: import("./inc/type").IRequestOptions | undefined) => import("./inc/type").ResponseWithoutType;
16
16
  /**
17
17
  * 发送一个 GET 请求,请求自带 500ms 缓冲控制以应对并发场景,可选 typeGuard 用于检查数据类型
18
18
  */
19
19
  export declare const get: {
20
20
  (url: string): import("./inc/type").ResponseWithoutType;
21
21
  (url: string, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
22
- <T>(url: string, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
22
+ <T>(url: string, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
23
23
  };
24
24
  /**
25
25
  * 发送一个 POST 请求,可选 typeGuard 用于检查数据类型
@@ -27,7 +27,7 @@ export declare const get: {
27
27
  export declare const post: {
28
28
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
29
29
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
30
- <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
30
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
31
31
  };
32
32
  /**
33
33
  * 发送一个 DELETE 请求,可选 typeGuard 用于检查数据类型
@@ -35,7 +35,7 @@ export declare const post: {
35
35
  export declare const del: {
36
36
  (url: string): import("./inc/type").ResponseWithoutType;
37
37
  (url: string, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
38
- <T>(url: string, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
38
+ <T>(url: string, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
39
39
  };
40
40
  /**
41
41
  * 发送一个 PUT 请求,可选 typeGuard 用于检查数据类型
@@ -43,7 +43,7 @@ export declare const del: {
43
43
  export declare const put: {
44
44
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
45
45
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
46
- <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
46
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
47
47
  };
48
48
  /**
49
49
  * 发送一个 PATCH 请求,可选 typeGuard 用于检查数据类型
@@ -51,5 +51,5 @@ export declare const put: {
51
51
  export declare const patch: {
52
52
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
53
53
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
54
- <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
54
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
55
55
  };
package/dist/node.mjs 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 p(e){return e>=200&&e<400}var b=function e(t,r,n,s,i){try{var u,c,l=i||0,h=Math.min(10,null!=(u=null==s?void 0:s.maxRetry)?u:n.get("maxRetry")),d=null!=(c=null==s?void 0:s.retryResolve)?c:n.get("retryResolve"),f=n.get("logHandler")||o;f({type:"prepear",url:r,method:(null==s?void 0:s.method)||"GET",retry:l,maxRetry:h,message:0===l?"start":"retry "+l+"/"+h+" start",options:s});var m=Date.now();return Promise.resolve(t(r,n,s)).then(function(o){var i,u=o.status,c=Date.now()-m,g="[cost "+c+"]["+u+"] "+(u<0?o.body:"");f({type:"finished",url:r,method:o.method,retry:l,maxRetry:h,message:0===l?"finish "+g:"retry "+l+"/"+h+" finish "+g,response:o,cost:c});var v=p(u);if(!h||"network"===d&&u>0||"status"===d&&v||l>=h)return o;var y=null!=(i=null==s?void 0:s.retryInterval)?i:n.get("retryInterval");return Promise.resolve(a(Math.max(100,"function"==typeof y?y(l+1):y))).then(function(){return Promise.resolve(e(t,r,n,s,l+1))})})}catch(e){return Promise.reject(e)}};function j(e,t,r,n,s,o){return!1!==(null==o?void 0:o.message)&&s.showMessage(!e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,n,t):t),e}function P(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var w=function(e,t,o){try{return Promise.resolve(b(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);p(e.status)||null==(u=o.get("errorHandler"))||u(e.status,e.method,t);var c,l,d,g,v,b=h({},(c=e.status,l=e.statusText,d=e.body,g=o.get("responseRule"),v=(null==a?void 0:a.responseRule)||g,p(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=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":i.message=y(o)||function(e,t){if(void 0===t&&(t=f),!r(e))return"";var o=n(e);return o&&s(o)&&m(o,t)||e}(o,a.messageField)}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({},b),e.method,t),j(b,b.ok?b.message:e.method+" "+t+" ["+(b.code||e.statusText)+"] "+(b.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,s=Object.assign({method:"GET"},r),o=s.body instanceof FormData,a=o?"POST":s.method;"GET"!==a&&"HEAD"!==a&&"DELETE"!==a||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var i=Object.assign(o?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),u=s.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),Promise.resolve(null==(n=t.get("requestHandler"))?void 0:n(i,c,a,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:a,body:P(s.body),params:c,headers:i,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(r,n,s)).then(function(n){var s=n.url||r;if(!i(s))return{url:s,method:n.method,status:-2,statusText:"URLFormatError",headers:{},body:""};var o=/^https:\/\//i.test(s)?t:e,a=new URL(s),u=n.params;u instanceof Object&&Object.keys(u).forEach(function(e){return a.searchParams.set(e,u[e])});var c="HEAD"===n.method;return new Promise(function(e){var t=o.request(a,{headers:n.headers,method:n.method,timeout:n.timeout>0?n.timeout:void 0},function(t){var r=[];c||t.on("data",function(e){return r.push(e)}),t.on("end",function(){var s=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:a.toString(),method:n.method,status:t.statusCode||-3,statusText:t.statusMessage||"Unknown",headers:s,body:c?"":Buffer.concat(r).toString("utf-8")})})});t.on("error",function(t){e({url:a.toString(),method:n.method,status:-1,statusText:t.name||"Unknown",body:t.message})}),n.body&&t.write(n.body),t.end()})})}catch(e){return Promise.reject(e)}},O=/*#__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)&&!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}(),R=/*#__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 O(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)&&null!==n){var s=c(n,"响应数据未能正确识别");if(s.guard(t.data))return t;console.error("response type check faild",e,t.data),r.showMessage(!0,e+" "+s.message)}return t.data=null,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 R(w,e)}var k=E(),A=k.setConfig,L=k.head,U=k.get,C=k.post,S=k.del,F=k.put,D=k.patch;export{E as NetRequest,S as del,U as get,L as head,D as patch,C as post,F as put,A 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 p(e){return e>=200&&e<400}var b=function e(t,r,n,s,i){try{var u,c,l=i||0,h=Math.min(10,null!=(u=null==s?void 0:s.maxRetry)?u:n.get("maxRetry")),d=null!=(c=null==s?void 0:s.retryResolve)?c:n.get("retryResolve"),f=n.get("logHandler")||o;f({type:"prepear",url:r,method:(null==s?void 0:s.method)||"GET",retry:l,maxRetry:h,message:0===l?"start":"retry "+l+"/"+h+" start",options:s});var m=Date.now();return Promise.resolve(t(r,n,s)).then(function(o){var i,u=o.status,c=Date.now()-m,g="[cost "+c+"]["+u+"] "+(u<0?o.body:"");f({type:"finished",url:r,method:o.method,retry:l,maxRetry:h,message:0===l?"finish "+g:"retry "+l+"/"+h+" finish "+g,response:o,cost:c});var v=p(u);if(!h||"network"===d&&u>0||"status"===d&&v||l>=h)return o;var y=null!=(i=null==s?void 0:s.retryInterval)?i:n.get("retryInterval");return Promise.resolve(a(Math.max(100,"function"==typeof y?y(l+1):y))).then(function(){return Promise.resolve(e(t,r,n,s,l+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}function P(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var w=function(e,t,o){try{return Promise.resolve(b(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);p(e.status)||null==(u=o.get("errorHandler"))||u(e.status,e.method,t);var c,l,d,g,v,b=h({},(c=e.status,l=e.statusText,d=e.body,g=o.get("responseRule"),v=(null==a?void 0:a.responseRule)||g,p(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=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":i.message=y(o)||function(e,t){if(void 0===t&&(t=f),!r(e))return"";var o=n(e);return o&&s(o)&&m(o,t)||e}(o,a.messageField)}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({},b),e.method,t),j(b,b.ok?b.message:e.method+" "+t+" ["+(b.code||e.statusText)+"] "+(b.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,s=Object.assign({method:"GET"},r),o=s.body instanceof FormData,a=o?"POST":s.method;"GET"!==a&&"HEAD"!==a&&"DELETE"!==a||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var i=Object.assign(o?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),u=s.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),Promise.resolve(null==(n=t.get("requestHandler"))?void 0:n(i,c,a,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:a,body:P(s.body),params:c,headers:i,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(r,n,s)).then(function(s){var o=n.getFullUrl(s.url||r);if(!i(o))return{url:o,method:s.method,status:-2,statusText:"URLFormatError",headers:{},body:""};var a=/^https:\/\//i.test(o)?t:e,u=new URL(o),c=s.params;c instanceof Object&&Object.keys(c).forEach(function(e){return u.searchParams.set(e,c[e])});var l="HEAD"===s.method;return new Promise(function(e){var t=a.request(u,{headers:s.headers,method:s.method,timeout:s.timeout>0?s.timeout:void 0},function(t){var r=[];l||t.on("data",function(e){return r.push(e)}),t.on("end",function(){var n=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:u.toString(),method:s.method,status:t.statusCode||-3,statusText:t.statusMessage||"Unknown",headers:n,body:l?"":Buffer.concat(r).toString("utf-8")})})});t.on("error",function(t){e({url:u.toString(),method:s.method,status:-1,statusText:t.name||"Unknown",body:t.message})}),s.body&&t.write(s.body),t.end()})})}catch(e){return Promise.reject(e)}},O=/*#__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)&&!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}(),R=/*#__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 O(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 R(w,e)}var k=E(),A=k.setConfig,L=k.head,U=k.get,C=k.post,F=k.del,S=k.put,D=k.patch;export{E as NetRequest,F as del,U as get,L as head,D as patch,C as post,S as put,A 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=a||0,h=Math.min(10,null!=(i=null==o?void 0:o.maxRetry)?i:s.get("maxRetry")),d=null!=(c=null==o?void 0:o.retryResolve)?c:s.get("retryResolve"),f=s.get("logHandler")||e.noop;f({type:"prepear",url:n,method:(null==o?void 0:o.method)||"GET",retry:l,maxRetry:h,message:0===l?"start":"retry "+l+"/"+h+" start",options:o});var g=Date.now();return Promise.resolve(r(n,s,o)).then(function(a){var i,c=a.status,m=Date.now()-g,v="[cost "+m+"]["+c+"] "+(c<0?a.body:"");f({type:"finished",url:n,method:a.method,retry:l,maxRetry:h,message:0===l?"finish "+v:"retry "+l+"/"+h+" finish "+v,response:a,cost:m});var y=u(c);if(!h||"network"===d&&c>0||"status"===d&&y||l>=h)return a;var p=null!=(i=null==o?void 0:o.retryInterval)?i:s.get("retryInterval");return Promise.resolve(e.sleep(Math.max(100,"function"==typeof p?p(l+1):p))).then(function(){return Promise.resolve(t(r,n,s,o,l+1))})})}catch(e){return Promise.reject(e)}};function l(e,t,r,n,s,o){return!1!==(null==o?void 0:o.message)&&s.showMessage(!e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,n,t):t),e}function h(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var d=function(r,o,a){try{return Promise.resolve(c(f,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=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":u.message=i(o)||function(t,r){if(void 0===r&&(r=n),!e.isJsonLike(t))return"";var o=e.parseJSON(t);return o&&e.isStringRecord(o)&&s(o,r)||t}(o,a.messageField)}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)}},f=function(r,n,s){try{return Promise.resolve(function(e,t,r){try{var n,s=Object.assign({method:"GET"},r),o=s.body instanceof FormData,a=o?"POST":s.method;"GET"!==a&&"HEAD"!==a&&"DELETE"!==a||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var i=Object.assign(o?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),u=s.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),Promise.resolve(null==(n=t.get("requestHandler"))?void 0:n(i,c,a,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:a,body:h(s.body),params:c,headers:i,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(r,n,s)).then(function(s){var o="PATCH"===s.method?"POST":s.method,a=e.addParamsToString(n.getFullUrl(s.url||r),s.params);return globalThis.wx?new Promise(function(e){wx.request({url:a,data:s.body,header:s.headers,method:o,dataType:"string",responseType:"text",fail:function(){e({url:a,method:o,status:-1,statusText:"NetworkError",body:"Network Error"})},success:function(r){var n;e({url:a,method:o,status:r.statusCode,statusText:r.statusCode+"",headers:t({},r.header),body:(n=r.data,"string"==typeof n?n:n instanceof ArrayBuffer&&"TextDecoder"in globalThis?(new TextDecoder).decode(n):JSON.stringify(n))})}})}):{url:a,method:o,status:-2,statusText:"NotSupport",body:"NotFound namespace of wx"}})}catch(e){return Promise.reject(e)}},g=/*#__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}(),m=/*#__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=/*#__PURE__*/function(){function t(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new m(t),this.agent=e,this.cache=new g(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)&&null!==s){var o=e.getTypeGuard(s,"响应数据未能正确识别");if(o.guard(r.data))return r;console.error("response type check faild",t,r.data),n.showMessage(!0,t+" "+o.message)}return r.data=null,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 y(e){return new v(d,e)}var p=y(),b=p.setConfig,T=p.head,j=p.get,P=p.post,x=p.del,w=p.put;exports.NetRequest=y,exports.del=x,exports.get=j,exports.head=T,exports.post=P,exports.put=w,exports.setGlobalConfig=b;
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=a||0,h=Math.min(10,null!=(i=null==o?void 0:o.maxRetry)?i:s.get("maxRetry")),d=null!=(c=null==o?void 0:o.retryResolve)?c:s.get("retryResolve"),f=s.get("logHandler")||e.noop;f({type:"prepear",url:n,method:(null==o?void 0:o.method)||"GET",retry:l,maxRetry:h,message:0===l?"start":"retry "+l+"/"+h+" start",options:o});var g=Date.now();return Promise.resolve(r(n,s,o)).then(function(a){var i,c=a.status,m=Date.now()-g,v="[cost "+m+"]["+c+"] "+(c<0?a.body:"");f({type:"finished",url:n,method:a.method,retry:l,maxRetry:h,message:0===l?"finish "+v:"retry "+l+"/"+h+" finish "+v,response:a,cost:m});var y=u(c);if(!h||"network"===d&&c>0||"status"===d&&y||l>=h)return a;var p=null!=(i=null==o?void 0:o.retryInterval)?i:s.get("retryInterval");return Promise.resolve(e.sleep(Math.max(100,"function"==typeof p?p(l+1):p))).then(function(){return Promise.resolve(t(r,n,s,o,l+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}function h(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var d=function(r,o,a){try{return Promise.resolve(c(f,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=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":u.message=i(o)||function(t,r){if(void 0===r&&(r=n),!e.isJsonLike(t))return"";var o=e.parseJSON(t);return o&&e.isStringRecord(o)&&s(o,r)||t}(o,a.messageField)}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)}},f=function(r,n,s){try{return Promise.resolve(function(e,t,r){try{var n,s=Object.assign({method:"GET"},r),o=s.body instanceof FormData,a=o?"POST":s.method;"GET"!==a&&"HEAD"!==a&&"DELETE"!==a||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var i=Object.assign(o?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),u=s.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),Promise.resolve(null==(n=t.get("requestHandler"))?void 0:n(i,c,a,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:a,body:h(s.body),params:c,headers:i,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(r,n,s)).then(function(s){var o="PATCH"===s.method?"POST":s.method,a=e.addParamsToString(n.getFullUrl(s.url||r),s.params);return globalThis.wx?new Promise(function(e){wx.request({url:a,data:s.body,header:s.headers,method:o,dataType:"string",responseType:"text",fail:function(){e({url:a,method:o,status:-1,statusText:"NetworkError",body:"Network Error"})},success:function(r){var n;e({url:a,method:o,status:r.statusCode,statusText:r.statusCode+"",headers:t({},r.header),body:(n=r.data,"string"==typeof n?n:n instanceof ArrayBuffer&&"TextDecoder"in globalThis?(new TextDecoder).decode(n):JSON.stringify(n))})}})}):{url:a,method:o,status:-2,statusText:"NotSupport",body:"NotFound namespace of wx"}})}catch(e){return Promise.reject(e)}},g=/*#__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}(),m=/*#__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=/*#__PURE__*/function(){function t(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new m(t),this.agent=e,this.cache=new g(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 y(e){return new v(d,e)}var p=y(),b=p.setConfig,T=p.head,j=p.get,P=p.post,x=p.del,w=p.put;exports.NetRequest=y,exports.del=x,exports.get=j,exports.head=T,exports.post=P,exports.put=w,exports.setGlobalConfig=b;
package/dist/wx.d.ts CHANGED
@@ -12,14 +12,14 @@ export declare const setGlobalConfig: (config: IRequestGlobalConfig) => void;
12
12
  /**
13
13
  * 发送一个 HEAD 请求
14
14
  */
15
- export declare const head: (url: string, options?: import("./inc/type").IRequestOptions | undefined) => import("./inc/type").ResponseWithType<null>;
15
+ export declare const head: (url: string, options?: import("./inc/type").IRequestOptions | undefined) => import("./inc/type").ResponseWithoutType;
16
16
  /**
17
17
  * 发送一个 GET 请求,请求自带 500ms 缓冲控制以应对并发场景,可选 typeGuard 用于检查数据类型
18
18
  */
19
19
  export declare const get: {
20
20
  (url: string): import("./inc/type").ResponseWithoutType;
21
21
  (url: string, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
22
- <T>(url: string, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
22
+ <T>(url: string, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
23
23
  };
24
24
  /**
25
25
  * 发送一个 POST 请求,可选 typeGuard 用于检查数据类型
@@ -27,7 +27,7 @@ export declare const get: {
27
27
  export declare const post: {
28
28
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
29
29
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
30
- <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
30
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
31
31
  };
32
32
  /**
33
33
  * 发送一个 DELETE 请求,可选 typeGuard 用于检查数据类型
@@ -35,7 +35,7 @@ export declare const post: {
35
35
  export declare const del: {
36
36
  (url: string): import("./inc/type").ResponseWithoutType;
37
37
  (url: string, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
38
- <T>(url: string, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
38
+ <T>(url: string, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
39
39
  };
40
40
  /**
41
41
  * 发送一个 PUT 请求,可选 typeGuard 用于检查数据类型
@@ -43,5 +43,5 @@ export declare const del: {
43
43
  export declare const put: {
44
44
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams): import("./inc/type").ResponseWithoutType;
45
45
  (url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: null, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithoutType;
46
- <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("@seayoo-web/utils").TypeGuard<T> | import("@seayoo-web/utils").TypeGuardFn<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
46
+ <T>(url: string, data: string | object | unknown[] | Blob | ArrayBuffer | FormData | URLSearchParams, typeGard: import("./inc/type").TypeGuardParam<T>, options?: import("./inc/type").IRequestOptions | undefined): import("./inc/type").ResponseWithType<T>;
47
47
  };
package/dist/wx.mjs 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 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 p=function e(t,r,o,a,i){try{var u,c,l=i||0,h=Math.min(10,null!=(u=null==a?void 0:a.maxRetry)?u:o.get("maxRetry")),d=null!=(c=null==a?void 0:a.retryResolve)?c:o.get("retryResolve"),f=o.get("logHandler")||n;f({type:"prepear",url:r,method:(null==a?void 0:a.method)||"GET",retry:l,maxRetry:h,message:0===l?"start":"retry "+l+"/"+h+" start",options:a});var g=Date.now();return Promise.resolve(t(r,o,a)).then(function(n){var i,u=n.status,c=Date.now()-g,m="[cost "+c+"]["+u+"] "+(u<0?n.body:"");f({type:"finished",url:r,method:n.method,retry:l,maxRetry:h,message:0===l?"finish "+m:"retry "+l+"/"+h+" finish "+m,response:n,cost:c});var v=y(u);if(!h||"network"===d&&u>0||"status"===d&&v||l>=h)return n;var p=null!=(i=null==a?void 0:a.retryInterval)?i:o.get("retryInterval");return Promise.resolve(s(Math.max(100,"function"==typeof p?p(l+1):p))).then(function(){return Promise.resolve(e(t,r,o,a,l+1))})})}catch(e){return Promise.reject(e)}};function b(e,t,r,n,s,o){return!1!==(null==o?void 0:o.message)&&s.showMessage(!e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,n,t):t),e}function j(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var T=function(n,s,o){try{return Promise.resolve(p(P,n,s,o)).then(function(a){return function(n,s,o,a){var i,u;if(n.status<0)return b({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,p,j=l({},(c=n.status,h=n.statusText,g=n.body,m=o.get("responseRule"),p=(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=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}(p.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":i.message=v(o)||function(n,s){if(void 0===s&&(s=d),!e(n))return"";var o=t(n);return o&&r(o)&&f(o,s)||n}(o,a.messageField)}return i}(p.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({},j),n.method,s),b(j,j.ok?j.message:n.method+" "+s+" ["+(j.code||n.statusText)+"] "+(j.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,s=Object.assign({method:"GET"},r),o=s.body instanceof FormData,a=o?"POST":s.method;"GET"!==a&&"HEAD"!==a&&"DELETE"!==a||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var i=Object.assign(o?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),u=s.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),Promise.resolve(null==(n=t.get("requestHandler"))?void 0:n(i,c,a,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:a,body:j(s.body),params:c,headers:i,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(e,t,r)).then(function(r){var n="PATCH"===r.method?"POST":r.method,s=o(t.getFullUrl(r.url||e),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:"Network Error"})},success:function(t){var r;e({url:s,method:n,status:t.statusCode,statusText:t.statusCode+"",headers:l({},t.header),body:(r=t.data,"string"==typeof r?r:r instanceof ArrayBuffer&&"TextDecoder"in globalThis?(new TextDecoder).decode(r):JSON.stringify(r))})}})}):{url:s,method:n,status:-2,statusText:"NotSupport",body:"NotFound namespace of wx"}})}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}(),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}(),O=/*#__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 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&&!a(t.data)&&null!==n){var s=i(n,"响应数据未能正确识别");if(s.guard(t.data))return t;console.error("response type check faild",e,t.data),r.showMessage(!0,e+" "+s.message)}return t.data=null,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 O(T,e)}var k=R(),E=k.setConfig,A=k.head,L=k.get,C=k.post,F=k.del,S=k.put;export{R as NetRequest,F as del,L as get,A as head,C as post,S as put,E 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 p=function e(t,r,o,a,i){try{var u,c,l=i||0,h=Math.min(10,null!=(u=null==a?void 0:a.maxRetry)?u:o.get("maxRetry")),d=null!=(c=null==a?void 0:a.retryResolve)?c:o.get("retryResolve"),f=o.get("logHandler")||n;f({type:"prepear",url:r,method:(null==a?void 0:a.method)||"GET",retry:l,maxRetry:h,message:0===l?"start":"retry "+l+"/"+h+" start",options:a});var g=Date.now();return Promise.resolve(t(r,o,a)).then(function(n){var i,u=n.status,c=Date.now()-g,m="[cost "+c+"]["+u+"] "+(u<0?n.body:"");f({type:"finished",url:r,method:n.method,retry:l,maxRetry:h,message:0===l?"finish "+m:"retry "+l+"/"+h+" finish "+m,response:n,cost:c});var v=y(u);if(!h||"network"===d&&u>0||"status"===d&&v||l>=h)return n;var p=null!=(i=null==a?void 0:a.retryInterval)?i:o.get("retryInterval");return Promise.resolve(s(Math.max(100,"function"==typeof p?p(l+1):p))).then(function(){return Promise.resolve(e(t,r,o,a,l+1))})})}catch(e){return Promise.reject(e)}};function b(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}function j(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var T=function(n,s,o){try{return Promise.resolve(p(P,n,s,o)).then(function(a){return function(n,s,o,a){var i,u;if(n.status<0)return b({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,p,j=l({},(c=n.status,h=n.statusText,g=n.body,m=o.get("responseRule"),p=(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=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}(p.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":i.message=v(o)||function(n,s){if(void 0===s&&(s=d),!e(n))return"";var o=t(n);return o&&r(o)&&f(o,s)||n}(o,a.messageField)}return i}(p.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({},j),n.method,s),b(j,j.ok?j.message:n.method+" "+s+" ["+(j.code||n.statusText)+"] "+(j.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,s=Object.assign({method:"GET"},r),o=s.body instanceof FormData,a=o?"POST":s.method;"GET"!==a&&"HEAD"!==a&&"DELETE"!==a||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var i=Object.assign(o?{}:{"Content-Type":"application/json;charset=utf-8"},s.headers),u=s.params||{},c={};return Object.keys(u).forEach(function(e){var t;void 0!==u[e]&&(c[e]="string"==typeof(t=u[e])?t:Array.isArray(t)?t.join(","):t+"")}),Promise.resolve(null==(n=t.get("requestHandler"))?void 0:n(i,c,a,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:a,body:j(s.body),params:c,headers:i,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(e,t,r)).then(function(r){var n="PATCH"===r.method?"POST":r.method,s=o(t.getFullUrl(r.url||e),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:"Network Error"})},success:function(t){var r;e({url:s,method:n,status:t.statusCode,statusText:t.statusCode+"",headers:l({},t.header),body:(r=t.data,"string"==typeof r?r:r instanceof ArrayBuffer&&"TextDecoder"in globalThis?(new TextDecoder).decode(r):JSON.stringify(r))})}})}):{url:s,method:n,status:-2,statusText:"NotSupport",body:"NotFound namespace of wx"}})}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}(),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}(),O=/*#__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 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&&!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 R(e){return new O(T,e)}var k=R(),E=k.setConfig,A=k.head,L=k.get,C=k.post,F=k.del,S=k.put;export{R as NetRequest,F as del,L as get,A as head,C as post,S as put,E as setGlobalConfig};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-web/request",
3
- "version": "1.1.1",
3
+ "version": "1.1.3",
4
4
  "description": "requst tools for seayoo web",
5
5
  "type": "module",
6
6
  "main": "dist/index.mjs",