@seayoo-web/request 0.9.2 → 1.0.1

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
@@ -11,7 +11,7 @@
11
11
 
12
12
  ## 特性
13
13
 
14
- 1. 默认基于 fetch,请求和响应解析均基于 json 或 text(不支持其他格式)
14
+ 1. 默认基于 fetch,请求和响应解析均默认基于 json 或 text
15
15
  2. 支持重试配置 maxRetry / retryResolve / retryInterval
16
16
  3. 支持响应结果处理策略 responseRule 和通用提示配置
17
17
  4. 支持类型守卫 typeGuard
@@ -108,7 +108,7 @@ setConfig({ timeout: 5000 })
108
108
 
109
109
  类型:string
110
110
 
111
- 说明:影响所有网络请求工具的 url 设置,需要以 / 开头 或者是一个完整的 url 地址;此设置会给请求 url 前增加 baseURL,但以下两种情况除外
111
+ 说明:需要以 / 开头 或者是一个完整的 url 地址;此设置会给所有请求的 url 增加 baseURL 作为前缀,但以下两种情况除外
112
112
 
113
113
  1. 请求时传入的 url 为完整 url,即以 http:// 或 https:// 开头
114
114
  2. 请求时传入的 url 以 / 开头
@@ -135,7 +135,7 @@ setConfig({ timeout: 5000 })
135
135
 
136
136
  类型: number
137
137
 
138
- 说明:用于控制 get 请求的缓冲时效,单位 ms,默认 500
138
+ 说明:用于控制 get 请求的缓冲时效,单位 ms,默认 500,设置为 0 则禁用缓冲
139
139
 
140
140
  ### message
141
141
 
@@ -153,13 +153,13 @@ setConfig({ timeout: 5000 })
153
153
 
154
154
  http失败时 (status <200 || status >= 400) 解析策略
155
155
 
156
- **resolve**: "json" | "body" | "auto"
156
+ **resolve**: "json" | "body"
157
157
 
158
- ​ 解析方式,设置为 json(默认),则可以进一步指定错误消息字段;设置为 body 则将整个 body 解析为错误信息;设置为 auto 则尝试上述两种策略;
158
+ ​ 解析方式,设置为 json(默认),则可以进一步指定错误消息字段;设置为 body 则将整个 body 解析为错误信息;
159
159
 
160
160
  **messageField**: string
161
161
 
162
- ​ 错误消息解析字段,仅在 resolve 为 json 或 auto 时有效,默认值 message
162
+ ​ 错误消息解析字段,仅在 resolve 为 json 时有效,默认值 message
163
163
 
164
164
  - **OKRule**: { resolve, statusField?, statusOKValue?, dataField?, messageField?, ignoreMessage? }
165
165
 
@@ -170,10 +170,12 @@ setConfig({ timeout: 5000 })
170
170
  ​ 解析方式,若设置为 json,则可以进一步指定更多字段;若设置为 body(默认),则把整个响应体作为接口返回的数据使用,如果格式化失败,则返回响应的字符串;
171
171
 
172
172
  **statusField**: string
173
+
174
+ 指定表示自定义状态的字段名,默认是 "code"
173
175
 
174
176
  **statusOKValue**: string
175
177
 
176
- 指定表示自定义状态的字段以及成功时的 value,默认是 "code" 和 "0"
178
+ 指定表示自定义状态成功时的 value,默认是 "0",如果响应值为数字,则会被转化为字符串进行处理
177
179
 
178
180
  **dataField**: string
179
181
 
@@ -195,9 +197,9 @@ setConfig({ timeout: 5000 })
195
197
 
196
198
  ### retryResolve
197
199
 
198
- 类型:network | status
200
+ 类型:"network" | "status"
199
201
 
200
- 说明:重试判断方法,network 表示仅仅当网络错误时才重试;stauts 表示网络错误或者状态码错误时重试; 默认是 network
202
+ 说明:重试判断方法,network 表示仅仅当网络错误时才重试;status 表示网络错误或者状态码错误时重试; 默认是 network
201
203
 
202
204
  ### retryInterval
203
205
 
@@ -207,15 +209,19 @@ setConfig({ timeout: 5000 })
207
209
 
208
210
  ### requestHandler
209
211
 
210
- 类型:null | ((headers: Record<string, string>, params: Record<string, string>, method: string, url: string) => void)
212
+ 类型:null | ((headers: Record<string, string>, params: Record<string, string>, method: string, url: string) => MaybePromise<void | string>)
213
+
214
+ 说明:发送前用于修改 headers 或 params 的函数,headers 和 params 为引用数据,可以直接追加字段和内容;
215
+
216
+ 函数如果返回一个非空字符串,则当作 url 地址使用,原有的 url 地址将被替换;
211
217
 
212
- 说明:发送前用于修改 request headers 或 params 的函数,headers 和 params 为引用数据,可以直接追加字段和内容;通常用于全局追加自定义认证信息;
218
+ 通常用于全局追加 header 自定义认证信息;
213
219
 
214
220
  ### errorHandler
215
221
 
216
222
  类型:null | ((status: number, method: string, url: string) => void)
217
223
 
218
- 说明:全局错误处理函数,仅仅在 http status 错误时触发
224
+ 说明:全局错误处理函数,仅仅在 http status 错误时触发,通常用于检查 401 未登录状态进行跳转登录
219
225
 
220
226
  ### responseHandler
221
227
 
@@ -1,9 +1,10 @@
1
1
  import type { IBaseRequestOptions, IBaseRequestBody } from "./type";
2
2
  import type { RequestGlobalConfig } from "./config";
3
3
  type FixedRequestOptions = Omit<Required<IBaseRequestOptions>, "params" | "body"> & {
4
+ url?: string;
4
5
  params: Record<string, string>;
5
6
  body: ReturnType<typeof convertBody>;
6
7
  };
7
- export declare function convertOptions(url: string, config: RequestGlobalConfig, options?: IBaseRequestOptions): FixedRequestOptions;
8
+ export declare function convertOptions(url: string, config: RequestGlobalConfig, options?: IBaseRequestOptions): Promise<FixedRequestOptions>;
8
9
  declare function convertBody(body: IBaseRequestOptions["body"]): IBaseRequestBody | undefined;
9
10
  export {};
@@ -1,3 +1,4 @@
1
+ import type { MaybePromise } from "@seayoo-web/utils";
1
2
  import type { RequestGlobalConfig } from "./config";
2
3
  export type IBaseRequestBody = Blob | ArrayBuffer | FormData | URLSearchParams | string;
3
4
  /** 通用网络请求工具的基本配置 */
