UNPKG

xior

Version:

A lite http request lib based on fetch with plugins support and similar API to axios.

1 lines 11.9 kB
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.xiorMock=t():e.xiorMock=t()}(this,(function(){return function(){"use strict";var e={99:function(e,t,r){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.buildSortedURL=void 0,t.delay=function(e){return new Promise((t=>{setTimeout((()=>{t(1)}),e)}))};const o=n(r(629));t.buildSortedURL=o.default},330:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.DELETE=t.PATCH=t.PUT=t.POST=t.OPTIONS=t.GET=t.HEAD=t.m=t.isArray=t.keys=t.op=t.nullValue=t.undefinedValue=t.O=t.h=t.status=t.addEventListener=t.qs=t.abort=t.json=t.text=t.p=t.f=t.o=void 0,t.o="object",t.f="function",t.p="prototype",t.text="text",t.json="json",t.abort="abort",t.qs="paramsSerializer",t.addEventListener="addEventListener",t.status="status",t.h="headers",t.O=Object,t.undefinedValue=void 0,t.nullValue=null,t.op=t.O[t.p],t.keys=t.O.keys,t.isArray=Array.isArray,t.m="method",t.HEAD="HEAD",t.GET="GET",t.OPTIONS="OPTIONS",t.POST="POST",t.PUT="PUT",t.PATCH="PATCH",t.DELETE="DELETE"},486:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))((function(o,i){function s(e){try{u(n.next(e))}catch(e){i(e)}}function a(e){try{u(n.throw(e))}catch(e){i(e)}}function u(e){var t;e.done?o(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(s,a)}u((n=n.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.MockError=void 0;const o=r(732),i=r(330),s=r(976),a="undefined"!=typeof AbortController;class u extends Error{constructor(e,t){super(e),this.request=t,this.config=t}}function d(e){const t=e.filter((e=>{const[,t]=e;return"function"==typeof(null==t?void 0:t.asymmetricMatch)})),r=t.filter((e=>{const[t,r]=e;return r.asymmetricMatch(t)}));return r.length>0&&r.length===t.length}function l(e){e||(e={});const t={},r="undefined"==typeof Headers?{append(e,r){t[e]=r+""},get(e){return t[e]||i.nullValue}}:new Headers;return(0,i.keys)(e).forEach((t=>{r.append(t,e[t])})),r}function c(e,t){if(e.status>=300)throw new s.XiorError(`Request failed with status code ${e.status}`,t,e);return e}t.MockError=u,t.default=class{constructor(e,t){this.handlers={},this.history={},this.options=t,this.instance=e,this.plugin=this._mockPlugin.bind(this),e.plugins.use(this.plugin)}_mockPlugin(e){return t=>n(this,void 0,void 0,(function*(){var r,n,o,d,h;const f=(null===(r=t.method)||void 0===r?void 0:r.toLowerCase())||"get";this.history[f]||(this.history[f]=[]),this.handlers[f]||(this.handlers[f]=[]),null===(n=this.history[f])||void 0===n||n.push(t);const p=this.findHandler(t);if(p){const r=p[6]||(null===(o=this.options)||void 0===o?void 0:o.delayResponse);6===p.length&&(0,i.keys)(this.handlers).forEach((e=>{var t,r;let n=null===(t=this.handlers[e])||void 0===t?void 0:t.indexOf(p);n=void 0===n?-1:n,n>-1&&(null===(r=this.handlers[e])||void 0===r||r.splice(n,1))}));const n=[];let u;if(2!==p.length){let e,r;if(t.timeout&&a){const e=new AbortController;r=setTimeout((()=>{e.abort(new s.XiorTimeoutError(`timeout of ${t.timeout}ms exceeded`,t))}),t.timeout),n.push(e.signal)}t.signal&&n.push(t.signal),e=n[0],n.length>1&&(e=(0,s.anySignal)(n,(()=>{r&&clearTimeout(r)}))),u=()=>{var t;r&&clearTimeout(r),null===(t=null==e?void 0:e.clear)||void 0===t||t.call(e)}}r&&r>0&&(yield(0,s.delay)(r));const d=n.find((e=>e.aborted));if(d)return null==u||u(),Promise.reject(d.reason);if(2===p.length)return e(t);if("function"!=typeof p[2]){const e=p.slice(2),r=c({data:e[1],status:e[0],statusText:"ok",headers:e[2],request:t,config:t},t);return null==u||u(),r}const h=p[2](t);if("function"!=typeof(null==h?void 0:h.then)){const e=c({data:h[1],status:h[0],statusText:"ok",headers:l(h[2]),request:t,config:t},t);return null==u||u(),e}{const e=yield h;return null==u||u(),e.config&&e.status?e:c({data:e[1],status:e[0],statusText:"ok",headers:l(e[2]),request:t,config:t},t)}}if("passthrough"===(null===(d=this.options)||void 0===d?void 0:d.onNoMatch))return e(t);if("throwException"===(null===(h=this.options)||void 0===h?void 0:h.onNoMatch)){const e="Could not find mock for: \n"+JSON.stringify(t,["method","url"],2);throw new u(e,t)}{const e="Request failed with status code 404";throw new s.XiorError(e,t,{status:404,statusText:e,config:t})}}))}resetHandlers(){this.handlers={}}resetHistory(){this.history={}}reset(){this.resetHandlers(),this.resetHistory()}restore(){var e;this.reset(),null===(e=this.instance)||void 0===e||e.plugins.eject(this.plugin)}onGet(e,t){return this.createHandler("get").bind(this)(e,t)}onDelete(e,t){return this.createHandler("delete").bind(this)(e,t)}onHead(e,t){return this.createHandler("head").bind(this)(e,t)}onAny(e,t){return this.createHandler("any").bind(this)(e,t)}onPost(e,t,r){return this.createHandler("post").bind(this)(e,(0,s.merge)({},r||{},{data:t||{}}))}onPut(e,t,r){return this.createHandler("put").bind(this)(e,(0,s.merge)({},r||{},{data:t||{}}))}onPatch(e,t,r){return this.createHandler("patch").bind(this)(e,(0,s.merge)({},r||{},{data:t||{}}))}onOptions(e,t){return this.createHandler("options").bind(this)(e,t)}createHandler(e){return(t,r)=>{var n,o,i,a,u,d;r=r?(0,s.merge)({},{headers:null===(o=null===(n=this.instance)||void 0===n?void 0:n.config)||void 0===o?void 0:o.headers,params:null===(a=null===(i=this.instance)||void 0===i?void 0:i.config)||void 0===a?void 0:a.params,data:null===(d=null===(u=this.instance)||void 0===u?void 0:u.config)||void 0===d?void 0:d.data},r||{}):{},t=void 0===t?/.*/:t;const l=(n,o,i)=>{const s=[t,r,n,o,i];return this.addHandler(e,s),this},c=(n,o,i)=>{const s=[t,r,n,o,i,!0];return this.addHandler(e,s),this},h=(n,o,i,s)=>{const a=[t,r,o,i,s,!1,n];return this.addHandler(e,a),this};return{reply:l,replyOnce:c,withDelayInMs:function(e){return function(t,r,n){return h(e,t,r,n)}},passThrough:()=>{const n=[t,r];return this.addHandler(e,n),this},abortRequest(){return l((e=>Promise.reject(new s.XiorError("Request aborted",e))))},abortRequestOnce(){return c((e=>Promise.reject(new s.XiorError("Request aborted",e,{}))))},networkError(){return l((e=>Promise.reject(new s.XiorError("Network Error",e,{}))))},networkErrorOnce(){return c((e=>Promise.reject(new s.XiorError("Network Error",e,{}))))},timeout(){return l((e=>Promise.reject(new s.XiorTimeoutError("timeout of 0ms exceeded",e))))},timeoutOnce(){return c((e=>Promise.reject(new s.XiorTimeoutError("timeout of 0ms exceeded",e))))}}}}addHandler(e,t){var r,n,a;const u=[...t];if(u[3])try{u[3]=JSON.parse(JSON.stringify(u[3]))}catch(e){}if(u[4]){const e="undefined"==typeof Headers?(()=>{const e={};return{append(t,r){e[t]=r+""},get(t){return e[t]||i.nullValue}}})():new Headers;(0,i.keys)(u[4]).forEach((t=>{e.append(t,u[4][t])})),u[4]=e}if("any"===e)o.VERBS.forEach((e=>{var t;this.handlers[e]||(this.handlers[e]=[]),null===(t=this.handlers[e])||void 0===t||t.push(u)}));else{this.handlers[e]||(this.handlers[e]=[]);let t=null===(r=this.handlers[e])||void 0===r?void 0:r.findIndex((e=>6!==e.length&&(0,s.buildSortedURL)(String(e[0]),e[1],s.encodeParams)===(0,s.buildSortedURL)(String(u[0]),u[1],s.encodeParams)));t=void 0===t?-1:t,t>-1&&u.length<6?null===(n=this.handlers[e])||void 0===n||n.splice(t,1,u):null===(a=this.handlers[e])||void 0===a||a.push(u)}}findHandler(e){var t;const{method:r,url:n,headers:o,params:a,data:u={},baseURL:l}=e,c=null==r?void 0:r.toLowerCase();return null===(t=this.handlers[c])||void 0===t?void 0:t.find((t=>{var r;const h=Object.assign({},t[1].headers||{});if((null===(r=e.headers)||void 0===r?void 0:r["Content-Type"])&&((0,i.keys)(h).find((e=>"content-type"===e.toLowerCase()))||(h["Content-Type"]=e.headers["Content-Type"])),"string"==typeof t[0]){const e=l&&t[0].startsWith(l),r=(0,s.buildSortedURL)(e?(0,s.joinPath)(l,n):(0,s.joinPath)("/",n),{b:a,c:u,a:o},s.encodeParams),i=(0,s.buildSortedURL)(e?t[0]:(0,s.joinPath)("/",t[0]),{b:t[1].params||{},c:t[1].data||{},a:h},s.encodeParams);return r===i||r.startsWith(i)||d([[a,t[1].params],[u,t[1].data],[o,h]])}if(t[0]instanceof RegExp)return(t[0].test(n)||t[0].test((0,s.joinPath)(l||"",n)))&&((0,s.buildSortedURL)(c,{b:a,c:u,a:o},s.encodeParams)===(0,s.buildSortedURL)(c,{b:t[1].params||{},c:t[1].data||{},a:h},s.encodeParams)||d([[a,t[1].params],[u,t[1].data],[o,h]]))}))}}},629:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r){const n=t?r(t):"",o=e.includes("?")?"&":"?",i=n?`${e}${o}${n}`:e,[s,a]=i.split("?");if(!a)return i;return`${s}?${a.split("&").sort().join("&")}`}},699:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.anySignal=function(e,t){const r=new AbortController;function o(e){r.abort(e),s()}const i=[];for(const t of e){if(!0===(null==t?void 0:t.aborted)){o(t.reason);break}if(null==t?void 0:t[n.addEventListener]){const e=()=>{o(t.reason)};i.push((()=>{var r;null===(r=t.removeEventListener)||void 0===r||r.call(t,n.abort,e)})),t[n.addEventListener](n.abort,e)}}function s(){i.forEach((e=>e())),null==t||t()}const a=r.signal;return a.clear=s,a};const n=r(330)},729:function(e,t,r){Object.defineProperty(t,"__esModule",{value:!0}),t.merge=void 0;const n=r(330),o=n.O.getPrototypeOf,i=e=>{if(e!==n.nullValue&&typeof e===n.o){if(typeof o===n.f){const t=o(e);return t===n.op||t===n.nullValue}return n.op.toString.call(e)===`[${n.o} Object]`}return!1};t.merge=(...e)=>e.reduce(((e,r)=>{if((0,n.isArray)(r))throw new TypeError(`Arguments must be ${n.o}s, not arrays.`);return(0,n.keys)(r).forEach((o=>{["__proto__","constructor",n.p].includes(o)||((0,n.isArray)(e[o])&&(0,n.isArray)(r[o])?e[o]=Array.from(new Set(e[o].concat(r[o]))):i(e[o])&&i(r[o])?e[o]=(0,t.merge)(e[o],r[o]):e[o]=r[o])})),e}),{})},732:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.VERBS=void 0,t.VERBS=["get","post","head","delete","patch","put","options"]},976:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var o=Object.getOwnPropertyDescriptor(t,r);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,o)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),o=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.XiorTimeoutError=t.XiorError=void 0,t.encodeParams=function e(t,r=!0,n=i.nullValue,o){if(t===i.undefinedValue||t===i.nullValue)return"";const s=[],a=r?encodeURIComponent:e=>e,u=(0,i.isArray)(t),{arrayFormat:d,allowDots:l,serializeDate:c}=o||{},h=e=>{if(l&&!u)return`.${e}`;if(u){if("brackets"===d)return"[]";if("repeat"===d)return""}return`[${e}]`};for(const u in t)if(i.op.hasOwnProperty.call(t,u)){let d=t[u];if(d!==i.undefinedValue){const t=n?`${n}${h(u)}`:a(u);if(!isNaN(d)&&d instanceof Date&&(d=c?c(d):d.toISOString()),typeof d===i.o){const n=e(d,r,t,o);""!==n&&s.push(n)}else s.push(`${a(t)}=${a(d)}`)}}return s.join("&")},t.trimUndefined=function e(t){return(0,i.isArray)(t)?t.map(e):(t&&typeof t===i.o&&(0,i.keys)(t).forEach((r=>{const n=t[r];n===i.undefinedValue?delete t[r]:e(n)})),t)},t.isAbsoluteURL=function(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)},t.joinPath=function(e,t){return e?t?(e.endsWith("/")?e:e+"/")+("/"===t[0]?t.slice(1):t):e:t||""},t.isXiorError=function(e){return(null==e?void 0:e.name)===s||(null==e?void 0:e.name)===a};const i=r(330);o(r(699),t),o(r(729),t),o(r(99),t);const s="XiorError",a="XiorTimeoutError";class u extends Error{constructor(e,t,r){super(e),this.name=s,this.request=t,this.config=t,this.response=r}}t.XiorError=u,t.XiorTimeoutError=class extends u{constructor(e,t,r){super(e,t,r),this.name=a}}}},t={},r=function r(n){var o=t[n];if(void 0!==o)return o.exports;var i=t[n]={exports:{}};return e[n].call(i.exports,i,i.exports,r),i.exports}(486);return r.default}()}));