@pollyjs/adapter
Version:
Extendable base adapter class used by @pollyjs
3 lines (2 loc) • 17.1 kB
JavaScript
import{assert as t,PollyError as e,MODES as r,ACTIONS as n,EXPIRY_STRATEGIES as o,Serializers as i}from"@pollyjs/utils";var s=function(t){if(null==t)throw TypeError("Can't call method on "+t);return t},u=function(t){return Object(s(t))},c={}.hasOwnProperty,a=function(t,e){return c.call(t,e)},f={}.toString,l=function(t){return f.call(t).slice(8,-1)},p=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==l(t)?t.split(""):Object(t)},h=function(t){return p(s(t))},y=Math.ceil,d=Math.floor,g=function(t){return isNaN(t=+t)?0:(t>0?d:y)(t)},b=Math.min,m=Math.max,v=Math.min;function w(t,e){return t(e={exports:{}},e.exports),e.exports}var O,S=w((function(t){var e=t.exports={version:"2.6.9"};"number"==typeof __e&&(__e=e)})),j=(S.version,w((function(t){var e=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=e)}))),P=w((function(t){var e=j["__core-js_shared__"]||(j["__core-js_shared__"]={});(t.exports=function(t,r){return e[t]||(e[t]=void 0!==r?r:{})})("versions",[]).push({version:S.version,mode:"pure",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})})),R=0,E=Math.random(),_=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++R+E).toString(36))},F=P("keys"),x=function(t){return F[t]||(F[t]=_(t))},N=(O=!1,function(t,e,r){var n,o,i=h(t),s=(n=i.length)>0?b(g(n),9007199254740991):0,u=function(t,e){return(t=g(t))<0?m(t+e,0):v(t,e)}(r,s);if(O&&e!=e){for(;s>u;)if((o=i[u++])!=o)return!0}else for(;s>u;u++)if((O||u in i)&&i[u]===e)return O||u||0;return!O&&-1}),k=x("IE_PROTO"),D=function(t,e){var r,n=h(t),o=0,i=[];for(r in n)r!=k&&a(n,r)&&i.push(r);for(;e.length>o;)a(n,r=e[o++])&&(~N(i,r)||i.push(r));return i},I="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),M=Object.keys||function(t){return D(t,I)},T=function(t,e,r){if(function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!")}(t),void 0===e)return t;switch(r){case 1:return function(r){return t.call(e,r)};case 2:return function(r,n){return t.call(e,r,n)};case 3:return function(r,n,o){return t.call(e,r,n,o)}}return function(){return t.apply(e,arguments)}},C=function(t){return"object"==typeof t?null!==t:"function"==typeof t},q=function(t){if(!C(t))throw TypeError(t+" is not an object!");return t},A=function(t){try{return!!t()}catch(t){return!0}},J=!A((function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})),W=j.document,$=C(W)&&C(W.createElement),G=function(t){return $?W.createElement(t):{}},K=!J&&!A((function(){return 7!=Object.defineProperty(G("div"),"a",{get:function(){return 7}}).a})),z=function(t,e){if(!C(t))return t;var r,n;if(e&&"function"==typeof(r=t.toString)&&!C(n=r.call(t)))return n;if("function"==typeof(r=t.valueOf)&&!C(n=r.call(t)))return n;if(!e&&"function"==typeof(r=t.toString)&&!C(n=r.call(t)))return n;throw TypeError("Can't convert object to primitive value")},Y=Object.defineProperty,H={f:J?Object.defineProperty:function(t,e,r){if(q(t),e=z(e,!0),q(r),K)try{return Y(t,e,r)}catch(t){}if("get"in r||"set"in r)throw TypeError("Accessors not supported!");return"value"in r&&(t[e]=r.value),t}},L=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},U=J?function(t,e,r){return H.f(t,e,L(1,r))}:function(t,e,r){return t[e]=r,t},B=function(t,e,r){var n,o,i,s=t&B.F,u=t&B.G,c=t&B.S,f=t&B.P,l=t&B.B,p=t&B.W,h=u?S:S[e]||(S[e]={}),y=h.prototype,d=u?j:c?j[e]:(j[e]||{}).prototype;for(n in u&&(r=e),r)(o=!s&&d&&void 0!==d[n])&&a(h,n)||(i=o?d[n]:r[n],h[n]=u&&"function"!=typeof d[n]?r[n]:l&&o?T(i,j):p&&d[n]==i?function(t){var e=function(e,r,n){if(this instanceof t){switch(arguments.length){case 0:return new t;case 1:return new t(e);case 2:return new t(e,r)}return new t(e,r,n)}return t.apply(this,arguments)};return e.prototype=t.prototype,e}(i):f&&"function"==typeof i?T(Function.call,i):i,f&&((h.virtual||(h.virtual={}))[n]=i,t&B.R&&y&&!y[n]&&U(y,n,i)))};B.F=1,B.G=2,B.S=4,B.P=8,B.B=16,B.W=32,B.U=64,B.R=128;var Q=B,Z=function(t,e){var r=(S.Object||{})[t]||Object[t],n={};n[t]=e(r),Q(Q.S+Q.F*A((function(){r(1)})),"Object",n)};Z("keys",(function(){return function(t){return M(u(t))}}));var V=S.Object.keys,X=U,tt=w((function(t){var e=_("meta"),r=H.f,n=0,o=Object.isExtensible||function(){return!0},i=!A((function(){return o(Object.preventExtensions({}))})),s=function(t){r(t,e,{value:{i:"O"+ ++n,w:{}}})},u=t.exports={KEY:e,NEED:!1,fastKey:function(t,r){if(!C(t))return"symbol"==typeof t?t:("string"==typeof t?"S":"P")+t;if(!a(t,e)){if(!o(t))return"F";if(!r)return"E";s(t)}return t[e].i},getWeak:function(t,r){if(!a(t,e)){if(!o(t))return!0;if(!r)return!1;s(t)}return t[e].w},onFreeze:function(t){return i&&u.NEED&&o(t)&&!a(t,e)&&s(t),t}}})),et=(tt.KEY,tt.NEED,tt.fastKey,tt.getWeak,tt.onFreeze,w((function(t){var e=P("wks"),r=j.Symbol,n="function"==typeof r;(t.exports=function(t){return e[t]||(e[t]=n&&r[t]||(n?r:_)("Symbol."+t))}).store=e}))),rt=H.f,nt=et("toStringTag"),ot=function(t,e,r){t&&!a(t=r?t:t.prototype,nt)&&rt(t,nt,{configurable:!0,value:e})},it={f:et},st=H.f,ut=function(t){var e=S.Symbol||(S.Symbol={});"_"==t.charAt(0)||t in e||st(e,t,{value:it.f(t)})},ct={f:Object.getOwnPropertySymbols},at={f:{}.propertyIsEnumerable},ft=Array.isArray||function(t){return"Array"==l(t)},lt=J?Object.defineProperties:function(t,e){q(t);for(var r,n=M(e),o=n.length,i=0;o>i;)H.f(t,r=n[i++],e[r]);return t},pt=j.document,ht=pt&&pt.documentElement,yt=x("IE_PROTO"),dt=function(){},gt=function(){var t,e=G("iframe"),r=I.length;for(e.style.display="none",ht.appendChild(e),e.src="javascript:",(t=e.contentWindow.document).open(),t.write("<script>document.F=Object<\/script>"),t.close(),gt=t.F;r--;)delete gt.prototype[I[r]];return gt()},bt=Object.create||function(t,e){var r;return null!==t?(dt.prototype=q(t),r=new dt,dt.prototype=null,r[yt]=t):r=gt(),void 0===e?r:lt(r,e)},mt=I.concat("length","prototype"),vt={f:Object.getOwnPropertyNames||function(t){return D(t,mt)}},wt=vt.f,Ot={}.toString,St="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],jt={f:function(t){return St&&"[object Window]"==Ot.call(t)?function(t){try{return wt(t)}catch(t){return St.slice()}}(t):wt(h(t))}},Pt=Object.getOwnPropertyDescriptor,Rt={f:J?Pt:function(t,e){if(t=h(t),e=z(e,!0),K)try{return Pt(t,e)}catch(t){}if(a(t,e))return L(!at.f.call(t,e),t[e])}},Et=tt.KEY,_t=Rt.f,Ft=H.f,xt=jt.f,Nt=j.Symbol,kt=j.JSON,Dt=kt&&kt.stringify,It=et("_hidden"),Mt=et("toPrimitive"),Tt={}.propertyIsEnumerable,Ct=P("symbol-registry"),qt=P("symbols"),At=P("op-symbols"),Jt=Object.prototype,Wt="function"==typeof Nt&&!!ct.f,$t=j.QObject,Gt=!$t||!$t.prototype||!$t.prototype.findChild,Kt=J&&A((function(){return 7!=bt(Ft({},"a",{get:function(){return Ft(this,"a",{value:7}).a}})).a}))?function(t,e,r){var n=_t(Jt,e);n&&delete Jt[e],Ft(t,e,r),n&&t!==Jt&&Ft(Jt,e,n)}:Ft,zt=function(t){var e=qt[t]=bt(Nt.prototype);return e._k=t,e},Yt=Wt&&"symbol"==typeof Nt.iterator?function(t){return"symbol"==typeof t}:function(t){return t instanceof Nt},Ht=function(t,e,r){return t===Jt&&Ht(At,e,r),q(t),e=z(e,!0),q(r),a(qt,e)?(r.enumerable?(a(t,It)&&t[It][e]&&(t[It][e]=!1),r=bt(r,{enumerable:L(0,!1)})):(a(t,It)||Ft(t,It,L(1,{})),t[It][e]=!0),Kt(t,e,r)):Ft(t,e,r)},Lt=function(t,e){q(t);for(var r,n=function(t){var e=M(t),r=ct.f;if(r)for(var n,o=r(t),i=at.f,s=0;o.length>s;)i.call(t,n=o[s++])&&e.push(n);return e}(e=h(e)),o=0,i=n.length;i>o;)Ht(t,r=n[o++],e[r]);return t},Ut=function(t){var e=Tt.call(this,t=z(t,!0));return!(this===Jt&&a(qt,t)&&!a(At,t))&&(!(e||!a(this,t)||!a(qt,t)||a(this,It)&&this[It][t])||e)},Bt=function(t,e){if(t=h(t),e=z(e,!0),t!==Jt||!a(qt,e)||a(At,e)){var r=_t(t,e);return!r||!a(qt,e)||a(t,It)&&t[It][e]||(r.enumerable=!0),r}},Qt=function(t){for(var e,r=xt(h(t)),n=[],o=0;r.length>o;)a(qt,e=r[o++])||e==It||e==Et||n.push(e);return n},Zt=function(t){for(var e,r=t===Jt,n=xt(r?At:h(t)),o=[],i=0;n.length>i;)!a(qt,e=n[i++])||r&&!a(Jt,e)||o.push(qt[e]);return o};Wt||(X((Nt=function(){if(this instanceof Nt)throw TypeError("Symbol is not a constructor!");var t=_(arguments.length>0?arguments[0]:void 0),e=function(r){this===Jt&&e.call(At,r),a(this,It)&&a(this[It],t)&&(this[It][t]=!1),Kt(this,t,L(1,r))};return J&&Gt&&Kt(Jt,t,{configurable:!0,set:e}),zt(t)}).prototype,"toString",(function(){return this._k})),Rt.f=Bt,H.f=Ht,vt.f=jt.f=Qt,at.f=Ut,ct.f=Zt,it.f=function(t){return zt(et(t))}),Q(Q.G+Q.W+Q.F*!Wt,{Symbol:Nt});for(var Vt="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),Xt=0;Vt.length>Xt;)et(Vt[Xt++]);for(var te=M(et.store),ee=0;te.length>ee;)ut(te[ee++]);Q(Q.S+Q.F*!Wt,"Symbol",{for:function(t){return a(Ct,t+="")?Ct[t]:Ct[t]=Nt(t)},keyFor:function(t){if(!Yt(t))throw TypeError(t+" is not a symbol!");for(var e in Ct)if(Ct[e]===t)return e},useSetter:function(){Gt=!0},useSimple:function(){Gt=!1}}),Q(Q.S+Q.F*!Wt,"Object",{create:function(t,e){return void 0===e?bt(t):Lt(bt(t),e)},defineProperty:Ht,defineProperties:Lt,getOwnPropertyDescriptor:Bt,getOwnPropertyNames:Qt,getOwnPropertySymbols:Zt});var re=A((function(){ct.f(1)}));Q(Q.S+Q.F*re,"Object",{getOwnPropertySymbols:function(t){return ct.f(u(t))}}),kt&&Q(Q.S+Q.F*(!Wt||A((function(){var t=Nt();return"[null]"!=Dt([t])||"{}"!=Dt({a:t})||"{}"!=Dt(Object(t))}))),"JSON",{stringify:function(t){for(var e,r,n=[t],o=1;arguments.length>o;)n.push(arguments[o++]);if(r=e=n[1],(C(e)||void 0!==t)&&!Yt(t))return ft(e)||(e=function(t,e){if("function"==typeof r&&(e=r.call(this,t,e)),!Yt(e))return e}),n[1]=e,Dt.apply(kt,n)}}),Nt.prototype[Mt]||U(Nt.prototype,Mt,Nt.prototype.valueOf),ot(Nt,"Symbol"),ot(Math,"Math",!0),ot(j.JSON,"JSON",!0);var ne=S.Object.getOwnPropertySymbols,oe=Rt.f;Z("getOwnPropertyDescriptor",(function(){return function(t,e){return oe(h(t),e)}}));var ie=S.Object,se=function(t,e){return ie.getOwnPropertyDescriptor(t,e)},ue=j.Reflect,ce=ue&&ue.ownKeys||function(t){var e=vt.f(q(t)),r=ct.f;return r?e.concat(r(t)):e},ae=function(t,e,r){e in t?H.f(t,e,L(0,r)):t[e]=r};Q(Q.S,"Object",{getOwnPropertyDescriptors:function(t){for(var e,r,n=h(t),o=Rt.f,i=ce(n),s={},u=0;i.length>u;)void 0!==(r=o(n,e=i[u++]))&&ae(s,e,r);return s}});var fe=S.Object.getOwnPropertyDescriptors;Q(Q.S+Q.F*!J,"Object",{defineProperties:lt});var le=S.Object,pe=function(t,e){return le.defineProperties(t,e)};Q(Q.S+Q.F*!J,"Object",{defineProperty:H.f});var he,ye=S.Object,de=function(t,e,r){return ye.defineProperty(t,e,r)},ge=w((function(t){t.exports=function(t,e,r){return e in t?de(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t},t.exports.default=t.exports,t.exports.__esModule=!0})),be=(he=ge)&&he.__esModule&&Object.prototype.hasOwnProperty.call(he,"default")?he.default:he;ut("asyncIterator"),ut("observable");var me=S.Symbol,ve=S.JSON||(S.JSON={stringify:JSON.stringify}),we=function(t){return ve.stringify.apply(ve,arguments)},Oe="\t\n\v\f\r \u2028\u2029\ufeff",Se="["+Oe+"]",je=RegExp("^"+Se+Se+"*"),Pe=RegExp(Se+Se+"*$"),Re=function(t,e,r){var n={},o=A((function(){return!!Oe[t]()||"
"!="
"[t]()})),i=n[t]=o?e(Ee):Oe[t];r&&(n[r]=i),Q(Q.P+Q.F*o,"String",n)},Ee=Re.trim=function(t,e){return t=String(s(t)),1&e&&(t=t.replace(je,"")),2&e&&(t=t.replace(Pe,"")),t},_e=Re,Fe=j.parseFloat,xe=_e.trim,Ne=1/Fe(Oe+"-0")!=-1/0?function(t){var e=xe(String(t),3),r=Fe(e);return 0===r&&"-"==e.charAt(0)?-0:r}:Fe;Q(Q.G+Q.F*(parseFloat!=Ne),{parseFloat:Ne});var ke=S.parseFloat;const De=/([0-9.]+)([a-zA-Z]+)/g,Ie={ms:1,millisecond:1,milliseconds:1,s:1e3,sec:1e3,secs:1e3,second:1e3,seconds:1e3,m:6e4,min:6e4,mins:6e4,minute:6e4,minutes:6e4,h:36e5,hr:36e5,hrs:36e5,hour:36e5,hours:36e5,d:864e5,day:864e5,days:864e5,w:6048e5,wk:6048e5,wks:6048e5,week:6048e5,weeks:6048e5,y:31536e6,yr:31536e6,yrs:31536e6,year:31536e6,years:31536e6};function Me(t,e){return!(!t||!e)&&new Date>new Date(new Date(t).getTime()+("string"!=typeof(r=e)?NaN:r.replace(/ /g,"").match(De).map(t=>t.split(De).filter(t=>t)).reduce((t,[e,r])=>t+ke(e)*Ie[r],0)));var r}function Te(t,e){var r=V(t);if(ne){var n=ne(t);e&&(n=n.filter((function(e){return se(t,e).enumerable}))),r.push.apply(r,n)}return r}function Ce(t,...e){const r=function(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?Te(Object(r),!0).forEach((function(e){be(t,e,r[e])})):fe?pe(t,fe(r)):Te(Object(r)).forEach((function(e){de(t,e,se(r,e))}))}return t}({},t.config);return["adapter","adapterOptions","persister","persisterOptions"].forEach(t=>delete r[t]),we({url:t.url,method:t.method,headers:t.headers,body:t.body,recordingName:t.recordingName,id:t.id,order:t.order,identifiers:t.identifiers,config:r},...e)}const{isArray:qe}=Array;function Ae(t){return(t||[]).reduce((t,{name:e,value:r,_fromType:n})=>{const o=t[e];return o?(qe(o)||(t[e]=[o]),t[e].push(r)):t[e]="array"===n?[r]:r,t},{})}function Je(t,e){var r=V(t);if(ne){var n=ne(t);e&&(n=n.filter((function(e){return se(t,e).enumerable}))),r.push.apply(r,n)}return r}function We(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?Je(Object(r),!0).forEach((function(e){be(t,e,r[e])})):fe?pe(t,fe(r)):Je(Object(r)).forEach((function(e){de(t,e,se(r,e))}))}return t}const $e=me();export default class{constructor(t){this.polly=t,this.isConnected=!1}static get type(){return"adapter"}static get id(){t("Must override the static `id` getter.")}get defaultOptions(){return{}}get options(){return We(We({},this.defaultOptions||{}),(this.polly.config.adapterOptions||{})[this.constructor.id]||{})}get persister(){return this.polly.persister}connect(){this.isConnected||(this.onConnect(),this.isConnected=!0,this.polly.logger.log.debug(`Connected to ${this.constructor.id} adapter.`))}onConnect(){this.assert("Must implement the `onConnect` hook.")}disconnect(){this.isConnected&&(this.onDisconnect(),this.isConnected=!1,this.polly.logger.log.debug(`Disconnected from ${this.constructor.id} adapter.`))}onDisconnect(){this.assert("Must implement the `onDisconnect` hook.")}timeout(t,{time:e}){const{timing:r}=t.config;if("function"==typeof r)return r(e)}async handleRequest(t){const r=this.polly.registerRequest(t);try{if(r.on("identify",(...t)=>this.onIdentifyRequest(...t)),await this.onRequest(r),await r.init(),await this[$e](r),r.aborted)throw new e("Request aborted.");await this.onRequestFinished(r)}catch(t){await this.onRequestFailed(r,t)}return r}async[$e](t){const{mode:e}=this.polly,{_interceptor:n}=t;if(!(t.aborted||t.shouldIntercept&&(await this.intercept(t,n),n.shouldIntercept)))return e===r.PASSTHROUGH||t.shouldPassthrough||n.shouldPassthrough?this.passthrough(t):(this.assert("A persister must be configured in order to record and replay requests.",!!this.persister),e===r.RECORD?this.record(t):e===r.REPLAY?this.replay(t):void this.assert("Unhandled request: \n"+Ce(t,null,2)))}async passthrough(t){return t.action=n.PASSTHROUGH,this.onPassthrough(t)}async onPassthrough(t){const e=await this.onFetchResponse(t);await t.respond(e)}async intercept(t,e){if(t.action=n.INTERCEPT,await t._intercept(e),e.shouldIntercept)return this.onIntercept(t,t.response)}async onIntercept(t,e){await t.respond(e)}async record(t){return t.action=n.RECORD,"navigator"in global&&!navigator.onLine&&t.log.warn("[Polly] Recording may fail because the browser is offline.\n"+Ce(t)),this.onRecord(t)}async onRecord(t){await this.onPassthrough(t),t.aborted||await this.persister.recordRequest(t)}async replay(t){const{config:e}=t,r=await this.persister.findEntry(t);if(r){const i=JSON.parse(we(r));if(await t._emit("beforeReplay",i),Me(i.startedDateTime,e.expiresIn)){const r="Recording for the following request has expired.\n"+Ce(t,null,2);switch(e.expiryStrategy){case o.RECORD:return this.record(t);case o.ERROR:this.assert(r);break;case o.WARN:t.log.warn("[Polly] "+r);break;default:this.assert(`Invalid config option passed for "expiryStrategy": "${e.expiryStrategy}"`)}}return await this.timeout(t,i),t.action=n.REPLAY,this.onReplay(t,function(t){const{status:e,statusText:r,headers:n,content:o}=t;return{statusText:r,statusCode:e,headers:Ae(n),body:o&&o.text,encoding:o&&o.encoding}}(i.response),i)}if(e.recordIfMissing)return this.record(t);this.assert("Recording for the following request is not found and `recordIfMissing` is `false`.\n"+Ce(t,null,2))}async onReplay(t,e){await t.respond(e)}assert(e,...r){t(`[${this.constructor.type}:${this.constructor.id}] ${e}`,...r)}onRequest(){}async onIdentifyRequest(t){const{identifiers:e}=t;for(const t of["blob","formData","buffer"])e.body=await i[t](e.body)}async onRequestFinished(t){await this.onRespond(t),t.promise.resolve()}async onRequestFailed(t,r){const{aborted:n}=t;r=r||new e("Request failed due to an unknown error.");try{n?await t._emit("abort"):await t._emit("error",r),await this.onRespond(t,r)}finally{t.promise.reject(r)}}async onRespond(){}async onFetchResponse(){this.assert("Must implement the `onFetchResponse` hook.")}}
//# sourceMappingURL=pollyjs-adapter.min.js.map