ryoko
Version:
a requestion lib based on the fetch native api
17 lines (14 loc) • 10.4 kB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ryoko=e.ryoko||{})}(this,(function(e){"use strict";const t=void 0!==globalThis?globalThis:void 0!==self?self:void 0!==window?window:void 0!==global?global:{},r=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","DataView"].concat("ArrayBuffer"),o=["Blob","FormData","URLSearchParams","ReadableStream","String","Null"].concat(r),n=["method","mode","credentials","headers","cache","integrity","redirect","referrer","referrerPolicy","keepalive","window"],s=["get","post","put","options","delete","patch","head"],i=["blob","arrayBuffer","formData","json","text"],a=["omit","same-origin","include"],c=Object.prototype.hasOwnProperty,l=(e,t)=>c.call(e,t),u=Object.assign,d=function(e,t,r){},f=/(([^:]+:)\/\/(([^:\/\?#]+)(:\d+)?))(\/[^?#]*)?(\?[^#]*)?(#.*)?/,h=(e,t)=>(Object(t)===t&&Object.keys(t).forEach((r=>{void 0===e[r]?e[r]=t[r]:h(e[r],t[r])})),e);function b(e,...t){let r;return e=Object(e),r=1!==t.length?t.reduce(((e,t)=>h(e,t)),{}):t[0],h(e,r)}const{toString:p}=Object.prototype,m=e=>p.call(e).slice(8,-1),y=["String","Number","Undefined","Boolean","Null","Symbol","Function"].reduce(((e,t)=>(e[t]=e=>typeof e===t.toLowerCase(),e)),{});y.Array=Array.isArray,y.emptyArray=e=>y.Array(e)&&e.length<1,y.Object=e=>"object"==typeof e&&null!==e&&"constructor"in e&&e.constructor===Object,y.PlainObject=e=>"object"==typeof e&&null!==e&&"Object"===m(e),y.emptyObject=e=>y.PlainObject(e)&&Object.keys(e).length<1;const g="AbortController"in t&&y.Function(AbortController),v=e=>{let t={};const r=e.match(/^.*\?/);if(r){const o=e.replace(r[0],"");o&&(t=o.split("&").reduce(((e,t)=>{const r=t.split("=");return e[r[0]]=r[1],e}),t))}return t},T=(e,t=!1)=>{let r={};for(let[o,n]of e.entries()){r[t?o.toLowerCase():o]=n}return r};class w{constructor(){this.init()}init(){this.callbacks=[]}use(e,t){return this.callbacks.push({success:e,failure:t})-1}eject(e){this.callbacks[e]&&(this.callbacks[e]=void 0)}traverse(e){this.callbacks.forEach((t=>null!=t&&e(t)))}}const R={prefixUrl:"",url:"",timeout:0,fetch:t.fetch,onDefer:d,verifyStatus:e=>e<300&&e>=200,method:"GET",responseType:"text",beforeRequest:d,afterResponse:d,credentials:"same-origin",params:{}};
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */function A(e,t,r,o){return new(r||(r=Promise))((function(n,s){function i(e){try{c(o.next(e))}catch(e){s(e)}}function a(e){try{c(o.throw(e))}catch(e){s(e)}}function c(e){var t;e.done?n(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(i,a)}c((o=o.apply(e,t||[])).next())}))}const j=function(e,r){const{body:o,status:n,statusText:s,headers:i}=e,a=o;let c,l;if(void 0!==r){let e=0;const o=Number(i.get("content-length"))||0;let n;const s=t=>{n.read().then((({value:n,done:i})=>{if(i)return void(t&&t.close());e+=(null==n?void 0:n.length)||0;const a={total:o,received:e,percent:0===o?0:e/o,buffer:n};r.call(this,a),t&&t.enqueue(n),s()}))};try{const e=a.tee();[c,l]=e,n=l.getReader(),s()}catch(e){l=a,n=l.getReader(),c=new t.ReadableStream({start(e){s(e)}})}}else c=a;return new Response(c,{status:n,statusText:s,headers:i})};function k(){const{tokenStore:e}=O;for(let t of e.keys())E(t)}function E(e){const{tokenStore:t}=O,r=t.get(e);if(void 0===r)return!1;for(let e of r)e("The user aborted a request");return r.clear(),t.delete(e),!0}class O{static createToken(){const{tokenStore:e,abortName:t}=O;return Symbol(t+e.size)}}O.abortName="RyokoAbortTokenizer",O.tokenStore=new Map;class S extends Error{constructor(e,t={}){super(e),this.name="RyokoError",this.isRyokoError=!0,b(this,t)}toString(){return`${this.name}: ${this.message}`}toJSON(){const{message:e,name:t,number:r,description:o,fileName:n,lineNumber:s,stack:i,columnNumber:a,config:c,status:l}=this;return{message:e,number:r,description:o,fileName:n,lineNumber:s,stack:i,columnNumber:a,name:t,config:c,status:l}}}const x=[Error,URIError,TypeError,RangeError,ReferenceError,SyntaxError,S],P=x.map((e=>new RegExp(e.name,"i"))),q=(e,t="Error",r)=>{if("console"===t)return void console.warn(e,`options:${r}`);let o=P.findIndex((e=>e.test(t)));throw!~o&&(o=0),new x[o](e)},$=(e,t,r)=>{if(t=decodeURIComponent(t),e=decodeURIComponent(e).trim(),f.test(t)?e.length>0&&q("the combination of 'baseURL' and 'url' is invalid!","URIError"):t=`${e.replace(/\/$/,"")}/${t.replace(/^\//,"")}`,null==r)return t;const o=v(t);"string"==typeof r?r=v(r):"URLSearchParams"===m(r)?r=T(r):y.PlainObject(r)||q("the type of 'params' parameter must be one of the thres options: 'String'、'PlainObject'、'URLSearchParams'","TypeError");return t+((e,t=!1)=>y.emptyObject(e)?"":`${t?"?":""}${Object.entries(e).map((e=>e.join("="))).join("&")}`)(b(o,r),!0)},N=e=>{const t=m(e);if("Undefined"!==t)return o.some((e=>e===t))?e:y.PlainObject(e)?JSON.stringify(e):void q("The original or converted value of 'data' parameter is invalid","TypeError")},U=(e,t)=>A(void 0,void 0,void 0,(function*(){const{statusText:r,status:o,headers:n}=e,s=T(n,!0),a={};return a.source=e.clone(),a.status=o,a.statusText=r,a.headers=s,a.config=t,a.data=yield((e,t)=>A(void 0,void 0,void 0,(function*(){const r=t.responseType.trim(),o=e;if(""===r)return yield o.text();const n=new RegExp(String.raw`^${r}$`,"i"),s=i.find((e=>n.test(e)));if(s)return yield o[s]();q("The value of 'responseType' parameter is invalid!","TypeError")})))(e,t),a}));class C{constructor(){this.isAllow=!1,this.aborted=!1,this.isDefer=!1,this.init()}init(){g&&(this.isAllow=!0),this.initAborber()}deferAbort(e,t){0!==(e=+e)&&((Number.isNaN(e)||e<0)&&q("the type of parameter 'timeout' is invalid!","TypeError"),this.abortTimer=setTimeout((()=>{const r=`The request duration exceeded the maximum limit of ${e} \n milliseconds and has been interrupted`;this.setAbortMsg(r),this.isDefer=!0,this.abortFetch(),t&&t(r)}),e))}initAborber(){const e=new AbortController,{signal:t}=e;this.controller=e,this.singal=t}setAbortMsg(e){this.abortMsg=e}abortFetch(){const{controller:e,isAllow:t}=this;t&&!this.aborted&&e.abort()}abortState(){const{isAllow:e,singal:t}=this;return new Promise(((r,o)=>{e&&t&&(t.onabort=e=>{this.aborted=!0,r(this.abortMsg)})}))}restoreAbortTimer(){const e=clearTimeout(this.abortTimer);return this.abortTimer=null,e}}function F(e){Object(e)!==e&&q("The request 'config' is invalid, is it returned in the request interceptor?","RyokoError"),e.beforeRequest.call(this,e);let t=new C;!function(e,t){if("function"==typeof t&&(t=[t]),null==e)return;const{tokenStore:r}=O;let o=r.get(e);void 0!==o?t.forEach((e=>o.add(e))):r.set(e,new Set(t))}(e.abortToken,(function(){null==t||t.restoreAbortTimer(),null==t||t.abortFetch()}));let{prefixUrl:r,url:o,params:s,data:i,timeout:a,method:c,onDefer:l,verifyStatus:u,downloadScheduler:d,headers:f,fetch:h}=e;const b={},p=Object.keys(e);n.forEach((t=>{p.includes(t)&&(b[t]=e[t])}));const m=$(r,o,s),y=N(i);return y&&(b.body=y),b.signal=t.singal,t.deferAbort(a),new Promise(((r,o)=>{t.abortState().then((r=>{t.isDefer&&(l&&l.call(this,e),o(new S(r,{config:e})))})),h(m,b).then((n=>A(this,void 0,void 0,(function*(){t.restoreAbortTimer(),t=null;//!作用是告知ts强制转null为RyokoAbortController类型
const{body:s,status:i}=n;null!=s&&d&&(n=j.call(this,n,d));const a=yield U(n,e);u(i)?(r(a),e.afterResponse.call(this,a)):o(new S(`The status of the Ryoko request response is ${i}`,{status:i,config:e}))}))),(r=>{if(t.aborted)return;const n=null==r?void 0:r.status;o(new S(`The Ryoko Requestion miss an Error: ${r}`,{status:n,config:e}))}))}))}const D=(e,t)=>{const r=(e=>{for(let t in e)l(e,t)&&void 0===e[t]&&delete e[t];return e})(b(t,e));let{method:o,headers:n,data:i,fetch:c,credentials:u,beforeRequest:d,afterResponse:f}=r,h=new RegExp(`^${o}$`,"i");var p;return s.some((e=>e.match(h)))?r.method=o=o.toLowerCase():q(`The 'method' parameter must be one of the ${s.length} \n options:${s.join("、")}`,"TypeError"),["get","head","options"].includes(o)?Reflect.deleteProperty(r,"data"):r.data=N(i),p=c,y.Function(p)||q("The 'fetch' option you provided is not a function!","TypeError"),"boolean"==typeof u?r.credentials=u=u?"include":"omit":a.includes(u)||q(`The valid type of 'credentials' paramter:Boolean、undefined、${a.join("、")}`,"TypeError"),r};class I{constructor(e){this.defaults=b({},e,R),this.interceptors={request:new w,response:new w}}request(e){const t=D(this.defaults,e),r=[],o=[];this.interceptors.request.traverse((e=>{r.push(e.success,e.failure)})),this.interceptors.response.traverse((e=>{o.push(e.success,e.failure)}));let n,s=t;for(;r.length;){const e=r.shift(),o=r.shift();try{s=e(t)}catch(e){o(e);break}}try{n=F.call(this,s)}catch(e){return Promise.reject(e)}for(;o.length;)n=n.then(o.shift(),o.shift());return n}}function L(e={}){const t=new I(e),r=t.request.bind(t);return b(r,t),b(r,Object.getPrototypeOf(t)),r}Object.defineProperty(I.prototype,"request",{enumerable:!0}),s.forEach(((e,t)=>{Reflect.set(I.prototype,e,(function(t,r){const o=u({},r,{method:e,url:t});return"function"==typeof this?this(o):this.request.call(this,o)}))}));const M=L();M.Ryoko=I,M.AbortTokenizer=O,M.create=e=>L(e),M.all=e=>Promise.all(e),M.spread=e=>t=>e.apply(null,t),e.abortAllRequest=k,e.abortOneRequest=E,e.abortPendingRequest=function(...e){e=e.flat(1/0);const{length:t}=e;if(t<1)k();else for(let r=0;r<t;r++)E(e[r])},e.default=M,Object.defineProperty(e,"__esModule",{value:!0})}));