@seayoo-web/request 3.3.3 → 3.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +53 -53
- package/dist/node.js +17 -17
- package/dist/{request.fetch-CHbeHmeX.js → request.fetch-B3ED8nRu.js} +6 -6
- package/dist/retry-CdUkYrFw.js +606 -0
- package/dist/wx.js +23 -23
- package/package.json +2 -6
- package/dist/index.cjs +0 -2
- package/dist/node.cjs +0 -1
- package/dist/request.fetch-Ce3_4Yuj.cjs +0 -1
- package/dist/retry-BXoyQlSJ.js +0 -1191
- package/dist/retry-D_7OkloZ.cjs +0 -3
- package/dist/wx.cjs +0 -1
package/dist/retry-D_7OkloZ.cjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
"use strict";const l=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:Function("return this")();function d(t){return typeof t=="function"}function R(t){return typeof t=="object"&&t!==null}function K(){return"wx"in l&&R(l.wx)&&"getSystemInfo"in l.wx&&d(l.wx.getSystemInfo)}const k={wx:K(),fetch:"fetch"in l&&d(l.fetch),window:"window"in l&&R(l.window)&&!K(),requestAnimationFrame:"requestAnimationFrame"in l&&d(l.requestAnimationFrame),localStorage:"localStorage"in l&&R(l.localStorage)&&"getItem"in l.localStorage&&d(l.localStorage.getItem),sessionStorage:"sessionStorage"in l&&R(l.sessionStorage)&&"getItem"in l.sessionStorage&&d(l.sessionStorage.getItem),File:"File"in l&&d(l.File),Blob:"Blob"in l&&d(l.Blob),Proxy:"Proxy"in l&&d(l.Proxy),Request:"Request"in l&&d(l.Request),FormData:"FormData"in l&&d(l.FormData),TextDecoder:"TextDecoder"in l&&d(l.TextDecoder),ResizeObserver:"ResizeObserver"in l&&d(l.ResizeObserver),AbortController:"AbortController"in l&&d(l.AbortController),URLSearchParams:"URLSearchParams"in l&&d(l.URLSearchParams),EventSource:"EventSource"in l&&d(l.EventSource)};function re(t){return new Promise(e=>setTimeout(e,Math.max(0,t)))}function Q(){}function X(t,e){const s={log:console.log.bind(console),error:console.error.bind(console),warn:console.warn.bind(console)},n=`[${t}]`;return["log","error","warn"].forEach(r=>{const o=console[r];s[r]=(...i)=>{o.apply(console,[n,...i])}}),s}function oe(t){const e=t||"CustomError";return class extends Error{constructor(s){super(s),Object.defineProperty(this,"name",{value:e,enumerable:!1,configurable:!0}),"setPrototypeOf"in Object&&Object.setPrototypeOf(this,new.target.prototype),"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,this.constructor)}}}const ie=/^(?:https?:)?\/\/.+$/i,ae=/^https?:\/\/.+$/i,le=/^\{[\d\D]*\}$/,ue=/^\[[\d\D]*\]$/;function ce(t){return typeof t=="string"}function x(t,e=!1){return e?ie.test(t):ae.test(t)}function he(t){return t==null}function Z(t,...e){return t!==null&&typeof t=="object"&&!(t instanceof Map)&&!(t instanceof Set)&&!(t instanceof WeakMap)&&!(t instanceof WeakSet)&&!Array.isArray(t)&&e.every(s=>s in t)}function y(t,...e){if(!t||typeof t!="object")return!1;const s=Object.getPrototypeOf(t);return s!==Object.prototype&&s!==null?!1:e.every(n=>n in t)}function U(t,e){return Array.isArray(t)&&t.every(s=>e(s))}function N(t){if(typeof t!="number"||Number.isNaN(t)||!Number.isFinite(t))return!1;if(Number.isInteger(t))return Number.isSafeInteger(t);if(t===0)return!0;const e=Math.abs(t);return e>=Number.EPSILON&&e<=Number.MAX_SAFE_INTEGER}function Y(t){return le.test(t)||ue.test(t)}function fe(t,e=20){const s=Math.max(e,10),n=[...t];return n.length<=s?t:n.slice(0,s-3).join("")+"..."}function F(t,e){try{const s=JSON.parse(t);return e?e(s)?s:null:s}catch{return null}}""+Math.random().toString(32).slice(2);X("LoadUtils");async function de(t){return await new Promise(function(e){const s=document.getElementsByTagName("head")[0],n=document.createElement("script");n.setAttribute("type","text/javascript"),n.setAttribute("charset","utf-8"),n.onload=function(){s.removeChild(n),e(!0)},n.onerror=function(){s.removeChild(n),e(!1)},n.setAttribute("src",t),s.appendChild(n)})}function z(t){return Object.getOwnPropertyNames(t).forEach(function(e){delete t[e]}),t}function me(t,e="数据未能正确识别"){return typeof t=="function"?{guard:t,message:e}:{guard:t.guard,message:t.message||e}}function _e(t,e=""){return!e||x(t,!0)?V(t):(V(e)+"/"+t).replace(/\/{2,}/g,"/").replace(/:\//,"://")}function V(t){return x(t,!0)?t.startsWith("http")?t:("location"in globalThis?location.protocol:"https:")+t:("location"in globalThis?location.origin:"http://127.0.0.1")+"/"+t.replace(/^\/+/,"")}function pe(t,e){const s={};return(t.match(/([^=&#?]+)=[^&#]*/g)||[]).forEach(function(n){const r=n.split("="),o=r[0],i=decodeURIComponent(r[1]||"");s[o]!==void 0?s[o]+=","+i:s[o]=i}),e!==!0?s[e]||"":s}function ge(t,e){if(e){if(e===!0)return t.replace(/\?[^#]*/,"")}else return t;const s=t.split("#"),n=s[0].split("?"),r=n[0],o=n.length>1?n[1]:"",i=s.length>1?"#"+s[1]:"",u=typeof e=="string"?[e]:Array.isArray(e)?e:[];return!u.length||!o?s[0]+i:(u.map(h=>h.replace(/([\\(){}[\]^$+\-*?|])/g,"\\$1")),(r+"?"+o.replace(new RegExp("(?:^|&)(?:"+u.join("|")+")=[^&$]+","g"),"").replace(/^&/,"")).replace(/\?$/,"")+i)}function be(t,e,s=!1){const n=typeof e=="string"?e:Object.keys(e).map(i=>`${i}=${encodeURIComponent(e[i])}`).join("&");if(!n)return t;const r=t.split("#");s&&(r[0]=ge(r[0],(n.match(/([^=&#?]+)=[^&#]+/g)||[]).map(i=>i.replace(/=.+$/,""))));const o=r[0].indexOf("?")+1?"&":"?";return(r[0]+o+n+(r.length>1?"#"+r[1]:"")).replace(/\?&/,"?")}const p=X("Validator");function j(t){return t?`"${fe(t).replace(/"/g,'\\"')}"`:"empty string"}function S(t){return typeof t=="object"&&t&&"constructor"in t&&typeof t.constructor=="function"?t.constructor.name||"ClassInstance":Object.prototype.toString.call(t).replace(/(?:.+ |]$)/g,"")}function O(t){return typeof t=="bigint"}function a(t){return new Error(`${t?`${t}()`:"method"} is not allowed after locked`)}class M{_ps={};_allow=[];_reject=[];_locked=!1;_opt=!1;_null=!1;pattern(e,s){if(this._locked)throw a("pattern");return this._ps[`#${e||"custom"}`]=s,this}url(e=!1){if(this._locked)throw a("url");return this._ps.url=e?/^(?:https?:)?\/\/.+$/i:/^https?:\/\/.+$/i,this}dataUri(){if(this._locked)throw a("dataUri");return this._ps.dataUri=/^data:[a-z]+\/[a-z]+;base64,[\w+/=]+$/,this}enum(...e){if(this._locked)throw a("enum");const s=e[0];return U(e,ce)?(this._allow=e,z(this._ps)):y(s)&&(this._allow=Object.values(s).map(n=>`${n}`),z(this._ps)),this}disallow(...e){return this._reject.push(...e),this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new M;return e._ps={...this._ps},e._allow=[...this._allow],e._reject=[...this._reject],e._locked=!1,e}validate(e,s=p.warn){if(e===void 0)return this._opt||(s("should be a string, but got undefined"),!1);if(e===null)return this._null||(s("should be a string, but got null"),!1);if(typeof e!="string")return s(`should be a string, but got ${typeof e}`),!1;if(this._allow.length>0)return this._allow.includes(e)||(s(`${j(e)} is not allowed, just support ${this._allow.map(j).join(", ")}`),!1);if(this._reject.length>0&&this._reject.some(r=>typeof r=="string"?r===e:r.test(e)))return s(`${j(e)} is not allowed`),!1;const n=Object.keys(this._ps);return n.length>0&&!n.some(r=>{const o=this._ps[r];return o instanceof RegExp?o.test(e):o(e)})?(s(`${j(e)} is not match pattern ${n.join(" | ")}`),!1):!0}}class C{_int=!1;_min=-1/0;_max=1/0;_allow=[];_reject=[];_infinite=!1;_unsafe=!1;_nan=!1;_locked=!1;_opt=!1;_null=!1;int(){if(this._locked)throw a("int");return this._int=!0,this}min(e){if(this._locked)throw a("min");return Number.isNaN(e)||(this._min=e),this}max(e){if(this._locked)throw a("max");return Number.isNaN(e)||(this._max=e),this}allowNaN(){if(this._locked)throw a("allowNaN");return this._nan=!0,this}allowInfinity(){if(this._locked)throw a("allowInfinity");return this._infinite=!0,this._unsafe=!0,this}unsafe(){if(this._locked)throw a("unsafe");return this._unsafe=!0,this}enum(...e){if(this._locked)throw a("enum");const s=e[0];return U(e,N)?(this._allow=e,this._reject=[]):y(s)&&(this._allow=Object.values(s).map(n=>N(n)?n:null).filter(n=>n!==null),this._reject=[]),this}disallow(...e){if(this._locked)throw a("disallow");return this._reject.push(...e),this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new C;return e._int=this._int,e._min=this._min,e._max=this._max,e._allow=[...this._allow],e._reject=[...this._reject],e._infinite=this._infinite,e._unsafe=this._unsafe,e._nan=this._nan,e._locked=!1,e}validate(e,s=p.warn){return e===void 0?this._opt||(s("should be a number, but got undefined"),!1):e===null?this._null||(s("should be a number, but got null"),!1):typeof e!="number"?(s(`should be a number, but got ${typeof e}`),!1):Number.isNaN(e)?this._nan||(s("should be a number, but got NaN"),!1):!Number.isFinite(e)&&!this._infinite?(s("should be a number, but got Infinity"),!1):this._allow.length>0?this._allow.includes(e)||(s(`${e} is not allowed, just support ${this._allow.join(", ")}`),!1):this._reject.length>0&&this._reject.includes(e)?(s(`${e} is not allowed`),!1):this._int&&Math.ceil(e)!==e?(s(`${e} is not an integer`),!1):!N(e)&&!this._unsafe?(s(`${e} is not a safe number`),!1):e>=this._min&&e<=this._max||(s(`${e} is not in range [${this._min}, ${this._max}]`),!1)}}class P{_min=null;_max=null;_allow=[];_reject=[];_locked=!1;_opt=!1;_null=!1;min(e){if(this._locked)throw a("min");return this._min=e,this}max(e){if(this._locked)throw a("max");return this._max=e,this}enum(...e){if(this._locked)throw a("enum");const s=e[0];return U(e,O)?(this._allow=e,this._reject=[]):y(s)&&(this._allow=Object.values(s).map(n=>O(n)?n:null).filter(n=>n!==null),this._reject=[]),this}disallow(...e){if(this._locked)throw a("disallow");return this._reject.push(...e),this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new P;return e._min=this._min,e._max=this._max,e._allow=[...this._allow],e._reject=[...this._reject],e._locked=!1,e}validate(e,s=p.warn){return e===void 0?this._opt||(s("should be a bigint, but got undefined"),!1):e===null?this._null||(s("should be a bigint, but got null"),!1):O(e)?this._allow.length>0?this._allow.includes(e)||(s(`${e} is not allowed, just support ${this._allow.join(", ")}`),!1):this._reject.length>0&&this._reject.includes(e)?(s(`${e} is not allowed`),!1):(this._min!==null?e>=this._min:!0)&&(this._max!==null?e<=this._max:!0)||(s(`${e} is not in range [${this._min===null?-1/0:this._min}, ${this._max===null?1/0:this._max}]`),!1):(s(`should be a bigint, but got ${typeof e}`),!1)}}class q{_locked=!1;_opt=!1;_null=!1;optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new q}validate(e,s=p.warn){return e===void 0?this._opt||(s("should be a boolean, but got undefined"),!1):e===null?this._null||(s("should be a boolean, but got null"),!1):typeof e!="boolean"?(s(`should be a boolean, but got ${typeof e}`),!1):!0}}class v{_shape;_plain=!1;_locked=!1;_opt=!1;_null=!1;constructor(e){this._shape=e}plain(){if(this._locked)throw a("plain");return this._plain=!0,this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}get shape(){return{...this._shape}}clone(){const e=new v(this._shape);return e._plain=this._plain,e._locked=!1,e}match(e,s){return e in this._shape?this._shape[e].validate(s,Q):!1}validate(e,s=p.warn){return e===void 0?this._opt||(s("should be a object, but got undefined"),!1):e===null?this._null||(s("should be a object, but got null"),!1):Z(e)?this._plain&&!y(e)?(s(`should be a plain object, but got ${S(e)}`),!1):Object.keys(this._shape).every(n=>this._shape[n].validate(e[n],(...r)=>{s(`[.${String(n)}]`,...r)})):(s(`should be a object, but got ${S(e)}`),!1)}}class I{_val;_locked=!1;_opt=!1;_null=!1;constructor(e){this._val=e}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new I(this._val)}validate(e,s=p.warn){return e===void 0?this._opt||(s("should be a record, but got undefined"),!1):e===null?this._null||(s("should be a record, but got null"),!1):y(e)?Object.keys(e).every(n=>this._val.validate(e[n],(...r)=>{s(`[:${n}]`,...r)})):(s(`should be a record, but got ${S(e)}`),!1)}}class L{_val;_min=0;_max=1/0;_locked=!1;_opt=!1;_null=!1;constructor(e){this._val=e}min(e){if(this._locked)throw a("min");return this._min=e,this}max(e){if(this._locked)throw a("max");return this._max=e,this}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){const e=new L(this._val);return e._min=this._min,e._max=this._max,e._locked=!1,e}validate(e,s=p.warn){return e===void 0?this._opt||(s("should be a array, but got undefined"),!1):e===null?this._null||(s("should be a array, but got null"),!1):Array.isArray(e)?e.length<this._min||e.length>this._max?(this._min===this._max?s(`should be a array with length ${this._min}`):s(`should be a array with length between ${this._min} and ${this._max}`),!1):e.every((n,r)=>this._val.validate(n,(...o)=>{s(`[${r}]`,...o)})):(s(`should be a array, but got ${typeof e}`),!1)}}class D{_vs;_locked=!1;_opt=!1;_null=!1;constructor(...e){this._vs=e}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new D(...this._vs)}validate(e,s=p.warn){return e===void 0?this._opt||(s("should be a tuple, but got undefined"),!1):e===null?this._null||(s("should be a tuple, but got null"),!1):Array.isArray(e)?e.length!==this._vs.length?(s(`should be a tuple with length ${this._vs.length}, but got ${e.length}`),!1):this._vs.every((n,r)=>n.validate(e[r],(...o)=>{s(`[idx:${r}]`,...o)})):(s(`should be a tuple, but got ${typeof e}`),!1)}}class B{_vs;_key="";_locked=!1;_opt=!1;_null=!1;constructor(...e){this._vs=e}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}key(e){if(this._locked)throw a("key");return this._vs.every(s=>s instanceof v)?this._key=e:p.warn("union type key can only be used when all validators are ObjectValidator"),this}satisfies(){return this}lock(){return this._locked=!0,this}get validators(){return[...this._vs]}clone(){const e=new B(...this._vs);return e._key=this._key,e._locked=!1,e}validate(e,s=p.warn){if(e===void 0)return this._opt||(s("should be a union, but got undefined"),!1);if(e===null)return this._null||(s("should be a union, but got null"),!1);if(this._key&&Z(e)&&e){const r=e[this._key];if(r===void 0)return s(`key field "${this._key}" is not found`,e),!1;const o=this._vs.find(i=>i instanceof v&&i.match(this._key,r));return o?o.validate(e,s):(s(`key field "${this._key}" value is match union definition`,r),!1)}const n=this._vs.some(r=>r.validate(e,Q));return n||s("value is not match union definition",e),n}}class E{_name="";_guard;_locked=!1;_opt=!1;_null=!1;constructor(e,s){this._name=e,this._guard=s}optional(){if(this._locked)throw a("optional");return this._opt=!0,this}maybeNull(){if(this._locked)throw a("maybeNull");return this._null=!0,this}lock(){return this._locked=!0,this}clone(){return new E(this._name,this._guard)}validate(e,s=p.warn){const n=this._name||"custom type";return e===void 0?this._opt||(s(`should be ${n}, but got undefined`),!1):e===null?this._null||(s(`should be ${n}, but got null`),!1):this._guard(e)||(s(`custom validation${this._name?`(${this._name})`:""} failed`),!1)}}function ye(t,e){if(typeof t=="string"){if(!e)throw new Error("custom type guard must be defined");return new E(t,e)}return new E("",t)}const we={shape(t){return t},define(t){return t},guard(t){return function(e){return t.validate(e)}},object(t){return new v(t)},record(t){return new I(t)},array(t){return new L(t)},tuple(...t){return new D(...t)},union(...t){return new B(...t)},string(){return new M},bool(){return new q},number(){return new C},bigint(){return new P},custom:ye,unknown(){return{validate(t){return!0}}},never(){return{validate(t){return!1}}}},ke=t=>y(t)&&Object.keys(t).length===0;we.custom("EmptyObject",ke);function ve(t){const e=t.match(/(?:\?|&)([^=]+)(?:&|$)/g);return e?e.join("").replace(/(?:\?|^&+|&+$)/g,"").replace(/&{2}/g,"&").split("&").sort():[]}class $e{ttl;cache;timer=null;loopCheck(){if(Object.keys(this.cache).forEach(s=>{this.cache[s].ttl<Date.now()&&delete this.cache[s]}),Object.keys(this.cache).length===0){this.timer=null;return}this.timer=setTimeout(this.loopCheck,5e3)}constructor(e=500){this.cache={},this.ttl=Math.max(e,0),this.loopCheck=this.loopCheck.bind(this)}getKey(e,s,n,r){if(e.toLowerCase()!=="get"&&!r)return"";const o=e.toLowerCase(),i=s.replace(/#.+/,""),u=i.replace(/\?.+/g,"");if(r)try{const c=r()||"";return c?`${u}_${o}_${c}`:""}catch(c){return console.warn("[RequestCache] cacheResolve error",s,n,c),""}const h=Object.assign(pe(i,!0),n),m=ve(i),f=Object.keys(h).sort().map(c=>`${c}#${h[c]}`);return`${u}_${o}_${f.join(",")}_${m.join(",")}`}updateTTL(e){this.ttl=Math.max(e,0)}get(e,s){if(Math.max(s??this.ttl,0)===0)return null;const r=this.cache[e];return r?r.ttl<Date.now()?(delete this.cache[e],null):r.res:null}set(e,s,n){const r=Math.max(n??this.ttl,0);r!==0&&(this.cache[e]={ttl:Date.now()+r,res:s},this.timer===null&&(this.timer=setTimeout(this.loopCheck,5e3)))}del(e){this.cache[e]&&delete this.cache[e]}}class ee{config={baseURL:"/",maxRetry:0,retryInterval:100,retryResolve:"network",timeout:1e4,cacheTTL:500,credentials:"same-origin",defaultTypeGuardMessage:"响应数据未能正确识别",responseRule:{ok:{resolve:"body"},failed:{resolve:"json",messageField:"message"}}};constructor(e){e&&this.set(e)}set(e){if(e.baseURL&&!/^\/.+/.test(e.baseURL)&&!x(e.baseURL))throw console.warn("baseURL 需要以 / 开头,或者是完整的 url 地址"),new Error("BaseURLError");Object.assign(this.config,e)}get(e){return this.config[e]}getFullUrl(e){return _e(e,this.config.baseURL)}showMessage(e,s,n,r){this.config.messageHandler&&s&&this.config.messageHandler(e,s,n,r)}}const H={UnexpectResponse:"UnexpectResponse",Aborted:"Aborted",Unknown:"Unknown",NetworkError:"NetworkError",Timeout:"Timeout",NotSupport:"NotSupport",URLFormatError:"URLFormatError"};function je(t,e,s,n){if(e.ok&&!he(e.data)&&n){const r=me(n,s.get("defaultTypeGuardMessage"));return r.guard(e.data)||(e.code=H.UnexpectResponse,s.showMessage(!0,`${t} ${r.message}`,e.code,e.status),console.error(e.code,t,e.data),e.data=null,e.message=r.message),e}return e}class Re{agent;config;cache;constructor(e,s){this.config=new ee(s),this.agent=e,this.cache=new $e(this.config.get("cacheTTL")),this.setConfig=this.setConfig.bind(this),this.getConfig=this.getConfig.bind(this),this.request=this.request.bind(this),this.get=this.get.bind(this),this.post=this.post.bind(this),this.del=this.del.bind(this),this.patch=this.patch.bind(this),this.put=this.put.bind(this),this.head=this.head.bind(this)}async request(e,s){const n=this.cache.getKey(s?.method||"GET",e,s?.params,s?.cacheResolve);if(n){const r=this.cache.get(n,s?.cacheTTL);if(r)return await r}try{const r=this.agent(e,this.config,s);n&&this.cache.set(n,r,s?.cacheTTL);const o=await r;return(!o.ok||o.status<0)&&this.cache.del(n),o}catch(r){return console.error("RequestError",r),{ok:!1,status:-9,code:H.Unknown,message:r instanceof Error?`${r.message}
|
|
2
|
-
${r.stack||""}`:String(r),headers:{},data:null}}}async guard(e,s,n){return je(e,s,this.config,n)}setConfig(e){this.config.set(e),this.cache.updateTTL(this.config.get("cacheTTL"))}getConfig(e){return this.config.get(e)}async head(e,s){const n=Object.assign({},s||null);return n.method="HEAD",this.guard(e,await this.request(e,n),null)}async get(e,s,n){const r=Object.assign({},n||null);r.method="GET";const o=this.request(e,r);return this.guard(e,await o,s||null)}async post(e,s,n,r){const o=Object.assign({},r||null);return o.method="POST",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}async del(e,s,n){const r=Object.assign({},n||null);return r.method="DELETE",this.guard(e,await this.request(e,r),s||null)}async put(e,s,n,r){const o=Object.assign({},r||null);return o.method="PUT",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}async patch(e,s,n,r){const o=Object.assign({},r||null);return o.method="PATCH",o.body=s||{},this.guard(e,await this.request(e,o),n||null)}}async function Ee(t,e,s){const n=Object.assign({method:"GET"},s),r=k.FormData?n.body instanceof FormData:!1,o=r&&n.method!=="POST"&&n.method!=="PUT"?"POST":n.method,i=o==="GET"||o==="HEAD"||o==="DELETE";i&&n.body!==void 0&&(console.warn("request body is invalid with method get, head, delete"),delete n.body);const u=Object.assign(r||i?{}:{"Content-Type":k.Blob&&n.body instanceof Blob?n.body.type||"application/octet-stream":"application/json;charset=utf-8"},n.headers),h=n.params||{},m={};Object.keys(h).forEach(_=>{h[_]!==void 0&&(m[_]=xe(h[_]))});const f=e.getFullUrl(t),c=Ne(n.body),g=n.timeout||e.get("timeout"),b=await async function(){const _=e.get("requestTransformer");if(_)return await _({headers:u,params:m,method:o,url:f,body:c})}(),w=typeof b=="string"&&b?b:f;return e.get("logHandler")?.({type:"ready",url:w,method:o,headers:u,timeout:g,body:c}),{url:w,method:o,body:c,params:m,headers:u,timeout:g,abort:n.abort,credentials:n.credentials||e.get("credentials")}}function xe(t){return typeof t=="string"?t:Array.isArray(t)?t.join(","):t+""}function Ne(t){if(t)return typeof t=="string"||k.URLSearchParams&&t instanceof URLSearchParams||t instanceof ArrayBuffer||k.Blob&&t instanceof Blob||k.FormData&&t instanceof FormData?t:JSON.stringify(t)}const te="data",$="message";function Oe(t,e,s,n,r){const o=r||n;return G(t)?Ce(o.ok||n.ok,t,e,s):Se(o.failed||n.failed,e,s)}const Fe=function(t){const e=[],s=t.failed||{resolve:"json"};switch(e.push("- 当http状态码 <200 或者 >=400 时"),s.resolve){case"body":e.push(" 将响应内容格式化为字符串并作为错误消息");break;case"json":e.push(" 将响应解析为json,并读取 "+(s.messageField||$)+" 作为错误消息");break}const n=t.ok||{resolve:"body"};switch(e.push("- 当http状态码 >=200 并且 <400 时"),n.resolve){case"body":e.push(" 将响应尝试解析为 json,并作为数据内容返回");break;case"json":e.push(" 将响应解析为 json,读取 "+(n.dataField||te)+" 作为响应数据,读取 "+(n.messageField||$)+" 作为提示消息"),n.statusField&&e.push(" 当 "+n.statusField+" 为 "+(n.statusOKValue||"空值")+" 时是成功提示,否则是错误消息"),n.ignoreMessage&&e.push(" 并忽略以下消息:"+n.ignoreMessage);break}return e.join(`
|
|
3
|
-
`)};function Se(t,e,s){const n=t||{resolve:"json",messageField:$},r={ok:!1,code:e,message:s,data:null};switch(n.resolve){case"body":r.message=W(s)||s;break;case"json":const{code:o,message:i}=Te(s,n.converter,n.statusField,n.messageField);r.code=o||e,r.message=W(s)||i;break}return r}function Te(t,e,s,n=$){if(!Y(t))return{message:""};const r=A(F(t),e);return!r||!y(r)?{message:t}:{code:s?T(r,s):"",message:T(r,n)||t}}function T(t,e){const s=Array.isArray(e)?e:[e];for(const n of s)if(n in t)return Ae(t[n]);return""}function Ae(t){return t?typeof t=="string"?t:JSON.stringify(t):""}const Ue=/<title>([^<]+)<\/title>/i,Me=/<message>([^<]+)<\/message>/i;function W(t){const e=t.match(Ue);if(e)return e[1];const s=t.match(Me);return s?s[1]:""}function Ce(t,e,s,n){const r=t||{resolve:"body"},o={ok:!0,code:s,message:"",data:null};if(e===204||!n)return o;if(r.resolve==="body")return o.data=Y(n)?A(F(n),t.converter):n,o;const i=A(F(n),t.converter);if(!i||!y(i))return o.ok=!1,o.code="ResponseFormatError",o.message="响应内容无法格式化为 Object",o;const u=r.statusField,h=r.statusOKValue||"",m=r.dataField||te,f=r.messageField||$,c=r.ignoreMessage||"";if(u&&!(u in i))return o.ok=!1,o.code="ResponseFieldMissing",o.message="响应内容找不到状态字段 "+u,o;const g=u?i[u]+"":"";return o.ok=u?g===h:!0,o.code=g||s,o.data=m===!0?i:m in i?i[m]:null,o.message=T(i,f),c&&o.message&&(Array.isArray(c)&&c.includes(o.message)||typeof c=="string"&&o.message===c)&&(o.message=""),o}function G(t){return t>=200&&t<400}function A(t,e){return e?typeof e=="function"?e(t):(console.warn('工具不再支持 "camelize", "snakify" 参数,请自行提供函数来转化 body 内容'),t):t}const Pe=oe("APIError");function qe(t){const e={};for(const r in t.headers)(r.startsWith("x-")||r.includes("trace")||r.includes("server")||/\b(?:id|uuid)\b/.test(r))&&(e[r]=t.headers[r]);const s=t.url.replace(/^(?:https?:)?\/*/i,"").replace(/\?.+/,""),n=t.status<0?"unknown":t.status;return{sentryError:new Pe(`${s} | ${n}${t.code?` | ${t.code}`:""}`),sentryTags:{...e,status:n,method:t.method,code:t.code||"unknown",message:t.message||"empty"},sentryExtra:{url:t.url,responseBody:t.body||"empty",responseHeaders:t.headers,rawError:t.error}}}function se(t){return t.reduce((e,[s,n])=>(s&&(e[s]=n||""),e),{})}function Ie(t,e,s,n){const r=t.status,o=t.method,i=se(Object.entries(t.headers||{}).map(([b,w])=>[b.toLowerCase(),w])),{ok:u,code:h,data:m,message:f}=Oe(r,t.statusText,t.body,s.get("responseRule"),n?.responseRule);if(!G(r)){const b=qe({url:t.url,method:t.method,status:r,code:h,message:f,body:t.body,headers:i,error:t.rawError});(s.get("errorHandler")||Le)({url:e,method:o,status:r,code:h,message:f,headers:i,rawError:t.rawError,responseBody:t.body,...b})}if(r<0)return J({ok:!1,status:r,code:t.statusText,headers:{},message:"",data:null},`${o} ${e} ${t.statusText}`,o,e,s,n);const c={ok:u,data:m,code:h,message:f,status:r,headers:i};s.get("responseHandler")?.({...c},o,e);const g=u?f:f||t.statusText;return J(c,g,o,e,s,n)}function J(t,e,s,n,r,o){const i=r.get("message"),u=i===!1||o?.message===!1?!1:o?.message||i;if(u!==!1){const h=typeof u=="function"?u(t,s,n,e):e;h instanceof Error?r.showMessage(!0,h.message,t.code,t.status):h&&typeof h=="object"&&"message"in h?r.showMessage(!1,h.message,t.code,t.status):r.showMessage(!t.ok,h,t.code,t.status)}return t}function Le(t){const e={};for(const s in t)s.startsWith("sentry")||(e[s]=t[s]);console.error("RequestError",e)}async function ne(t,e,s,n,r){const o=r||0,i=Math.max(0,Math.min(10,n?.maxRetry??s.get("maxRetry")??0)),u=n?.retryResolve??s.get("retryResolve"),h=s.get("logHandler");h?.({type:"prepare",url:e,method:n?.method||"GET",retry:o,maxRetry:i,message:o===0?"start":`retry ${o}/${i} start`,headers:n?.headers,options:n});const m=Date.now(),f=await t(e,s,n),c=f.status,g=Date.now()-m,b=`[cost ${g}][${c}] ${c<0?f.body:""}`;h?.({type:"finished",url:e,method:f.method,retry:o,maxRetry:i,message:o===0?`finish ${b}`:`retry ${o}/${i} finish ${b}`,response:f,headers:f.headers,cost:g});const w=G(c);if(!i||o>=i||u==="network"&&c>0||u==="status"&&w||Array.isArray(u)&&!u.includes(c)||typeof u=="function"&&u(f,o)!==!0)return f;const _=n?.retryInterval??s.get("retryInterval")??100;return await re(Math.max(100,_==="2EB"?Math.pow(2,o)*100:typeof _=="function"?_(o+1,{url:e,status:c,method:f.method})||0:_)),await ne(t,e,s,n,o+1)}exports.At=x;exports.NetRequestHandler=Re;exports.RequestGlobalConfig=ee;exports.RequestInternalError=H;exports.St=k;exports.ce=de;exports.convertOptions=Ee;exports.fromEntries=se;exports.getResponseRulesDescription=Fe;exports.handleResponse=Ie;exports.pe=be;exports.retryRequest=ne;
|
package/dist/wx.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./retry-D_7OkloZ.cjs"),l=async function(e,o,u){return t.handleResponse(await t.retryRequest(p,e,o,u),e,o,u)},p=async function(e,o,u){const s=await t.convertOptions(e,o,u),a=s.method==="PATCH"?"POST":s.method,c=t.pe(s.url,s.params);return t.St.wx?new Promise(d=>{wx.request({url:c,data:s.body,header:s.headers,method:a,dataType:"string",responseType:"text",fail(){d({url:c,method:a,status:-1,statusText:t.RequestInternalError.Unknown,body:""})},success(n){d({url:c,method:a,status:n.statusCode,statusText:n.statusCode+"",headers:{...n.header},body:s.method==="HEAD"||n.statusCode===204?"":f(n.data)})}})}):{url:c,method:a,status:-1,statusText:t.RequestInternalError.NotSupport,body:""}};function f(e){return typeof e=="string"?e:e instanceof ArrayBuffer&&t.St.TextDecoder?new TextDecoder().decode(e):JSON.stringify(e)}function i(e){return new t.NetRequestHandler(l,e)}const r=i(),R=r.setConfig,y=r.head,g=r.get,q=r.post,h=r.del,x=r.put;exports.RequestInternalError=t.RequestInternalError;exports.getResponseRulesDescription=t.getResponseRulesDescription;exports.NetRequest=i;exports.del=h;exports.get=g;exports.head=y;exports.post=q;exports.put=x;exports.setGlobalConfig=R;
|