@@ -44,8 +45,8 @@ export type IRequestGlobalConfig = {
44
45
  baseURL?: string;
45
46
  /** 用于 get 请求的缓存时长,单位 ms,建议不小于 100 */
46
47
  cacheTTL?: number;
47
- /** 全局 request 处理函数,headers 和 params 为引用型数据可直接修改 */
48
- requestHandler?: null | ((headers: Record<string, string>, params: Record<string, string>, method: string, url: string) => void);
48
+ /** 全局 request 处理函数,headers 和 params 为引用型数据可直接修改,如果返回字符串,则替换原来的 url 进行请求 */
49
+ requestHandler?: null | ((headers: Record<string, string>, params: Record<string, string>, method: string, url: string) => MaybePromise<void | string>);
49
50
  /** 全局错误处理函数,仅仅在 statusCode 错误时触发 */
50
51
  errorHandler?: null | ((status: number, method: string, url: string) => void);
51
52
  /** 全局响应处理函数,任意状态都会触发 */
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,r){var s,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+"")}),null==(s=t.get("requestHandler"))||s(u,l,i,e),{method:i,body:n(o.body),params:l,headers:u,timeout:o.timeout||t.get("timeout"),credentials:o.credentials||t.get("credentials")}}function n(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var s=function(e,t,n){try{var s=r(e,t,n),o=new URL(t.getFullUrl(e)),a=s.params;a instanceof Object&&Object.keys(a).forEach(function(e){return o.searchParams.set(e,a[e])});var i=new AbortController,u=s.timeout>0?setTimeout(function(){return i.abort()},s.timeout):null,c=new Request(o,{method:s.method,headers:new Headers(s.headers),body:s.body,credentials:s.credentials,signal:s.timeout>0?i.signal:null,redirect:"follow"});return Promise.resolve(fetch(c).then(function(e){try{var t=function(e){return{url:u,method:i,status:a,statusText:n,headers:r,body:e}},r=Object.fromEntries(e.headers.entries()),n=e.statusText,a=e.status,i=s.method,u=o.toString();return Promise.resolve("HEAD"===s.method?t(""):Promise.resolve(e.text()).then(t))}catch(e){return Promise.reject(e)}}).catch(function(e){return{url:o.toString(),method:s.method,status:-1,statusText:"NetworkError",body:String(e)}}).finally(function(){null!==u&&clearTimeout(u)}))}catch(e){return Promise.reject(e)}},o="data",a="message";function i(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);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,d=Math.min(10,null!=(i=null==o?void 0:o.maxRetry)?i:s.get("maxRetry")),h=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:d,message:0===l?"start":"retry "+l+"/"+d+" 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:d,message:0===l?"finish "+v:"retry "+l+"/"+d+" finish "+v,response:a,cost:m});var p=u(c);if(!d||"network"===h&&c>0||"status"===h&&p||l>=d)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(l+1):y))).then(function(){return Promise.resolve(t(r,n,s,o,l+1))})})}catch(e){return Promise.reject(e)}};function l(r,n,s,c){var l,h;if(r.status<0)return d({ok:!1,status:r.status,code:r.statusText,headers:{},message:"",data:null},r.method+" "+n+" "+r.statusText,r.method,n,s,c);u(r.status)||null==(h=s.get("errorHandler"))||h(r.status,r.method,n);var f,g,m,v,p,y=t({},(f=r.status,g=r.statusText,m=r.body,v=s.get("responseRule"),p=(null==c?void 0:c.responseRule)||v,u(f)?function(t,r,n,s){var i=t||{resolve:"body"},u={ok:!0,code:n,message:"",data:null};if(202===r||204===r||!s)return u;if("body"===i.resolve)return u.data=e.isJsonLike(s)?e.parseJSON(s):s,u;var c=e.parseJSON(s);if(!c||!e.isStringRecord(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=i.statusField,d=i.statusOKValue||"",h=i.dataField||o,f=i.messageField||a,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===d,u.code=m||n,u.data=h in c?c[h]:null,u.message=f in c?c[f]+"":"",g&&u.message&&(Array.isArray(g)&&g.includes(u.message)||"string"==typeof g&&u.message===g)&&(u.message=""),u}(p.ok||v.ok,f,g,m):function(t,r,n){var s=t||{resolve:"json",messageField:a},o={ok:!1,code:r,message:n,data:null};switch(s.resolve){case"body":o.message=i(n)||n;break;case"json":o.message=i(n)||function(t,r){if(void 0===r&&(r=a),!e.isJsonLike(t))return"";var n,s=e.parseJSON(t);return s&&e.isStringRecord(s)&&r in s?(n=s[r])?"string"==typeof n?n:JSON.stringify(n):"":t}(n,s.messageField)}return o}(p.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==(l=s.get("responseHandler"))||l(t({},y),r.method,n),d(y,y.ok?y.message:r.method+" "+n+" ["+y.code+"] "+(y.message||r.statusText),r.method,n,s,c)}function d(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 h=/*#__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}(),f=function(n,s,o){try{var a=t({},r(n,s,o),{onUploadProgress:null==o?void 0:o.onUploadProgress}),i=a.method,u=a.onUploadProgress||function(){return 0},c=e.addParamsToString(s.getFullUrl(n),a.params);return Promise.resolve(new Promise(function(e){var t=1,r=0,s=new XMLHttpRequest;s.upload.addEventListener("progress",function(e){t=e.total,u({total:e.total,loaded:e.loaded})}),s.addEventListener("load",function(){r&&clearTimeout(r),u({loaded:t,total:t}),e({url:c,method:i,status:s.status,statusText:s.statusText,headers:g(s),body:"HEAD"===i?"":s.responseText})}),s.addEventListener("error",function(){r&&clearTimeout(r),e({url:c,method:i,status:-2,statusText:"Failed",body:"Request "+i+" "+n+" Failed"})}),s.addEventListener("abort",function(){r&&clearTimeout(r),e({url:c,method:i,status:-3,statusText:"Aborted",body:"Request "+i+" "+n+" 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&&(r=setTimeout(function(){s.abort()},a.timeout))}))}catch(e){return Promise.reject(e)}};function g(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 m=function(e,t,r){try{return Promise.resolve(c(s,e,t,r)).then(function(n){return l(n,e,t,r)})}catch(e){return Promise.reject(e)}},v=function(e,t,r){try{return Promise.resolve(c(f,e,t,r)).then(function(n){return l(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}(),y=/*#__PURE__*/function(){function t(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new h(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 b(e){return"fetch"in window?new y(m,e):new y(v,e)}var j=b(),P=j.setConfig,w=j.head,T=j.get,x=j.post,R=j.del,O=j.put,E=j.patch;exports.NetRequest=b,exports.del=R,exports.get=T,exports.getResponseRulesDescription=function(e){var t=[],r=e.failed||{resolve:"json"};switch(t.push("- 当http状态码 <200 或者 >=400 时"),r.resolve){case"body":t.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":t.push(" 将响应解析为json,并读取 "+(r.messageField||a)+" 作为错误消息")}var n=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":t.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(n.dataField||o)+" 作为响应数据,读取 "+(n.messageField||a)+" 作为提示消息"),n.statusField&&t.push(" 当 "+n.statusField+" 为 "+(n.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&t.push(" 并忽略以下消息:"+n.ignoreMessage)}return t.join("\n")},exports.head=w,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=E,exports.post=x,exports.put=O,exports.setGlobalConfig=P,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 h(s);return Promise.resolve(f(e,c,t({},n,{method:"POST",body:o}))).then(function(t){return l(t,e,c,n)})}catch(e){return Promise.reject(e)}}(e,r,n,{baseURL:j.getConfig("baseURL"),logHandler:j.getConfig("logHandler"),errorHandler:j.getConfig("errorHandler"),requestHandler:j.getConfig("requestHandler"),messageHandler:j.getConfig("messageHandler"),responseHandler:j.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)}var r=function(e,t,r){try{var s,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==(s=t.get("requestHandler"))?void 0:s(u,l,i,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:i,body:n(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 n(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var s=function(e,t,n){try{return Promise.resolve(r(e,t,n)).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)}},o="data",a="message";function i(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);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,d=Math.min(10,null!=(i=null==o?void 0:o.maxRetry)?i:s.get("maxRetry")),h=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:d,message:0===l?"start":"retry "+l+"/"+d+" 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:d,message:0===l?"finish "+v:"retry "+l+"/"+d+" finish "+v,response:a,cost:m});var p=u(c);if(!d||"network"===h&&c>0||"status"===h&&p||l>=d)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(l+1):y))).then(function(){return Promise.resolve(t(r,n,s,o,l+1))})})}catch(e){return Promise.reject(e)}};function l(r,n,s,c){var l,h;if(r.status<0)return d({ok:!1,status:r.status,code:r.statusText,headers:{},message:"",data:null},r.method+" "+n+" "+r.statusText,r.method,n,s,c);u(r.status)||null==(h=s.get("errorHandler"))||h(r.status,r.method,n);var f,g,m,v,p,y=t({},(f=r.status,g=r.statusText,m=r.body,v=s.get("responseRule"),p=(null==c?void 0:c.responseRule)||v,u(f)?function(t,r,n,s){var i=t||{resolve:"body"},u={ok:!0,code:n,message:"",data:null};if(202===r||204===r||!s)return u;if("body"===i.resolve)return u.data=e.isJsonLike(s)?e.parseJSON(s):s,u;var c=e.parseJSON(s);if(!c||!e.isStringRecord(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=i.statusField,d=i.statusOKValue||"",h=i.dataField||o,f=i.messageField||a,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===d,u.code=m||n,u.data=h in c?c[h]:null,u.message=f in c?c[f]+"":"",g&&u.message&&(Array.isArray(g)&&g.includes(u.message)||"string"==typeof g&&u.message===g)&&(u.message=""),u}(p.ok||v.ok,f,g,m):function(t,r,n){var s=t||{resolve:"json",messageField:a},o={ok:!1,code:r,message:n,data:null};switch(s.resolve){case"body":o.message=i(n)||n;break;case"json":o.message=i(n)||function(t,r){if(void 0===r&&(r=a),!e.isJsonLike(t))return"";var n,s=e.parseJSON(t);return s&&e.isStringRecord(s)&&r in s?(n=s[r])?"string"==typeof n?n:JSON.stringify(n):"":t}(n,s.messageField)}return o}(p.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==(l=s.get("responseHandler"))||l(t({},y),r.method,n),d(y,y.ok?y.message:r.method+" "+n+" ["+y.code+"] "+(y.message||r.statusText),r.method,n,s,c)}function d(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 h=/*#__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}(),f=function(n,s,o){try{return Promise.resolve(r(n,s,o)).then(function(r){var a=t({},r,{onUploadProgress:null==o?void 0:o.onUploadProgress}),i=a.method,u=a.onUploadProgress||function(){return 0},c=e.addParamsToString(s.getFullUrl(a.url||n),a.params);return Promise.resolve(new Promise(function(e){var t=1,r=0,s=new XMLHttpRequest;s.upload.addEventListener("progress",function(e){t=e.total,u({total:e.total,loaded:e.loaded})}),s.addEventListener("load",function(){r&&clearTimeout(r),u({loaded:t,total:t}),e({url:c,method:i,status:s.status,statusText:s.statusText,headers:g(s),body:"HEAD"===i?"":s.responseText})}),s.addEventListener("error",function(){r&&clearTimeout(r),e({url:c,method:i,status:-2,statusText:"Failed",body:"Request "+i+" "+n+" Failed"})}),s.addEventListener("abort",function(){r&&clearTimeout(r),e({url:c,method:i,status:-3,statusText:"Aborted",body:"Request "+i+" "+n+" 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&&(r=setTimeout(function(){s.abort()},a.timeout))}))})}catch(e){return Promise.reject(e)}};function g(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 m=function(e,t,r){try{return Promise.resolve(c(s,e,t,r)).then(function(n){return l(n,e,t,r)})}catch(e){return Promise.reject(e)}},v=function(e,t,r){try{return Promise.resolve(c(f,e,t,r)).then(function(n){return l(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}(),y=/*#__PURE__*/function(){function t(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new h(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 b(e){return"fetch"in window?new y(m,e):new y(v,e)}var P=b(),j=P.setConfig,w=P.head,T=P.get,x=P.post,R=P.del,O=P.put,E=P.patch;exports.NetRequest=b,exports.del=R,exports.get=T,exports.getResponseRulesDescription=function(e){var t=[],r=e.failed||{resolve:"json"};switch(t.push("- 当http状态码 <200 或者 >=400 时"),r.resolve){case"body":t.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":t.push(" 将响应解析为json,并读取 "+(r.messageField||a)+" 作为错误消息")}var n=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":t.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(n.dataField||o)+" 作为响应数据,读取 "+(n.messageField||a)+" 作为提示消息"),n.statusField&&t.push(" 当 "+n.statusField+" 为 "+(n.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&t.push(" 并忽略以下消息:"+n.ignoreMessage)}return t.join("\n")},exports.head=w,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=E,exports.post=x,exports.put=O,exports.setGlobalConfig=j,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 h(s);return Promise.resolve(f(e,c,t({},n,{method:"POST",body:o}))).then(function(t){return l(t,e,c,n)})}catch(e){return Promise.reject(e)}}(e,r,n,{baseURL:P.getConfig("baseURL"),logHandler:P.getConfig("logHandler"),errorHandler:P.getConfig("errorHandler"),requestHandler:P.getConfig("requestHandler"),messageHandler:P.getConfig("messageHandler"),responseHandler:P.getConfig("responseHandler")}))}catch(e){return Promise.reject(e)}};
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,r){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+"")}),null==(n=t.get("requestHandler"))||n(i,c,a,e),{method:a,body:f(s.body),params:c,headers:i,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}}function f(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var m=function(e,t,r){try{var n=h(e,t,r),s=new URL(t.getFullUrl(e)),o=n.params;o instanceof Object&&Object.keys(o).forEach(function(e){return s.searchParams.set(e,o[e])});var a=new AbortController,i=n.timeout>0?setTimeout(function(){return a.abort()},n.timeout):null,u=new Request(s,{method:n.method,headers:new Headers(n.headers),body:n.body,credentials:n.credentials,signal:n.timeout>0?a.signal:null,redirect:"follow"});return Promise.resolve(fetch(u).then(function(e){try{var t=function(e){return{url:u,method:i,status:a,statusText:o,headers:r,body:e}},r=Object.fromEntries(e.headers.entries()),o=e.statusText,a=e.status,i=n.method,u=s.toString();return Promise.resolve("HEAD"===n.method?t(""):Promise.resolve(e.text()).then(t))}catch(e){return Promise.reject(e)}}).catch(function(e){return{url:s.toString(),method:n.method,status:-1,statusText:"NetworkError",body:String(e)}}).finally(function(){null!==i&&clearTimeout(i)}))}catch(e){return Promise.reject(e)}},g="data",v="message",y=function(e){var t=[],r=e.failed||{resolve:"json"};switch(t.push("- 当http状态码 <200 或者 >=400 时"),r.resolve){case"body":t.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":t.push(" 将响应解析为json,并读取 "+(r.messageField||v)+" 作为错误消息")}var n=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":t.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(n.dataField||g)+" 作为响应数据,读取 "+(n.messageField||v)+" 作为提示消息"),n.statusField&&t.push(" 当 "+n.statusField+" 为 "+(n.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&t.push(" 并忽略以下消息:"+n.ignoreMessage)}return t.join("\n")};function p(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function b(e){return e>=200&&e<400}var j=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=b(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 P(n,s,o,a){var i,u;if(n.status<0)return w({ok:!1,status:n.status,code:n.statusText,headers:{},message:"",data:null},n.method+" "+s+" "+n.statusText,n.method,s,o,a);b(n.status)||null==(u=o.get("errorHandler"))||u(n.status,n.method,s);var c,l,h,f,m,y=d({},(c=n.status,l=n.statusText,h=n.body,f=o.get("responseRule"),m=(null==a?void 0:a.responseRule)||f,b(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||g,f=i.messageField||v,m=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===d,u.code=y||o,u.data=h in c?c[h]:null,u.message=f in c?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:v},i={ok:!1,code:s,message:o,data:null};switch(a.resolve){case"body":i.message=p(o)||o;break;case"json":i.message=p(o)||function(n,s){if(void 0===s&&(s=v),!e(n))return"";var o,a=t(n);return a&&r(a)&&s in a?(o=a[s])?"string"==typeof o?o:JSON.stringify(o):"":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({},y),n.method,s),w(y,y.ok?y.message:n.method+" "+s+" ["+y.code+"] "+(y.message||n.statusText),n.method,s,o,a)}function w(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 T=/*#__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}(),x=function(e,t,r){try{var n=d({},h(e,t,r),{onUploadProgress:null==r?void 0:r.onUploadProgress}),s=n.method,o=n.onUploadProgress||function(){return 0},a=i(t.getFullUrl(e),n.params);return Promise.resolve(new Promise(function(t){var r=1,i=0,u=new XMLHttpRequest;u.upload.addEventListener("progress",function(e){r=e.total,o({total:e.total,loaded:e.loaded})}),u.addEventListener("load",function(){i&&clearTimeout(i),o({loaded:r,total:r}),t({url:a,method:s,status:u.status,statusText:u.statusText,headers:O(u),body:"HEAD"===s?"":u.responseText})}),u.addEventListener("error",function(){i&&clearTimeout(i),t({url:a,method:s,status:-2,statusText:"Failed",body:"Request "+s+" "+e+" Failed"})}),u.addEventListener("abort",function(){i&&clearTimeout(i),t({url:a,method:s,status:-3,statusText:"Aborted",body:"Request "+s+" "+e+" Aborted"})}),Object.entries(n.headers).forEach(function(e){u.setRequestHeader(e[0],e[1])}),"include"===n.credentials&&(u.withCredentials=!0),u.open(s,a,!0),n.body&&u.send(n.body),n.timeout>0&&(i=setTimeout(function(){u.abort()},n.timeout))}))}catch(e){return Promise.reject(e)}};function O(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 E=function(e,t,r){try{return Promise.resolve(j(m,e,t,r)).then(function(n){return P(n,e,t,r)})}catch(e){return Promise.reject(e)}},R=function(e,t,r){try{return Promise.resolve(j(x,e,t,r)).then(function(n){return P(n,e,t,r)})}catch(e){return Promise.reject(e)}},k=/*#__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}(),H=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new T(t),this.agent=e,this.cache=new k(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}(),L=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)}},F=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)}},C=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 T(n);return Promise.resolve(x(e,u,d({},r,{method:"POST",body:s}))).then(function(t){return P(t,e,u,r)})}catch(e){return Promise.reject(e)}}(e,t,r,{baseURL:A.getConfig("baseURL"),logHandler:A.getConfig("logHandler"),errorHandler:A.getConfig("errorHandler"),requestHandler:A.getConfig("requestHandler"),messageHandler:A.getConfig("messageHandler"),responseHandler:A.getConfig("responseHandler")}))}catch(e){return Promise.reject(e)}};function U(e){return"fetch"in window?new H(E,e):new H(R,e)}var A=U(),D=A.setConfig,M=A.head,S=A.get,q=A.post,B=A.del,G=A.put,K=A.patch;export{U as NetRequest,B as del,S as get,y as getResponseRulesDescription,M as head,F as jsonp,L as jsonx,K as patch,q as post,G as put,D as setGlobalConfig,C 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)}var h=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:f(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 f(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var m=function(e,t,r){try{return Promise.resolve(h(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)}},g="data",v="message",y=function(e){var t=[],r=e.failed||{resolve:"json"};switch(t.push("- 当http状态码 <200 或者 >=400 时"),r.resolve){case"body":t.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":t.push(" 将响应解析为json,并读取 "+(r.messageField||v)+" 作为错误消息")}var n=e.ok||{resolve:"body"};switch(t.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":t.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":t.push(" 将响应解析为 json,读取 "+(n.dataField||g)+" 作为响应数据,读取 "+(n.messageField||v)+" 作为提示消息"),n.statusField&&t.push(" 当 "+n.statusField+" 为 "+(n.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&t.push(" 并忽略以下消息:"+n.ignoreMessage)}return t.join("\n")};function p(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function b(e){return e>=200&&e<400}var P=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=b(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 j(n,s,o,a){var i,u;if(n.status<0)return w({ok:!1,status:n.status,code:n.statusText,headers:{},message:"",data:null},n.method+" "+s+" "+n.statusText,n.method,s,o,a);b(n.status)||null==(u=o.get("errorHandler"))||u(n.status,n.method,s);var c,l,h,f,m,y=d({},(c=n.status,l=n.statusText,h=n.body,f=o.get("responseRule"),m=(null==a?void 0:a.responseRule)||f,b(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||g,f=i.messageField||v,m=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===d,u.code=y||o,u.data=h in c?c[h]:null,u.message=f in c?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:v},i={ok:!1,code:s,message:o,data:null};switch(a.resolve){case"body":i.message=p(o)||o;break;case"json":i.message=p(o)||function(n,s){if(void 0===s&&(s=v),!e(n))return"";var o,a=t(n);return a&&r(a)&&s in a?(o=a[s])?"string"==typeof o?o:JSON.stringify(o):"":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({},y),n.method,s),w(y,y.ok?y.message:n.method+" "+s+" ["+y.code+"] "+(y.message||n.statusText),n.method,s,o,a)}function w(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 T=/*#__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}(),x=function(e,t,r){try{return Promise.resolve(h(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:O(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 O(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 E=function(e,t,r){try{return Promise.resolve(P(m,e,t,r)).then(function(n){return j(n,e,t,r)})}catch(e){return Promise.reject(e)}},R=function(e,t,r){try{return Promise.resolve(P(x,e,t,r)).then(function(n){return j(n,e,t,r)})}catch(e){return Promise.reject(e)}},k=/*#__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}(),H=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new T(t),this.agent=e,this.cache=new k(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}(),L=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)}},F=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)}},C=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 T(n);return Promise.resolve(x(e,u,d({},r,{method:"POST",body:s}))).then(function(t){return j(t,e,u,r)})}catch(e){return Promise.reject(e)}}(e,t,r,{baseURL:A.getConfig("baseURL"),logHandler:A.getConfig("logHandler"),errorHandler:A.getConfig("errorHandler"),requestHandler:A.getConfig("requestHandler"),messageHandler:A.getConfig("messageHandler"),responseHandler:A.getConfig("responseHandler")}))}catch(e){return Promise.reject(e)}};function U(e){return"fetch"in window?new H(E,e):new H(R,e)}var A=U(),D=A.setConfig,M=A.head,S=A.get,q=A.post,B=A.del,G=A.put,K=A.patch;export{U as NetRequest,B as del,S as get,y as getResponseRulesDescription,M as head,F as jsonp,L as jsonx,K as patch,q as post,G as put,D as setGlobalConfig,C 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 s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=/*#__PURE__*/s(e),o=/*#__PURE__*/s(t),a="message";function i(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function u(e){return e>=200&&e<400}var c=function e(t,s,n,o,a){try{var i,c,l=a||0,h=Math.min(10,null!=(i=null==o?void 0:o.maxRetry)?i:n.get("maxRetry")),d=null!=(c=null==o?void 0:o.retryResolve)?c:n.get("retryResolve"),f=n.get("logHandler")||r.noop;f({type:"prepear",url:s,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(t(s,n,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:s,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:n.get("retryInterval");return Promise.resolve(r.sleep(Math.max(100,"function"==typeof p?p(l+1):p))).then(function(){return Promise.resolve(e(t,s,n,o,l+1))})})}catch(e){return Promise.reject(e)}};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 s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},l.apply(this,arguments)}function h(e,t,r,s,n,o){return!1!==(null==o?void 0:o.message)&&n.showMessage(!e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,s,t):t),e}function d(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var f=function(e,t,s){try{return Promise.resolve(c(g,e,t,s)).then(function(n){return function(e,t,s,n){var o,c;if(e.status<0)return h({ok:!1,status:e.status,code:e.statusText,headers:{},message:"",data:null},e.method+" "+t+" "+e.statusText,e.method,t,s,n);u(e.status)||null==(c=s.get("errorHandler"))||c(e.status,e.method,t);var d,f,g,m,v,y=l({},(d=e.status,f=e.statusText,g=e.body,m=s.get("responseRule"),v=(null==n?void 0:n.responseRule)||m,u(d)?function(e,t,s,n){var o=e||{resolve:"body"},i={ok:!0,code:s,message:"",data:null};if(202===t||204===t||!n)return i;if("body"===o.resolve)return i.data=r.isJsonLike(n)?r.parseJSON(n):n,i;var u=r.parseJSON(n);if(!u||!r.isStringRecord(u))return i.ok=!1,i.code="ResponseFormatError",i.message="响应内容无法格式化为 Object",i;var c=o.statusField,l=o.statusOKValue||"",h=o.dataField||"data",d=o.messageField||a,f=o.ignoreMessage||"";if(c&&!(c in u))return i.ok=!1,i.code="ResponseFieldMissing",i.message="响应内容找不到状态字段 "+c,i;var g=c?u[c]+"":"";return i.ok=!c||g===l,i.code=g||s,i.data=h in u?u[h]:null,i.message=d in u?u[d]+"":"",f&&i.message&&(Array.isArray(f)&&f.includes(i.message)||"string"==typeof f&&i.message===f)&&(i.message=""),i}(v.ok||m.ok,d,f,g):function(e,t,s){var n=e||{resolve:"json",messageField:a},o={ok:!1,code:t,message:s,data:null};switch(n.resolve){case"body":o.message=i(s)||s;break;case"json":o.message=i(s)||function(e,t){if(void 0===t&&(t=a),!r.isJsonLike(e))return"";var s,n=r.parseJSON(e);return n&&r.isStringRecord(n)&&t in n?(s=n[t])?"string"==typeof s?s:JSON.stringify(s):"":e}(s,n.messageField)}return o}(v.failed||m.failed,f,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=s.get("responseHandler"))||o(l({},y),e.method,t),h(y,y.ok?y.message:e.method+" "+t+" ["+y.code+"] "+(y.message||e.statusText),e.method,t,s,n)}(n,e,t,s)})}catch(e){return Promise.reject(e)}},g=function(e,t,s){try{var a=function(e,t,r){var s,n=Object.assign({method:"GET"},r),o=n.body instanceof FormData,a=o?"POST":n.method;"GET"!==a&&"HEAD"!==a&&"DELETE"!==a||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var i=Object.assign(o?{}:{"Content-Type":"application/json;charset=utf-8"},n.headers),u=n.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+"")}),null==(s=t.get("requestHandler"))||s(i,c,a,e),{method:a,body:d(n.body),params:c,headers:i,timeout:n.timeout||t.get("timeout"),credentials:n.credentials||t.get("credentials")}}(e,t,s);if(!r.isFullURL(e))return Promise.resolve({url:e,method:a.method,status:-2,statusText:"URLFormatError",headers:{},body:""});var i=/^https:\/\//i.test(e)?o.default:n.default,u=new URL(e),c=a.params;c instanceof Object&&Object.keys(c).forEach(function(e){return u.searchParams.set(e,c[e])});var l="HEAD"===a.method;return Promise.resolve(new Promise(function(t){var r=i.request(u,{headers:a.headers,method:a.method,timeout:a.timeout>0?a.timeout:void 0},function(r){var s=[];l||r.on("data",function(e){return s.push(e)}),r.on("end",function(){var n=Object.fromEntries(Object.entries(r.headers).map(function(e){var t=e[1];return[e[0].toLowerCase(),Array.isArray(t)?t.join(","):t]}));t({url:e,method:a.method,status:r.statusCode||-3,statusText:r.statusMessage||"Unknown",headers:n,body:l?"":Buffer.concat(s).toString("utf-8")})})});r.on("error",function(r){t({url:e,method:a.method,status:-1,statusText:r.name||"Unknown",body:r.message})}),a.body&&r.write(a.body),r.end()}))}catch(e){return Promise.reject(e)}},m=/*#__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}(),v=/*#__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}(),y=/*#__PURE__*/function(){function e(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 m(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,s){try{return Promise.resolve(function(e,t,s,n){if(t.ok&&!r.isEmpty(t.data)&&null!==n){var o=r.getTypeGuard(n,"响应数据未能正确识别");if(o.guard(t.data))return t;console.error("response type check faild",e,t.data),s.showMessage(!0,e+" "+o.message)}return t.data=null,t}(e,t,this.config,s))}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,s=Object.assign({},t||null);s.method="HEAD";var n=r.guard;return Promise.resolve(r.exec(e,s)).then(function(t){return n.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},t.get=function(e,t,r){try{var s,n=function(r){if(s)return r;var n=o.exec(e,a);o.cache.set(i,n);var u=o.guard;return Promise.resolve(n).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(n){var a=r.call(o,e,n,t||null);return s=1,a})}}();return Promise.resolve(c&&c.then?c.then(n):n(c))}catch(e){return Promise.reject(e)}},t.post=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="POST",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.del=function(e,t,r){try{var s=this,n=Object.assign({},r||null);n.method="DELETE";var o=s.guard;return Promise.resolve(s.exec(e,n)).then(function(r){return o.call(s,e,r,t||null)})}catch(e){return Promise.reject(e)}},t.put=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PUT",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PATCH",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function p(e){return new y(f,e)}var b=p(),j=b.setConfig,P=b.head,x=b.get,O=b.post,R=b.del,T=b.put,w=b.patch;exports.NetRequest=p,exports.del=R,exports.get=x,exports.head=P,exports.patch=w,exports.post=O,exports.put=T,exports.setGlobalConfig=j;
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),i="message";function a(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function u(e){return e>=200&&e<400}var c=function e(t,n,s,o,i){try{var a,c,l=i||0,h=Math.min(10,null!=(a=null==o?void 0:o.maxRetry)?a:s.get("maxRetry")),d=null!=(c=null==o?void 0:o.retryResolve)?c:s.get("retryResolve"),f=s.get("logHandler")||r.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(t(n,s,o)).then(function(i){var a,c=i.status,m=Date.now()-g,v="[cost "+m+"]["+c+"] "+(c<0?i.body:"");f({type:"finished",url:n,method:i.method,retry:l,maxRetry:h,message:0===l?"finish "+v:"retry "+l+"/"+h+" finish "+v,response:i,cost:m});var y=u(c);if(!h||"network"===d&&c>0||"status"===d&&y||l>=h)return i;var p=null!=(a=null==o?void 0:o.retryInterval)?a:s.get("retryInterval");return Promise.resolve(r.sleep(Math.max(100,"function"==typeof p?p(l+1):p))).then(function(){return Promise.resolve(e(t,n,s,o,l+1))})})}catch(e){return Promise.reject(e)}};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,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 d(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var f=function(e,t,n){try{return Promise.resolve(c(g,e,t,n)).then(function(s){return function(e,t,n,s){var o,c;if(e.status<0)return h({ok:!1,status:e.status,code:e.statusText,headers:{},message:"",data:null},e.method+" "+t+" "+e.statusText,e.method,t,n,s);u(e.status)||null==(c=n.get("errorHandler"))||c(e.status,e.method,t);var d,f,g,m,v,y=l({},(d=e.status,f=e.statusText,g=e.body,m=n.get("responseRule"),v=(null==s?void 0:s.responseRule)||m,u(d)?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 u=r.parseJSON(s);if(!u||!r.isStringRecord(u))return a.ok=!1,a.code="ResponseFormatError",a.message="响应内容无法格式化为 Object",a;var c=o.statusField,l=o.statusOKValue||"",h=o.dataField||"data",d=o.messageField||i,f=o.ignoreMessage||"";if(c&&!(c in u))return a.ok=!1,a.code="ResponseFieldMissing",a.message="响应内容找不到状态字段 "+c,a;var g=c?u[c]+"":"";return a.ok=!c||g===l,a.code=g||n,a.data=h in u?u[h]:null,a.message=d in u?u[d]+"":"",f&&a.message&&(Array.isArray(f)&&f.includes(a.message)||"string"==typeof f&&a.message===f)&&(a.message=""),a}(v.ok||m.ok,d,f,g):function(e,t,n){var s=e||{resolve:"json",messageField:i},o={ok:!1,code:t,message:n,data:null};switch(s.resolve){case"body":o.message=a(n)||n;break;case"json":o.message=a(n)||function(e,t){if(void 0===t&&(t=i),!r.isJsonLike(e))return"";var n,s=r.parseJSON(e);return s&&r.isStringRecord(s)&&t in s?(n=s[t])?"string"==typeof n?n:JSON.stringify(n):"":e}(n,s.messageField)}return o}(v.failed||m.failed,f,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(l({},y),e.method,t),h(y,y.ok?y.message:e.method+" "+t+" ["+y.code+"] "+(y.message||e.statusText),e.method,t,n,s)}(s,e,t,n)})}catch(e){return Promise.reject(e)}},g=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,i=o?"POST":s.method;"GET"!==i&&"HEAD"!==i&&"DELETE"!==i||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var a=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(a,c,i,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:i,body:d(s.body),params:c,headers:a,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 i=/^https:\/\//i.test(n)?o.default:s.default,a=new URL(n),u=t.params;u instanceof Object&&Object.keys(u).forEach(function(e){return a.searchParams.set(e,u[e])});var c="HEAD"===t.method;return new Promise(function(e){var r=i.request(a,{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:a.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:a.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)}},m=/*#__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}(),v=/*#__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}(),y=/*#__PURE__*/function(){function e(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 m(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,i);o.cache.set(a,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,i=Object.assign({},r||null);i.method="GET";var a=o.cache.getKey(e,i.params),u=o.cache.get(a),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var i=r.call(o,e,s,t||null);return n=1,i})}}();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 i=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return i.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 i=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return i.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 i=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return i.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function p(e){return new y(f,e)}var b=p(),j=b.setConfig,P=b.head,x=b.get,O=b.post,R=b.del,T=b.put,w=b.patch;exports.NetRequest=p,exports.del=R,exports.get=x,exports.head=P,exports.patch=w,exports.post=O,exports.put=T,exports.setGlobalConfig=j;
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";var h="message";function d(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function f(e){return e>=200&&e<400}var m=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"),m=n.get("logHandler")||o;m({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 g=Date.now();return Promise.resolve(t(r,n,s)).then(function(o){var i,u=o.status,c=Date.now()-g,v="[cost "+c+"]["+u+"] "+(u<0?o.body:"");m({type:"finished",url:r,method:o.method,retry:l,maxRetry:h,message:0===l?"finish "+v:"retry "+l+"/"+h+" finish "+v,response:o,cost:c});var y=f(u);if(!h||"network"===d&&u>0||"status"===d&&y||l>=h)return o;var p=null!=(i=null==s?void 0:s.retryInterval)?i:n.get("retryInterval");return Promise.resolve(a(Math.max(100,"function"==typeof p?p(l+1):p))).then(function(){return Promise.resolve(e(t,r,n,s,l+1))})})}catch(e){return Promise.reject(e)}};function g(){return g=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},g.apply(this,arguments)}function v(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 y(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var p=function(e,t,o){try{return Promise.resolve(m(b,e,t,o)).then(function(a){return function(e,t,o,a){var i,u;if(e.status<0)return v({ok:!1,status:e.status,code:e.statusText,headers:{},message:"",data:null},e.method+" "+t+" "+e.statusText,e.method,t,o,a);f(e.status)||null==(u=o.get("errorHandler"))||u(e.status,e.method,t);var c,l,m,y,p,b=g({},(c=e.status,l=e.statusText,m=e.body,y=o.get("responseRule"),p=(null==a?void 0:a.responseRule)||y,f(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,d=i.statusOKValue||"",f=i.dataField||"data",m=i.messageField||h,g=i.ignoreMessage||"";if(l&&!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var v=l?c[l]+"":"";return u.ok=!l||v===d,u.code=v||o,u.data=f in c?c[f]:null,u.message=m in c?c[m]+"":"",g&&u.message&&(Array.isArray(g)&&g.includes(u.message)||"string"==typeof g&&u.message===g)&&(u.message=""),u}(p.ok||y.ok,c,l,m):function(e,t,o){var a=e||{resolve:"json",messageField:h},i={ok:!1,code:t,message:o,data:null};switch(a.resolve){case"body":i.message=d(o)||o;break;case"json":i.message=d(o)||function(e,t){if(void 0===t&&(t=h),!r(e))return"";var o,a=n(e);return a&&s(a)&&t in a?(o=a[t])?"string"==typeof o?o:JSON.stringify(o):"":e}(o,a.messageField)}return i}(p.failed||y.failed,l,m)),{status:e.status,headers:Object.fromEntries(Object.entries(e.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return null==(i=o.get("responseHandler"))||i(g({},b),e.method,t),v(b,b.ok?b.message:e.method+" "+t+" ["+b.code+"] "+(b.message||e.statusText),e.method,t,o,a)}(a,e,t,o)})}catch(e){return Promise.reject(e)}},b=function(r,n,s){try{var o=function(e,t,r){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+"")}),null==(n=t.get("requestHandler"))||n(i,c,a,e),{method:a,body:y(s.body),params:c,headers:i,timeout:s.timeout||t.get("timeout"),credentials:s.credentials||t.get("credentials")}}(r,n,s);if(!i(r))return Promise.resolve({url:r,method:o.method,status:-2,statusText:"URLFormatError",headers:{},body:""});var a=/^https:\/\//i.test(r)?t:e,u=new URL(r),c=o.params;c instanceof Object&&Object.keys(c).forEach(function(e){return u.searchParams.set(e,c[e])});var l="HEAD"===o.method;return Promise.resolve(new Promise(function(e){var t=a.request(u,{headers:o.headers,method:o.method,timeout:o.timeout>0?o.timeout:void 0},function(t){var n=[];l||t.on("data",function(e){return n.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:r,method:o.method,status:t.statusCode||-3,statusText:t.statusMessage||"Unknown",headers:s,body:l?"":Buffer.concat(n).toString("utf-8")})})});t.on("error",function(t){e({url:r,method:o.method,status:-1,statusText:t.name||"Unknown",body:t.message})}),o.body&&t.write(o.body),t.end()}))}catch(e){return Promise.reject(e)}},j=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),P=/*#__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}(),T=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new P(t),this.agent=e,this.cache=new j(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this),this.head=this.head.bind(this)}var t=e.prototype;return t.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},t.guard=function(e,t,r){try{return Promise.resolve(function(e,t,r,n){if(t.ok&&!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 w(e){return new T(p,e)}var O=w(),x=O.setConfig,R=O.head,k=O.get,E=O.post,L=O.del,U=O.put,C=O.patch;export{w as NetRequest,L as del,k as get,R as head,C as patch,E as post,U as put,x 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 i,isFullURL as a,isEmpty as u,getTypeGuard as c,getFullURL as l}from"@seayoo-web/utils";var h="message";function d(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function f(e){return e>=200&&e<400}var m=function e(t,r,n,s,a){try{var u,c,l=a||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"),m=n.get("logHandler")||o;m({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 g=Date.now();return Promise.resolve(t(r,n,s)).then(function(o){var a,u=o.status,c=Date.now()-g,v="[cost "+c+"]["+u+"] "+(u<0?o.body:"");m({type:"finished",url:r,method:o.method,retry:l,maxRetry:h,message:0===l?"finish "+v:"retry "+l+"/"+h+" finish "+v,response:o,cost:c});var y=f(u);if(!h||"network"===d&&u>0||"status"===d&&y||l>=h)return o;var p=null!=(a=null==s?void 0:s.retryInterval)?a:n.get("retryInterval");return Promise.resolve(i(Math.max(100,"function"==typeof p?p(l+1):p))).then(function(){return Promise.resolve(e(t,r,n,s,l+1))})})}catch(e){return Promise.reject(e)}};function g(){return g=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},g.apply(this,arguments)}function v(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 y(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var p=function(e,t,o){try{return Promise.resolve(m(b,e,t,o)).then(function(i){return function(e,t,o,i){var a,u;if(e.status<0)return v({ok:!1,status:e.status,code:e.statusText,headers:{},message:"",data:null},e.method+" "+t+" "+e.statusText,e.method,t,o,i);f(e.status)||null==(u=o.get("errorHandler"))||u(e.status,e.method,t);var c,l,m,y,p,b=g({},(c=e.status,l=e.statusText,m=e.body,y=o.get("responseRule"),p=(null==i?void 0:i.responseRule)||y,f(c)?function(e,t,o,i){var a=e||{resolve:"body"},u={ok:!0,code:o,message:"",data:null};if(202===t||204===t||!i)return u;if("body"===a.resolve)return u.data=r(i)?n(i):i,u;var c=n(i);if(!c||!s(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=a.statusField,d=a.statusOKValue||"",f=a.dataField||"data",m=a.messageField||h,g=a.ignoreMessage||"";if(l&&!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var v=l?c[l]+"":"";return u.ok=!l||v===d,u.code=v||o,u.data=f in c?c[f]:null,u.message=m in c?c[m]+"":"",g&&u.message&&(Array.isArray(g)&&g.includes(u.message)||"string"==typeof g&&u.message===g)&&(u.message=""),u}(p.ok||y.ok,c,l,m):function(e,t,o){var i=e||{resolve:"json",messageField:h},a={ok:!1,code:t,message:o,data:null};switch(i.resolve){case"body":a.message=d(o)||o;break;case"json":a.message=d(o)||function(e,t){if(void 0===t&&(t=h),!r(e))return"";var o,i=n(e);return i&&s(i)&&t in i?(o=i[t])?"string"==typeof o?o:JSON.stringify(o):"":e}(o,i.messageField)}return a}(p.failed||y.failed,l,m)),{status:e.status,headers:Object.fromEntries(Object.entries(e.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return null==(a=o.get("responseHandler"))||a(g({},b),e.method,t),v(b,b.ok?b.message:e.method+" "+t+" ["+b.code+"] "+(b.message||e.statusText),e.method,t,o,i)}(i,e,t,o)})}catch(e){return Promise.reject(e)}},b=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,i=o?"POST":s.method;"GET"!==i&&"HEAD"!==i&&"DELETE"!==i||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var a=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(a,c,i,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:i,body:y(s.body),params:c,headers:a,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(!a(s))return{url:s,method:n.method,status:-2,statusText:"URLFormatError",headers:{},body:""};var o=/^https:\/\//i.test(s)?t:e,i=new URL(s),u=n.params;u instanceof Object&&Object.keys(u).forEach(function(e){return i.searchParams.set(e,u[e])});var c="HEAD"===n.method;return new Promise(function(e){var t=o.request(i,{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:i.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:i.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)}},j=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),P=/*#__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)&&!a(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}(),T=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new P(t),this.agent=e,this.cache=new j(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this),this.head=this.head.bind(this)}var t=e.prototype;return t.exec=function(e,t){try{return Promise.resolve(this.agent(e,this.config,t))}catch(e){return Promise.reject(e)}},t.guard=function(e,t,r){try{return Promise.resolve(function(e,t,r,n){if(t.ok&&!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,i);o.cache.set(a,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,i=Object.assign({},r||null);i.method="GET";var a=o.cache.getKey(e,i.params),u=o.cache.get(a),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var i=r.call(o,e,s,t||null);return n=1,i})}}();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 i=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return i.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 i=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return i.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 i=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return i.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function w(e){return new T(p,e)}var O=w(),x=O.setConfig,R=O.head,k=O.get,E=O.post,L=O.del,U=O.put,C=O.patch;export{w as NetRequest,L as del,k as get,R as head,C as patch,E as post,U as put,x 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 s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},t.apply(this,arguments)}var r="message";function s(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function n(e){return e>=200&&e<400}var o=function t(r,s,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")||e.noop;f({type:"prepear",url:s,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(r(s,o,a)).then(function(i){var u,c=i.status,m=Date.now()-g,v="[cost "+m+"]["+c+"] "+(c<0?i.body:"");f({type:"finished",url:s,method:i.method,retry:l,maxRetry:h,message:0===l?"finish "+v:"retry "+l+"/"+h+" finish "+v,response:i,cost:m});var y=n(c);if(!h||"network"===d&&c>0||"status"===d&&y||l>=h)return i;var p=null!=(u=null==a?void 0:a.retryInterval)?u:o.get("retryInterval");return Promise.resolve(e.sleep(Math.max(100,"function"==typeof p?p(l+1):p))).then(function(){return Promise.resolve(t(r,s,o,a,l+1))})})}catch(e){return Promise.reject(e)}};function a(e,t,r,s,n,o){return!1!==(null==o?void 0:o.message)&&n.showMessage(!e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,s,t):t),e}function i(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var u=function(i,u,l){try{return Promise.resolve(o(c,i,u,l)).then(function(o){return function(o,i,u,c){var l,h;if(o.status<0)return a({ok:!1,status:o.status,code:o.statusText,headers:{},message:"",data:null},o.method+" "+i+" "+o.statusText,o.method,i,u,c);n(o.status)||null==(h=u.get("errorHandler"))||h(o.status,o.method,i);var d,f,g,m,v,y=t({},(d=o.status,f=o.statusText,g=o.body,m=u.get("responseRule"),v=(null==c?void 0:c.responseRule)||m,n(d)?function(t,s,n,o){var a=t||{resolve:"body"},i={ok:!0,code:n,message:"",data:null};if(202===s||204===s||!o)return i;if("body"===a.resolve)return i.data=e.isJsonLike(o)?e.parseJSON(o):o,i;var u=e.parseJSON(o);if(!u||!e.isStringRecord(u))return i.ok=!1,i.code="ResponseFormatError",i.message="响应内容无法格式化为 Object",i;var c=a.statusField,l=a.statusOKValue||"",h=a.dataField||"data",d=a.messageField||r,f=a.ignoreMessage||"";if(c&&!(c in u))return i.ok=!1,i.code="ResponseFieldMissing",i.message="响应内容找不到状态字段 "+c,i;var g=c?u[c]+"":"";return i.ok=!c||g===l,i.code=g||n,i.data=h in u?u[h]:null,i.message=d in u?u[d]+"":"",f&&i.message&&(Array.isArray(f)&&f.includes(i.message)||"string"==typeof f&&i.message===f)&&(i.message=""),i}(v.ok||m.ok,d,f,g):function(t,n,o){var a=t||{resolve:"json",messageField:r},i={ok:!1,code:n,message:o,data:null};switch(a.resolve){case"body":i.message=s(o)||o;break;case"json":i.message=s(o)||function(t,s){if(void 0===s&&(s=r),!e.isJsonLike(t))return"";var n,o=e.parseJSON(t);return o&&e.isStringRecord(o)&&s in o?(n=o[s])?"string"==typeof n?n:JSON.stringify(n):"":t}(o,a.messageField)}return i}(v.failed||m.failed,f,g)),{status:o.status,headers:Object.fromEntries(Object.entries(o.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return null==(l=u.get("responseHandler"))||l(t({},y),o.method,i),a(y,y.ok?y.message:o.method+" "+i+" ["+y.code+"] "+(y.message||o.statusText),o.method,i,u,c)}(o,i,u,l)})}catch(e){return Promise.reject(e)}},c=function(r,s,n){try{var o=function(e,t,r){var s,n=Object.assign({method:"GET"},r),o=n.body instanceof FormData,a=o?"POST":n.method;"GET"!==a&&"HEAD"!==a&&"DELETE"!==a||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var u=Object.assign(o?{}:{"Content-Type":"application/json;charset=utf-8"},n.headers),c=n.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+"")}),null==(s=t.get("requestHandler"))||s(u,l,a,e),{method:a,body:i(n.body),params:l,headers:u,timeout:n.timeout||t.get("timeout"),credentials:n.credentials||t.get("credentials")}}(r,s,n),a="PATCH"===o.method?"POST":o.method,u=e.addParamsToString(s.getFullUrl(r),o.params);return globalThis.wx?Promise.resolve(new Promise(function(e){wx.request({url:u,data:o.body,header:o.headers,method:a,dataType:"string",responseType:"text",fail:function(){e({url:u,method:a,status:-1,statusText:"NetworkError",body:"Network Error"})},success:function(r){var s;e({url:u,method:a,status:r.statusCode,statusText:r.statusCode+"",headers:t({},r.header),body:(s=r.data,"string"==typeof s?s:s instanceof ArrayBuffer&&"TextDecoder"in globalThis?(new TextDecoder).decode(s):JSON.stringify(s))})}})})):Promise.resolve({url:u,method:a,status:-2,statusText:"NotSupport",body:"NotFound namespace of wx"})}catch(e){return Promise.reject(e)}},l=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),h=/*#__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}(),d=/*#__PURE__*/function(){function t(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new h(t),this.agent=e,this.cache=new l(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this),this.head=this.head.bind(this)}var 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,s){try{return Promise.resolve(function(t,r,s,n){if(r.ok&&!e.isEmpty(r.data)&&null!==n){var o=e.getTypeGuard(n,"响应数据未能正确识别");if(o.guard(r.data))return r;console.error("response type check faild",t,r.data),s.showMessage(!0,t+" "+o.message)}return r.data=null,r}(t,r,this.config,s))}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,s=Object.assign({},t||null);s.method="HEAD";var n=r.guard;return Promise.resolve(r.exec(e,s)).then(function(t){return n.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},r.get=function(e,t,r){try{var s,n=function(r){if(s)return r;var n=o.exec(e,a);o.cache.set(i,n);var u=o.guard;return Promise.resolve(n).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(n){var a=r.call(o,e,n,t||null);return s=1,a})}}();return Promise.resolve(c&&c.then?c.then(n):n(c))}catch(e){return Promise.reject(e)}},r.post=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="POST",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.del=function(e,t,r){try{var s=this,n=Object.assign({},r||null);n.method="DELETE";var o=s.guard;return Promise.resolve(s.exec(e,n)).then(function(r){return o.call(s,e,r,t||null)})}catch(e){return Promise.reject(e)}},r.put=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PUT",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.patch=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PATCH",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},t}();function f(e){return new d(u,e)}var g=f(),m=g.setConfig,v=g.head,y=g.get,p=g.post,b=g.del,T=g.put;exports.NetRequest=f,exports.del=b,exports.get=y,exports.head=v,exports.post=p,exports.put=T,exports.setGlobalConfig=m;
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 s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},t.apply(this,arguments)}var r="message";function s(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function n(e){return e>=200&&e<400}var o=function t(r,s,o,i,a){try{var u,c,l=a||0,h=Math.min(10,null!=(u=null==i?void 0:i.maxRetry)?u:o.get("maxRetry")),d=null!=(c=null==i?void 0:i.retryResolve)?c:o.get("retryResolve"),f=o.get("logHandler")||e.noop;f({type:"prepear",url:s,method:(null==i?void 0:i.method)||"GET",retry:l,maxRetry:h,message:0===l?"start":"retry "+l+"/"+h+" start",options:i});var g=Date.now();return Promise.resolve(r(s,o,i)).then(function(a){var u,c=a.status,m=Date.now()-g,v="[cost "+m+"]["+c+"] "+(c<0?a.body:"");f({type:"finished",url:s,method:a.method,retry:l,maxRetry:h,message:0===l?"finish "+v:"retry "+l+"/"+h+" finish "+v,response:a,cost:m});var y=n(c);if(!h||"network"===d&&c>0||"status"===d&&y||l>=h)return a;var p=null!=(u=null==i?void 0:i.retryInterval)?u:o.get("retryInterval");return Promise.resolve(e.sleep(Math.max(100,"function"==typeof p?p(l+1):p))).then(function(){return Promise.resolve(t(r,s,o,i,l+1))})})}catch(e){return Promise.reject(e)}};function i(e,t,r,s,n,o){return!1!==(null==o?void 0:o.message)&&n.showMessage(!e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,s,t):t),e}function a(e){if(e)return e instanceof Blob||e instanceof ArrayBuffer||e instanceof FormData||e instanceof URLSearchParams||"string"==typeof e?e:JSON.stringify(e)}var u=function(a,u,l){try{return Promise.resolve(o(c,a,u,l)).then(function(o){return function(o,a,u,c){var l,h;if(o.status<0)return i({ok:!1,status:o.status,code:o.statusText,headers:{},message:"",data:null},o.method+" "+a+" "+o.statusText,o.method,a,u,c);n(o.status)||null==(h=u.get("errorHandler"))||h(o.status,o.method,a);var d,f,g,m,v,y=t({},(d=o.status,f=o.statusText,g=o.body,m=u.get("responseRule"),v=(null==c?void 0:c.responseRule)||m,n(d)?function(t,s,n,o){var i=t||{resolve:"body"},a={ok:!0,code:n,message:"",data:null};if(202===s||204===s||!o)return a;if("body"===i.resolve)return a.data=e.isJsonLike(o)?e.parseJSON(o):o,a;var u=e.parseJSON(o);if(!u||!e.isStringRecord(u))return a.ok=!1,a.code="ResponseFormatError",a.message="响应内容无法格式化为 Object",a;var c=i.statusField,l=i.statusOKValue||"",h=i.dataField||"data",d=i.messageField||r,f=i.ignoreMessage||"";if(c&&!(c in u))return a.ok=!1,a.code="ResponseFieldMissing",a.message="响应内容找不到状态字段 "+c,a;var g=c?u[c]+"":"";return a.ok=!c||g===l,a.code=g||n,a.data=h in u?u[h]:null,a.message=d in u?u[d]+"":"",f&&a.message&&(Array.isArray(f)&&f.includes(a.message)||"string"==typeof f&&a.message===f)&&(a.message=""),a}(v.ok||m.ok,d,f,g):function(t,n,o){var i=t||{resolve:"json",messageField:r},a={ok:!1,code:n,message:o,data:null};switch(i.resolve){case"body":a.message=s(o)||o;break;case"json":a.message=s(o)||function(t,s){if(void 0===s&&(s=r),!e.isJsonLike(t))return"";var n,o=e.parseJSON(t);return o&&e.isStringRecord(o)&&s in o?(n=o[s])?"string"==typeof n?n:JSON.stringify(n):"":t}(o,i.messageField)}return a}(v.failed||m.failed,f,g)),{status:o.status,headers:Object.fromEntries(Object.entries(o.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return null==(l=u.get("responseHandler"))||l(t({},y),o.method,a),i(y,y.ok?y.message:o.method+" "+a+" ["+y.code+"] "+(y.message||o.statusText),o.method,a,u,c)}(o,a,u,l)})}catch(e){return Promise.reject(e)}},c=function(r,s,n){try{return Promise.resolve(function(e,t,r){try{var s,n=Object.assign({method:"GET"},r),o=n.body instanceof FormData,i=o?"POST":n.method;"GET"!==i&&"HEAD"!==i&&"DELETE"!==i||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var u=Object.assign(o?{}:{"Content-Type":"application/json;charset=utf-8"},n.headers),c=n.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==(s=t.get("requestHandler"))?void 0:s(u,l,i,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:i,body:a(n.body),params:l,headers:u,timeout:n.timeout||t.get("timeout"),credentials:n.credentials||t.get("credentials")}})}catch(e){return Promise.reject(e)}}(r,s,n)).then(function(n){var o="PATCH"===n.method?"POST":n.method,i=e.addParamsToString(s.getFullUrl(n.url||r),n.params);return globalThis.wx?new Promise(function(e){wx.request({url:i,data:n.body,header:n.headers,method:o,dataType:"string",responseType:"text",fail:function(){e({url:i,method:o,status:-1,statusText:"NetworkError",body:"Network Error"})},success:function(r){var s;e({url:i,method:o,status:r.statusCode,statusText:r.statusCode+"",headers:t({},r.header),body:(s=r.data,"string"==typeof s?s:s instanceof ArrayBuffer&&"TextDecoder"in globalThis?(new TextDecoder).decode(s):JSON.stringify(s))})}})}):{url:i,method:o,status:-2,statusText:"NotSupport",body:"NotFound namespace of wx"}})}catch(e){return Promise.reject(e)}},l=/*#__PURE__*/function(){function e(e){void 0===e&&(e=500),this.ttl=void 0,this.cache=void 0,this.cache={},this.ttl=Math.max(e,0)}var t=e.prototype;return t.getKey=function(e,t){return e+Object.keys(t||{}).sort().map(function(e){return e+"#"+(null==t?void 0:t[e])}).join(",")},t.updateTTL=function(e){this.ttl=Math.max(e,0)},t.get=function(e){if(0===this.ttl)return null;var t=this.cache[e];return t?t.ttl<Date.now()?(delete this.cache[e],null):t.res:null},t.set=function(e,t){0!==this.ttl&&(this.cache[e]={ttl:Date.now()+this.ttl,res:t})},e}(),h=/*#__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}(),d=/*#__PURE__*/function(){function t(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new h(t),this.agent=e,this.cache=new l(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this),this.head=this.head.bind(this)}var 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,s){try{return Promise.resolve(function(t,r,s,n){if(r.ok&&!e.isEmpty(r.data)&&null!==n){var o=e.getTypeGuard(n,"响应数据未能正确识别");if(o.guard(r.data))return r;console.error("response type check faild",t,r.data),s.showMessage(!0,t+" "+o.message)}return r.data=null,r}(t,r,this.config,s))}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,s=Object.assign({},t||null);s.method="HEAD";var n=r.guard;return Promise.resolve(r.exec(e,s)).then(function(t){return n.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},r.get=function(e,t,r){try{var s,n=function(r){if(s)return r;var n=o.exec(e,i);o.cache.set(a,n);var u=o.guard;return Promise.resolve(n).then(function(r){return u.call(o,e,r,t||null)})},o=this,i=Object.assign({},r||null);i.method="GET";var a=o.cache.getKey(e,i.params),u=o.cache.get(a),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(n){var i=r.call(o,e,n,t||null);return s=1,i})}}();return Promise.resolve(c&&c.then?c.then(n):n(c))}catch(e){return Promise.reject(e)}},r.post=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="POST",o.body=t;var i=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return i.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.del=function(e,t,r){try{var s=this,n=Object.assign({},r||null);n.method="DELETE";var o=s.guard;return Promise.resolve(s.exec(e,n)).then(function(r){return o.call(s,e,r,t||null)})}catch(e){return Promise.reject(e)}},r.put=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PUT",o.body=t;var i=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return i.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},r.patch=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PATCH",o.body=t;var i=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return i.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},t}();function f(e){return new d(u,e)}var g=f(),m=g.setConfig,v=g.head,y=g.get,p=g.post,b=g.del,P=g.put;exports.NetRequest=f,exports.del=b,exports.get=y,exports.head=v,exports.post=p,exports.put=P,exports.setGlobalConfig=m;
package/dist/wx.mjs CHANGED
@@ -1 +1 @@
1
- import{isJsonLike as e,parseJSON as t,isStringRecord as r,noop as s,sleep as n,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 s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},l.apply(this,arguments)}var h="message";function d(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function f(e){return e>=200&&e<400}var g=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"),g=o.get("logHandler")||s;g({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 m=Date.now();return Promise.resolve(t(r,o,a)).then(function(s){var i,u=s.status,c=Date.now()-m,v="[cost "+c+"]["+u+"] "+(u<0?s.body:"");g({type:"finished",url:r,method:s.method,retry:l,maxRetry:h,message:0===l?"finish "+v:"retry "+l+"/"+h+" finish "+v,response:s,cost:c});var y=f(u);if(!h||"network"===d&&u>0||"status"===d&&y||l>=h)return s;var p=null!=(i=null==a?void 0:a.retryInterval)?i:o.get("retryInterval");return Promise.resolve(n(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 m(e,t,r,s,n,o){return!1!==(null==o?void 0:o.message)&&n.showMessage(!e.ok,"function"==typeof(null==o?void 0:o.message)?o.message(e,r,s,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(s,n,o){try{return Promise.resolve(g(p,s,n,o)).then(function(a){return function(s,n,o,a){var i,u;if(s.status<0)return m({ok:!1,status:s.status,code:s.statusText,headers:{},message:"",data:null},s.method+" "+n+" "+s.statusText,s.method,n,o,a);f(s.status)||null==(u=o.get("errorHandler"))||u(s.status,s.method,n);var c,g,v,y,p,b=l({},(c=s.status,g=s.statusText,v=s.body,y=o.get("responseRule"),p=(null==a?void 0:a.responseRule)||y,f(c)?function(s,n,o,a){var i=s||{resolve:"body"},u={ok:!0,code:o,message:"",data:null};if(202===n||204===n||!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||"",f=i.dataField||"data",g=i.messageField||h,m=i.ignoreMessage||"";if(l&&!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var v=l?c[l]+"":"";return u.ok=!l||v===d,u.code=v||o,u.data=f in c?c[f]:null,u.message=g in c?c[g]+"":"",m&&u.message&&(Array.isArray(m)&&m.includes(u.message)||"string"==typeof m&&u.message===m)&&(u.message=""),u}(p.ok||y.ok,c,g,v):function(s,n,o){var a=s||{resolve:"json",messageField:h},i={ok:!1,code:n,message:o,data:null};switch(a.resolve){case"body":i.message=d(o)||o;break;case"json":i.message=d(o)||function(s,n){if(void 0===n&&(n=h),!e(s))return"";var o,a=t(s);return a&&r(a)&&n in a?(o=a[n])?"string"==typeof o?o:JSON.stringify(o):"":s}(o,a.messageField)}return i}(p.failed||y.failed,g,v)),{status:s.status,headers:Object.fromEntries(Object.entries(s.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return null==(i=o.get("responseHandler"))||i(l({},b),s.method,n),m(b,b.ok?b.message:s.method+" "+n+" ["+b.code+"] "+(b.message||s.statusText),s.method,n,o,a)}(a,s,n,o)})}catch(e){return Promise.reject(e)}},p=function(e,t,r){try{var s=function(e,t,r){var s,n=Object.assign({method:"GET"},r),o=n.body instanceof FormData,a=o?"POST":n.method;"GET"!==a&&"HEAD"!==a&&"DELETE"!==a||void 0!==n.body&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);var i=Object.assign(o?{}:{"Content-Type":"application/json;charset=utf-8"},n.headers),u=n.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+"")}),null==(s=t.get("requestHandler"))||s(i,c,a,e),{method:a,body:v(n.body),params:c,headers:i,timeout:n.timeout||t.get("timeout"),credentials:n.credentials||t.get("credentials")}}(e,t,r),n="PATCH"===s.method?"POST":s.method,a=o(t.getFullUrl(e),s.params);return globalThis.wx?Promise.resolve(new Promise(function(e){wx.request({url:a,data:s.body,header:s.headers,method:n,dataType:"string",responseType:"text",fail:function(){e({url:a,method:n,status:-1,statusText:"NetworkError",body:"Network Error"})},success:function(t){var r;e({url:a,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))})}})})):Promise.resolve({url:a,method:n,status:-2,statusText:"NotSupport",body:"NotFound namespace of wx"})}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}(),P=/*#__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}(),T=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new P(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,r){try{return Promise.resolve(function(e,t,r,s){if(t.ok&&!a(t.data)&&null!==s){var n=i(s,"响应数据未能正确识别");if(n.guard(t.data))return t;console.error("response type check faild",e,t.data),r.showMessage(!0,e+" "+n.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,s=Object.assign({},t||null);s.method="HEAD";var n=r.guard;return Promise.resolve(r.exec(e,s)).then(function(t){return n.call(r,e,t,null)})}catch(e){return Promise.reject(e)}},t.get=function(e,t,r){try{var s,n=function(r){if(s)return r;var n=o.exec(e,a);o.cache.set(i,n);var u=o.guard;return Promise.resolve(n).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(n){var a=r.call(o,e,n,t||null);return s=1,a})}}();return Promise.resolve(c&&c.then?c.then(n):n(c))}catch(e){return Promise.reject(e)}},t.post=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="POST",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.del=function(e,t,r){try{var s=this,n=Object.assign({},r||null);n.method="DELETE";var o=s.guard;return Promise.resolve(s.exec(e,n)).then(function(r){return o.call(s,e,r,t||null)})}catch(e){return Promise.reject(e)}},t.put=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PUT",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},t.patch=function(e,t,r,s){try{var n=this,o=Object.assign({},s||null);o.method="PATCH",o.body=t;var a=n.guard;return Promise.resolve(n.exec(e,o)).then(function(t){return a.call(n,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function j(e){return new T(y,e)}var x=j(),w=x.setConfig,O=x.head,R=x.get,k=x.post,E=x.del,L=x.put;export{j as NetRequest,E as del,R as get,O as head,k as post,L as put,w as setGlobalConfig};
1
+ import{isJsonLike as e,parseJSON as t,isStringRecord as r,noop as n,sleep as s,addParamsToString as o,isEmpty as i,getTypeGuard as a,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)}var h="message";function d(e){var t=e.match(/<title>([^<]+)<\/title>/i);if(t)return t[1];var r=e.match(/<message>([^<]+)<\/message>/i);return r?r[1]:""}function f(e){return e>=200&&e<400}var g=function e(t,r,o,i,a){try{var u,c,l=a||0,h=Math.min(10,null!=(u=null==i?void 0:i.maxRetry)?u:o.get("maxRetry")),d=null!=(c=null==i?void 0:i.retryResolve)?c:o.get("retryResolve"),g=o.get("logHandler")||n;g({type:"prepear",url:r,method:(null==i?void 0:i.method)||"GET",retry:l,maxRetry:h,message:0===l?"start":"retry "+l+"/"+h+" start",options:i});var m=Date.now();return Promise.resolve(t(r,o,i)).then(function(n){var a,u=n.status,c=Date.now()-m,v="[cost "+c+"]["+u+"] "+(u<0?n.body:"");g({type:"finished",url:r,method:n.method,retry:l,maxRetry:h,message:0===l?"finish "+v:"retry "+l+"/"+h+" finish "+v,response:n,cost:c});var y=f(u);if(!h||"network"===d&&u>0||"status"===d&&y||l>=h)return n;var p=null!=(a=null==i?void 0:i.retryInterval)?a: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,i,l+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(n,s,o){try{return Promise.resolve(g(p,n,s,o)).then(function(i){return function(n,s,o,i){var a,u;if(n.status<0)return m({ok:!1,status:n.status,code:n.statusText,headers:{},message:"",data:null},n.method+" "+s+" "+n.statusText,n.method,s,o,i);f(n.status)||null==(u=o.get("errorHandler"))||u(n.status,n.method,s);var c,g,v,y,p,b=l({},(c=n.status,g=n.statusText,v=n.body,y=o.get("responseRule"),p=(null==i?void 0:i.responseRule)||y,f(c)?function(n,s,o,i){var a=n||{resolve:"body"},u={ok:!0,code:o,message:"",data:null};if(202===s||204===s||!i)return u;if("body"===a.resolve)return u.data=e(i)?t(i):i,u;var c=t(i);if(!c||!r(c))return u.ok=!1,u.code="ResponseFormatError",u.message="响应内容无法格式化为 Object",u;var l=a.statusField,d=a.statusOKValue||"",f=a.dataField||"data",g=a.messageField||h,m=a.ignoreMessage||"";if(l&&!(l in c))return u.ok=!1,u.code="ResponseFieldMissing",u.message="响应内容找不到状态字段 "+l,u;var v=l?c[l]+"":"";return u.ok=!l||v===d,u.code=v||o,u.data=f in c?c[f]:null,u.message=g in c?c[g]+"":"",m&&u.message&&(Array.isArray(m)&&m.includes(u.message)||"string"==typeof m&&u.message===m)&&(u.message=""),u}(p.ok||y.ok,c,g,v):function(n,s,o){var i=n||{resolve:"json",messageField:h},a={ok:!1,code:s,message:o,data:null};switch(i.resolve){case"body":a.message=d(o)||o;break;case"json":a.message=d(o)||function(n,s){if(void 0===s&&(s=h),!e(n))return"";var o,i=t(n);return i&&r(i)&&s in i?(o=i[s])?"string"==typeof o?o:JSON.stringify(o):"":n}(o,i.messageField)}return a}(p.failed||y.failed,g,v)),{status:n.status,headers:Object.fromEntries(Object.entries(n.headers||{}).map(function(e){var t=e[1];return[e[0].toLowerCase(),t]}))});return null==(a=o.get("responseHandler"))||a(l({},b),n.method,s),m(b,b.ok?b.message:n.method+" "+s+" ["+b.code+"] "+(b.message||n.statusText),n.method,s,o,i)}(i,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,i=o?"POST":s.method;"GET"!==i&&"HEAD"!==i&&"DELETE"!==i||void 0!==s.body&&(console.warn("request body is invalid with method get, head, delete"),delete s.body);var a=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(a,c,i,e)).then(function(e){return{url:"string"==typeof e&&e?e:void 0,method:i,body:v(s.body),params:c,headers:a,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)}},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}(),P=/*#__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}(),T=/*#__PURE__*/function(){function e(e,t){this.agent=void 0,this.config=void 0,this.cache=void 0,this.config=new P(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,r){try{return Promise.resolve(function(e,t,r,n){if(t.ok&&!i(t.data)&&null!==n){var s=a(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,i);o.cache.set(a,s);var u=o.guard;return Promise.resolve(s).then(function(r){return u.call(o,e,r,t||null)})},o=this,i=Object.assign({},r||null);i.method="GET";var a=o.cache.getKey(e,i.params),u=o.cache.get(a),c=function(){if(u){var r=o.guard;return Promise.resolve(u).then(function(s){var i=r.call(o,e,s,t||null);return n=1,i})}}();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 i=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return i.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 i=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return i.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 i=s.guard;return Promise.resolve(s.exec(e,o)).then(function(t){return i.call(s,e,t,r||null)})}catch(e){return Promise.reject(e)}},e}();function j(e){return new T(y,e)}var x=j(),w=x.setConfig,O=x.head,R=x.get,k=x.post,E=x.del,L=x.put;export{j as NetRequest,E as del,R as get,O as head,k as post,L as put,w as setGlobalConfig};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seayoo-web/request",
3
- "version": "0.9.2",
3
+ "version": "1.0.1",
4
4
  "description": "requst tools for seayoo web",
5
5
  "type": "module",
6
6
  "main": "dist/index.mjs",
@@ -47,19 +47,19 @@
47
47
  "commit-msg": "node scripts/verifyCommit.mjs $1"
48
48
  },
49
49
  "devDependencies": {
50
- "@types/node": "^20.6.0",
51
- "@typescript-eslint/eslint-plugin": "^6.7.0",
52
- "@typescript-eslint/parser": "^6.7.0",
53
- "eslint": "^8.49.0",
50
+ "@types/node": "^20.9.0",
51
+ "@typescript-eslint/eslint-plugin": "^6.10.0",
52
+ "@typescript-eslint/parser": "^6.10.0",
53
+ "eslint": "^8.53.0",
54
54
  "eslint-config-prettier": "^9.0.0",
55
- "eslint-plugin-prettier": "^5.0.0",
55
+ "eslint-plugin-prettier": "^5.0.1",
56
56
  "lint-staged": "^14.0.1",
57
57
  "microbundle": "^0.15.1",
58
- "rimraf": "^5.0.1",
58
+ "rimraf": "^5.0.5",
59
59
  "simple-git-hooks": "^2.9.0",
60
60
  "typescript": "^5.2.2"
61
61
  },
62
62
  "dependencies": {
63
- "@seayoo-web/utils": "^1.3.4"
63
+ "@seayoo-web/utils": "^1.7.0"
64
64
  }
65
65
  }