flighty
Version:
Fetch wrapper. Polyfills optional. Aborts, retries, intercepts all in 5kb
2 lines (1 loc) • 18.5 kB
JavaScript
;var flighty=function(){'use strict';var b=String.prototype;function a(a,b){return b={exports:{}},a(b,b.exports),b.exports}var c="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?{}:self:global:window,d=a(function(){(function(a,b){b()})(c,function(){function a(a){return"function"==typeof a.Request&&!a.Request.prototype.hasOwnProperty("signal")||!a.AbortController}function b(b){"function"==typeof b&&(b={fetch:b});var c=b,d=c.fetch,e=c.Request,f=void 0===e?d.Request:e,g=c.AbortController;if(!a({fetch:d,Request:f,AbortController:g}))return{fetch:d,Request:h};var h=f;h&&!h.prototype.hasOwnProperty("signal")&&(h=function(a,b){var c=new f(a,b);return b&&b.signal&&(c.signal=b.signal),c},h.prototype=f.prototype);var i=d,j=function(a,b){var c=h&&h.prototype.isPrototypeOf(a)?a.signal:b?b.signal:void 0;if(c){var d;try{d=new DOMException("Aborted","AbortError")}catch(a){d=new Error("Aborted"),d.name="AbortError"}if(c.aborted)return Promise.reject(d);var e=new Promise(function(a,b){c.addEventListener("abort",function(){return b(d)},{once:!0})});return Promise.race([e,i(a,b)])}return i(a,b)};return{fetch:j,Request:h}}var d=function(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")},e=function(){function a(a,b){for(var c,d=0;d<b.length;d++)c=b[d],c.enumerable=c.enumerable||!1,c.configurable=!0,"value"in c&&(c.writable=!0),Object.defineProperty(a,c.key,c)}return function(b,c,d){return c&&a(b.prototype,c),d&&a(b,d),b}}(),f=function a(b,c,d){null===b&&(b=Function.prototype);var e=Object.getOwnPropertyDescriptor(b,c);if(void 0===e){var f=Object.getPrototypeOf(b);return null===f?void 0:a(f,c,d)}if("value"in e)return e.value;var g=e.get;return void 0===g?void 0:g.call(d)},g=function(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)},h=function(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return b&&("object"==typeof b||"function"==typeof b)?b:a},i=function(){function a(){d(this,a),this.listeners={}}return e(a,[{key:"addEventListener",value:function(a,b){a in this.listeners||(this.listeners[a]=[]),this.listeners[a].push(b)}},{key:"removeEventListener",value:function(a,b){if(a in this.listeners)for(var c=this.listeners[a],d=0,e=c.length;void 0>d;d++)if(c[d]===b)return void c.splice(d,1)}},{key:"dispatchEvent",value:function(a){var b=this;if(a.type in this.listeners){for(var c=function(c){setTimeout(function(){return c.call(b,a)})},d=this.listeners[a.type],e=0,f=d.length;void 0>e;e++)c(d[e]);return!a.defaultPrevented}}}]),a}(),j=function(a){function b(){d(this,b);var a=h(this,(b.__proto__||Object.getPrototypeOf(b)).call(this));return a.aborted=!1,a.onabort=null,a}return g(b,a),e(b,[{key:"toString",value:function(){return"[object AbortSignal]"}},{key:"dispatchEvent",value:function(a){"abort"===a.type&&(this.aborted=!0,"function"==typeof this.onabort&&this.onabort.call(this,a)),f(b.prototype.__proto__||Object.getPrototypeOf(b.prototype),"dispatchEvent",this).call(this,a)}}]),b}(i),k=function(){function a(){d(this,a),this.signal=new j}return e(a,[{key:"abort",value:function(){var a;try{a=new Event("abort")}catch(b){"undefined"==typeof document?a={type:"abort",bubbles:!1,cancelable:!1}:(a=document.createEvent("Event"),a.initEvent("abort",!1,!1))}this.signal.dispatchEvent(a)}},{key:"toString",value:function(){return"[object AbortController]"}}]),a}();"undefined"!=typeof Symbol&&Symbol.toStringTag&&(k.prototype[Symbol.toStringTag]="AbortController",j.prototype[Symbol.toStringTag]="AbortSignal"),function(c){if(a(c)){if(!c.fetch)return void console.warn("fetch() is not available, cannot install abortcontroller-polyfill");var d=b(c),e=d.fetch,f=d.Request;c.fetch=e,c.Request=f,Object.defineProperty(c,"AbortController",{writable:!0,enumerable:!1,configurable:!0,value:k}),Object.defineProperty(c,"AbortSignal",{writable:!0,enumerable:!1,configurable:!0,value:j})}}("undefined"==typeof self?c:self)})}),e=Object.prototype.hasOwnProperty,f=function(){for(var a=[],b=0;256>b;++b)a.push("%"+((16>b?"0":"")+b.toString(16)).toUpperCase());return a}(),g=function(a){for(;1<a.length;){var b=a.pop(),c=b.obj[b.prop];if(Array.isArray(c)){for(var d=[],e=0;e<c.length;++e)"undefined"!=typeof c[e]&&d.push(c[e]);b.obj[b.prop]=d}}},h=function(a,b){for(var c=b&&b.plainObjects?Object.create(null):{},d=0;d<a.length;++d)"undefined"!=typeof a[d]&&(c[d]=a[d]);return c},j={arrayToObject:h,assign:function(a,b){return Object.keys(b).reduce(function(a,c){return a[c]=b[c],a},a)},combine:function(c,a){return[].concat(c,a)},compact:function(a){for(var b=[{obj:{o:a},prop:"o"}],c=[],d=0;d<b.length;++d)for(var e=b[d],f=e.obj[e.prop],h=Object.keys(f),k=0;k<h.length;++k){var l=h[k],m=f[l];"object"==typeof m&&null!==m&&-1===c.indexOf(m)&&(b.push({obj:f,prop:l}),c.push(m))}return g(b),a},decode:function(a,b,c){var d=a.replace(/\+/g," ");if("iso-8859-1"===c)return d.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(d)}catch(a){return d}},encode:function(a,b,d){if(0===a.length)return a;var e="string"==typeof a?a:a+"";if("iso-8859-1"===d)return escape(e).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});for(var g,h="",j=0;j<e.length;++j){if(g=e.charCodeAt(j),45===g||46===g||95===g||126===g||48<=g&&57>=g||65<=g&&90>=g||97<=g&&122>=g){h+=e.charAt(j);continue}if(128>g){h+=f[g];continue}if(2048>g){h+=f[192|g>>6]+f[128|63&g];continue}if(55296>g||57344<=g){h+=f[224|g>>12]+f[128|63&g>>6]+f[128|63&g];continue}j+=1,g=65536+((1023&g)<<10|1023&e.charCodeAt(j)),h+=f[240|g>>18]+f[128|63&g>>12]+f[128|63&g>>6]+f[128|63&g]}return h},isBuffer:function(a){return null!==a&&"undefined"!=typeof a&&!!(a.constructor&&a.constructor.isBuffer&&a.constructor.isBuffer(a))},isRegExp:function(a){return"[object RegExp]"===Object.prototype.toString.call(a)},merge:function a(b,c,d){if(!c)return b;if("object"!=typeof c){if(Array.isArray(b))b.push(c);else if("object"==typeof b)(d&&(d.plainObjects||d.allowPrototypes)||!e.call(Object.prototype,c))&&(b[c]=!0);else return[b,c];return b}if("object"!=typeof b)return[b].concat(c);var f=b;return Array.isArray(b)&&!Array.isArray(c)&&(f=h(b,d)),Array.isArray(b)&&Array.isArray(c)?(c.forEach(function(c,f){e.call(b,f)?b[f]&&"object"==typeof b[f]?b[f]=a(b[f],c,d):b.push(c):b[f]=c}),b):Object.keys(c).reduce(function(b,f){var g=c[f];return b[f]=e.call(b,f)?a(b[f],g,d):g,b},f)}},k=b.replace,l=/%20/g,m={default:"RFC3986",formatters:{RFC1738:function(a){return k.call(a,l,"+")},RFC3986:function(a){return a}},RFC1738:"RFC1738",RFC3986:"RFC3986"},n={brackets:function(a){return a+"[]"},indices:function(a,b){return a+"["+b+"]"},repeat:function(a){return a}},o=Array.isArray,p=Array.prototype.push,q=function(a,b){p.apply(a,o(b)?b:[b])},r=Date.prototype.toISOString,s={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:j.encode,encodeValuesOnly:!1,indices:!1,serializeDate:function(a){return r.call(a)},skipNulls:!1,strictNullHandling:!1},t=function a(b,c,d,e,f,g,h,k,l,m,n,o,p){var r=b;if("function"==typeof h?r=h(c,r):r instanceof Date&&(r=m(r)),null===r){if(e)return g&&!o?g(c,s.encoder,p):c;r=""}if("string"==typeof r||"number"==typeof r||"boolean"==typeof r||j.isBuffer(r)){if(g){var t=o?c:g(c,s.encoder,p);return[n(t)+"="+n(g(r,s.encoder,p))]}return[n(c)+"="+n(r+"")]}var u=[];if("undefined"==typeof r)return u;var v;if(Array.isArray(h))v=h;else{var w=Object.keys(r);v=k?w.sort(k):w}for(var x,y=0;y<v.length;++y)(x=v[y],!(f&&null===r[x]))&&(Array.isArray(r)?q(u,a(r[x],d(c,x),d,e,f,g,h,k,l,m,n,o,p)):q(u,a(r[x],c+(l?"."+x:"["+x+"]"),d,e,f,g,h,k,l,m,n,o,p)));return u},u=function(a,b){var c=a,d=b?j.assign({},b):{};if(null!==d.encoder&&void 0!==d.encoder&&"function"!=typeof d.encoder)throw new TypeError("Encoder has to be a function.");var e="undefined"==typeof d.delimiter?s.delimiter:d.delimiter,f="boolean"==typeof d.strictNullHandling?d.strictNullHandling:s.strictNullHandling,g="boolean"==typeof d.skipNulls?d.skipNulls:s.skipNulls,h="boolean"==typeof d.encode?d.encode:s.encode,k="function"==typeof d.encoder?d.encoder:s.encoder,l="function"==typeof d.sort?d.sort:null,o="undefined"==typeof d.allowDots?s.allowDots:!!d.allowDots,p="function"==typeof d.serializeDate?d.serializeDate:s.serializeDate,r="boolean"==typeof d.encodeValuesOnly?d.encodeValuesOnly:s.encodeValuesOnly,u=d.charset||s.charset;if("undefined"!=typeof d.charset&&"utf-8"!==d.charset&&"iso-8859-1"!==d.charset)throw new Error("The charset option must be either utf-8, iso-8859-1, or undefined");if("undefined"==typeof d.format)d.format=m["default"];else if(!Object.prototype.hasOwnProperty.call(m.formatters,d.format))throw new TypeError("Unknown format option provided.");var v,w,x=m.formatters[d.format];"function"==typeof d.filter?(w=d.filter,c=w("",c)):Array.isArray(d.filter)&&(w=d.filter,v=w);var y=[];if("object"!=typeof c||null===c)return"";var z=d.arrayFormat in n?d.arrayFormat:"indices"in d?d.indices?"indices":"repeat":"indices";var A=n[z];v||(v=Object.keys(c)),l&&v.sort(l);for(var B,C=0;C<v.length;++C)(B=v[C],!(g&&null===c[B]))&&q(y,t(c[B],B,A,f,g,h?k:null,w,l,o,p,x,r,u));var D=y.join(e),E=!0===d.addQueryPrefix?"?":"";return d.charsetSentinel&&("iso-8859-1"===u?E+="utf8=%26%2310003%3B&":E+="utf8=%E2%9C%93&"),0<D.length?E+D:""},v=Object.prototype.hasOwnProperty,w={allowDots:!1,allowPrototypes:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,decoder:j.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},x=function(a){return a.replace(/&#(\d+);/g,function(a,b){var c=String.fromCharCode;return c(parseInt(b,10))})},y=function(a,b){var c,d={},e=b.ignoreQueryPrefix?a.replace(/^\?/,""):a,f=b.parameterLimit===1/0?void 0:b.parameterLimit,g=e.split(b.delimiter,f),h=-1,k=b.charset;if(b.charsetSentinel)for(c=0;c<g.length;++c)0===g[c].indexOf("utf8=")&&(g[c]==="utf8=%E2%9C%93"?k="utf-8":g[c]==="utf8=%26%2310003%3B"&&(k="iso-8859-1"),h=c,c=g.length);for(c=0;c<g.length;++c)if(c!==h){var l,m,n=g[c],o=n.indexOf("]="),p=-1===o?n.indexOf("="):o+1;-1===p?(l=b.decoder(n,w.decoder,k),m=b.strictNullHandling?null:""):(l=b.decoder(n.slice(0,p),w.decoder,k),m=b.decoder(n.slice(p+1),w.decoder,k)),m&&b.interpretNumericEntities&&"iso-8859-1"===k&&(m=x(m)),d[l]=v.call(d,l)?j.combine(d[l],m):m}return d},z=function(a,b,c){for(var d=b,e=a.length-1;0<=e;--e){var f,g=a[e];if("[]"===g&&c.parseArrays)f=[].concat(d);else{f=c.plainObjects?Object.create(null):{};var h="["===g.charAt(0)&&"]"===g.charAt(g.length-1)?g.slice(1,-1):g,j=parseInt(h,10);c.parseArrays||""!==h?!isNaN(j)&&g!==h&&j+""===h&&0<=j&&c.parseArrays&&j<=c.arrayLimit?(f=[],f[j]=d):f[h]=d:f={0:d}}d=f}return d},A=function(a,b,c){if(a){var d=c.allowDots?a.replace(/\.([^.[]+)/g,"[$1]"):a,e=/(\[[^[\]]*])/,f=/(\[[^[\]]*])/g,g=e.exec(d),h=g?d.slice(0,g.index):d,j=[];if(h){if(!c.plainObjects&&v.call(Object.prototype,h)&&!c.allowPrototypes)return;j.push(h)}for(var k=0;null!==(g=f.exec(d))&&k<c.depth;){if(k+=1,!c.plainObjects&&v.call(Object.prototype,g[1].slice(1,-1))&&!c.allowPrototypes)return;j.push(g[1])}return g&&j.push("["+d.slice(g.index)+"]"),z(j,b,c)}},B={formats:m,parse:function(a,b){var c=b?j.assign({},b):{};if(null!==c.decoder&&void 0!==c.decoder&&"function"!=typeof c.decoder)throw new TypeError("Decoder has to be a function.");if(c.ignoreQueryPrefix=!0===c.ignoreQueryPrefix,c.delimiter="string"==typeof c.delimiter||j.isRegExp(c.delimiter)?c.delimiter:w.delimiter,c.depth="number"==typeof c.depth?c.depth:w.depth,c.arrayLimit="number"==typeof c.arrayLimit?c.arrayLimit:w.arrayLimit,c.parseArrays=!1!==c.parseArrays,c.decoder="function"==typeof c.decoder?c.decoder:w.decoder,c.allowDots="undefined"==typeof c.allowDots?w.allowDots:!!c.allowDots,c.plainObjects="boolean"==typeof c.plainObjects?c.plainObjects:w.plainObjects,c.allowPrototypes="boolean"==typeof c.allowPrototypes?c.allowPrototypes:w.allowPrototypes,c.parameterLimit="number"==typeof c.parameterLimit?c.parameterLimit:w.parameterLimit,c.strictNullHandling="boolean"==typeof c.strictNullHandling?c.strictNullHandling:w.strictNullHandling,"undefined"!=typeof c.charset&&"utf-8"!==c.charset&&"iso-8859-1"!==c.charset)throw new Error("The charset option must be either utf-8, iso-8859-1, or undefined");if("undefined"==typeof c.charset&&(c.charset=w.charset),""===a||null===a||"undefined"==typeof a)return c.plainObjects?Object.create(null):{};for(var d="string"==typeof a?y(a,c):a,e=c.plainObjects?Object.create(null):{},f=Object.keys(d),g=0;g<f.length;++g){var h=f[g],k=A(h,d[h],c);e=j.merge(e,k,c)}return j.compact(e)},stringify:u},C=a(function(a){(function(b,c,d){a.exports?a.exports=d():c[b]=d()})("urljoin",c,function(){function a(a){var b=[];if(a[0].match(/^[^/:]+:\/*$/)&&1<a.length){var c=a.shift();a[0]=c+a[0]}a[0]=a[0].match(/^file:\/\/\//)?a[0].replace(/^([^/:]+):\/*/,"$1:///"):a[0].replace(/^([^/:]+):\/*/,"$1://");for(var d,e=0;e<a.length;e++){if(d=a[e],"string"!=typeof d)throw new TypeError("Url must be a string. Received "+d);""!==d&&(0<e&&(d=d.replace(/^[\/]+/,"")),d=e<a.length-1?d.replace(/[\/]+$/,""):d.replace(/[\/]+$/,"/"),b.push(d))}var f=b.join("/");f=f.replace(/\/(\?|&|#[^!])/g,"$1");var g=f.split("?");return f=g.shift()+(0<g.length?"?":"")+g.join("&"),f}return function(){var b;return b="object"==typeof arguments[0]?arguments[0]:[].slice.call(arguments),a(b)}})});const D=(a,b)=>{if(a){const c=b.get(a);!c||--c.count||b.delete(a)}},E=({abortToken:a,signal:b},c,d)=>{if(!a&&!b)return c.signal;let e=new AbortController;if(a){const b=d.get(a)||{controller:e,count:0};b.count++,d.set(a,b),e=b.controller}return b&&(b.aborted?e.abort():b.addEventListener("abort",()=>e.abort())),c.signal.addEventListener("abort",()=>e.abort()),e.signal},F=a=>new Promise(b=>setTimeout(()=>b(),a)),G=(a,b)=>{if("function"!=typeof a)throw new Error(b)},H=async(a,{retries:c=0,retryDelay:d=1e3,retryFn:b})=>{var e=Number.isFinite,f=Number.isInteger;if(G(a,"retry function is not a function"),"number"!=typeof c||!f(c)||0>c)throw new Error("retries must be a number greater than or equal to 0");if(d&&("number"!=typeof d||!e(d)))throw new Error("retryDelay must be a number (milliseconds)");if(b&&"function"!=typeof b)throw new Error("retryFn must be callable");const g=async(...a)=>b?b(...a):F(d);let h=-1;const i=async b=>{try{return h++,await a(h)}catch(a){if(!b)throw a;return await g(h+1,a),i(b-1)}},j=await i(c);return{count:h,res:j}},I=async(a,{retries:b,retryDelay:c,retryFn:d,retryOn:f=[],signal:e})=>{if(G(a,"retry function is not a function"),f&&!Array.isArray(f))throw new Error("retryOn must be an array of response statii");if(null!=e&&"boolean"!=typeof e.aborted)throw new Error("signal must have boolean \"aborted\" property");return H(async c=>{const d=await a();if(-1===f.indexOf(d.status)||b===c)return d;throw new Error(d)},{retries:b,retryFn:async(a,b)=>{if(e&&e.aborted)throw b;return d?d(a,b):F(c)}})};if("undefined"==typeof fetch)throw new Error("You're missing a fetch implementation. Try var Flighty = require('flighty/fetch') or import Flighty from 'flighty/fetch'");if("undefined"==typeof AbortController)throw new Error("You're missing an AbortController implementation. Try var Flighty = require('flighty/abort') or import Flighty from 'flighty/abort'");const J=a=>Object.keys(a).some(b=>{const c=a[b];return"content-type"===b.toLowerCase()&&"application/json"===c.toLowerCase().split(";")[0]}),K=["GET","POST","PUT","HEAD","OPTIONS","DEL","PATCH"],L=(a,b,c,d)=>{const e={...d,method:"del"===a?"DELETE":a.toUpperCase(),headers:{...(b.headers||{}),...d.headers}};e.headers=Object.keys(e.headers).reduce((a,b)=>{const c=e.headers[b];return c?{[b]:c,...a}:a},{}),e.body||"POST"!==a||(e.body="");let f=c;"GET"===a&&e.body&&(f+=`?${B.stringify(e.body,{arrayFormat:b.arrayFormat})}`,delete e.body),J(e.headers)&&e.body&&(e.body=JSON.stringify(e.body));const g=b.baseURI?C(b.baseURI,f):f;return fetch(g,e)},M=async(a,b,{path:c,options:d},e,f=0)=>{const{retries:k=0,retryDelay:l=1e3,retryOn:m=[],retryFn:g,abortToken:h,signal:i,...j}=d,n=E({abortToken:h,signal:i},b.abortController,b.abortTokenMap);let o=f;const p={method:a,call:{path:c,options:{...d},extra:{...e}},retry:()=>(o+=1,M(a,b,{path:c,options:{...d}},{...e},o))},q=Array.from(b.interceptors),r=q.reduce((a,b)=>{let c=a;return c=c.then(a=>a.slice(0,2).concat([{...e},f])),b.request&&(c=c.then(a=>b.request(...a))),b.requestError&&(c=c.catch(b.requestError)),c},Promise.resolve([c,j])),s=q.reverse().reduce((a,b)=>{let c=a;return b.response&&(c=c.then(b.response)),b.responseError&&(c=c.catch(b.responseError)),c},(async()=>{const[c,d]=await r,{count:e,res:f}=await I(()=>L(a,b,c,{...d,signal:n}),{retries:k,retryDelay:l,retryOn:m,retryFn:g,signal:n});o+=e,f.flighty=p;let h,i;try{h=await f.clone().json()}catch(a){}try{i=await f.clone().text()}catch(a){}return f.flighty={...p,retryCount:o,json:h,text:i},f})());try{return await s}catch(a){throw a}finally{D(h,b.abortTokenMap)}};class N{constructor(a={}){let b={...a};K.forEach(a=>{this[a.toLowerCase()]=(b="/",c={},d={})=>M(a,this,{path:b,options:c},d)});let c;const d=new Set,e=new Map;Object.defineProperties(this,{headers:{get(){return b.headers},set(a={}){b={...b,headers:a}}},arrayFormat:{get(){return b.arrayFormat||"indicies"}},baseURI:{get(){return b.baseURI},set(a){b={...b,baseURI:a}}},interceptors:{get(){return d}},interceptor:{get(){return{register:a=>this.registerInterceptor(a),unregister:a=>this.removeInterceptor(a),clear:()=>this.clearInterceptors()}}},abortController:{get(){return c||(c=new AbortController,c.signal.addEventListener("abort",()=>{c=null})),c}},abortTokenMap:{get(){return e}}})}abort(a){const b=this.abortTokenMap.get(a);return b&&b.controller.abort()}abortAll(){this.abortController.abort()}registerInterceptor(a){if(!a)throw new Error("cannot register a null interceptor");return this.interceptors.add(a),()=>this.interceptors.delete(a)}clearInterceptors(){this.interceptors.clear()}removeInterceptor(a){this.interceptors.delete(a)}auth(a,b){this.headers={...this.headers,Authorization:a&&b?`Basic ${(a=>"undefined"==typeof btoa?Buffer.from(a).toString("base64"):btoa(a))(`${a}:${b}`)}`:null}}jwt(a){return this.headers={...this.headers,Authorization:a?`Bearer ${a}`:null},this}}const O=new N;return O.create=a=>new N(a),O}();