UNPKG

mappersmith

Version:

It is a lightweight rest client for node.js and the browser

3 lines 17 kB
var T=class{allowResourceHostOverride;authAttr;binary;bodyAttr;headers;headersAttr;host;hostAttr;method;middleware;parameterEncoder;params;path;pathAttr;queryParamAlias;signalAttr;timeoutAttr;constructor(e){this.allowResourceHostOverride=e.allowResourceHostOverride||!1,this.binary=e.binary||!1,this.headers=e.headers,this.host=e.host,this.method=e.method||"get",this.parameterEncoder=e.parameterEncoder||encodeURIComponent,this.params=e.params,this.path=e.path,this.queryParamAlias=e.queryParamAlias||{},this.authAttr=e.authAttr||"auth",this.bodyAttr=e.bodyAttr||"body",this.headersAttr=e.headersAttr||"headers",this.hostAttr=e.hostAttr||"host",this.pathAttr=e.pathAttr||"path",this.signalAttr=e.signalAttr||"signal",this.timeoutAttr=e.timeoutAttr||"timeout";let t=e.middleware||e.middlewares||[];this.middleware=t}};var A,q,B;try{A=eval('typeof __TEST_WEB__ === "undefined" && typeof process === "object" ? process : undefined')}catch(o){}var X=()=>typeof A<"u"&&A!==null&&A.hrtime;X()&&(q=()=>{let o=A.hrtime();return o[0]*1e9+o[1]},B=q());var Y=/%20/g,x=o=>o!=null,de=o=>Object.keys(o).filter(e=>x(o[e])),F=(o,e,t="",r=encodeURIComponent)=>Array.isArray(e)?e.map(s=>F(o,s,t+"[]",r)).join("&"):typeof e!="object"?`${r(o+t)}=${r(e)}`:Object.keys(e).map(s=>{let i=e[s];return x(i)?F(o,i,t+"["+s+"]",r):null}).filter(x).join("&"),M=(o,e=encodeURIComponent)=>D(o)?Object.keys(o).map(t=>{let r=o[t];return x(r)?F(t,r,"",e):null}).filter(x).join("&").replace(Y,"+"):o,H=()=>{if(X()&&q!==void 0){let o=q();if(o!==void 0&&B!==void 0)return(o-B)/1e6}return Date.now()},K=o=>{let e={};if(!o)return e;let t=o.split(`\r `);for(let r=0;r<t.length;r++){let s=t[r],i=s.indexOf(": ");if(i>0){let a=s.substring(0,i).toLowerCase().trim(),c=s.substring(i+2).trim();e[a]=c}}return e},O=o=>Object.keys(o).reduce((e,t)=>(e[t.toLowerCase()]=o[t],e),{}),Z=Object.prototype.hasOwnProperty,h=Object.assign||function(o){for(let e=1;e<arguments.length;e++){let t=arguments[e];for(let r in t)Z.call(t,r)&&(o[r]=t[r])}return o},ee=Object.prototype.toString,D=o=>ee.call(o)==="[object Object]"&&Object.getPrototypeOf(o)===Object.getPrototypeOf({}),le=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),te="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",k=o=>{let e="",t=te,r=String(o);for(let s=0,i,a=0;r.charAt(a|0)||(t="=",a%1);e+=t.charAt(63&s>>8-a%1*8)){if(i=r.charCodeAt(a+=3/4),i>255)throw new Error("[Mappersmith] 'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");s=s<<8|i}return e};var S=class{allowResourceHostOverride;authAttr;bodyAttr;clientId;context;gatewayConfigs;headersAttr;host;hostAttr;middleware;parameterEncoder;resources;signalAttr;timeoutAttr;constructor(e,{gatewayConfigs:t,middleware:r=[],context:s={}}){this.allowResourceHostOverride=e.allowResourceHostOverride||!1,this.authAttr=e.authAttr,this.bodyAttr=e.bodyAttr,this.clientId=e.clientId||null,this.context=s,this.gatewayConfigs=h({},t,e.gatewayConfigs),this.headersAttr=e.headersAttr,this.host=e.host,this.hostAttr=e.hostAttr,this.parameterEncoder=e.parameterEncoder||encodeURIComponent,this.resources=e.resources||{},this.signalAttr=e.signalAttr,this.timeoutAttr=e.timeoutAttr;let i=e.middleware||e.middlewares||[];e.ignoreGlobalMiddleware?this.middleware=i:this.middleware=[...i,...r]}eachResource(e){Object.keys(this.resources).forEach(t=>{let r=this.eachMethod(t,s=>({name:s,descriptor:this.createMethodDescriptor(t,s)}));e(t,r)})}eachMethod(e,t){return Object.keys(this.resources[e]).map(t)}createMethodDescriptor(e,t){let r=this.resources[e][t];if(!r||!["string","function"].includes(typeof r.path))throw new Error(`[Mappersmith] path is undefined for resource "${e}" method "${t}"`);return new T(h({host:this.host,allowResourceHostOverride:this.allowResourceHostOverride,parameterEncoder:this.parameterEncoder,bodyAttr:this.bodyAttr,headersAttr:this.headersAttr,authAttr:this.authAttr,timeoutAttr:this.timeoutAttr,hostAttr:this.hostAttr,signalAttr:this.signalAttr},r))}createMiddleware(e){let t=c=>{let m={__name:c.name||c.toString(),response(u){return u()},prepareRequest(u){return this.request?u().then(p=>{var l;return(l=this.request)==null?void 0:l.call(this,p)}):u()}},f=h(e,{clientId:this.clientId,context:h({},this.context)});return h(m,c(f))},{resourceName:r,resourceMethod:s}=e;return[...this.createMethodDescriptor(r,s).middleware,...this.middleware].map(t)}};var J=/{([^}?]+)\??}/,re=/\/?{([^}?]+)\?}/g,se=/\/$/,C=class o{methodDescriptor;requestParams;requestContext;constructor(e,t={},r={}){this.methodDescriptor=e,this.requestParams=t,this.requestContext=r}isParam(e){return e!==this.methodDescriptor.headersAttr&&e!==this.methodDescriptor.bodyAttr&&e!==this.methodDescriptor.authAttr&&e!==this.methodDescriptor.timeoutAttr&&e!==this.methodDescriptor.hostAttr&&e!==this.methodDescriptor.signalAttr&&e!==this.methodDescriptor.pathAttr}params(){let e=h({},this.methodDescriptor.params,this.requestParams);return Object.keys(e).reduce((t,r)=>(this.isParam(r)&&(t[r]=e[r]),t),{})}context(){return this.requestContext}method(){return this.methodDescriptor.method.toLowerCase()}host(){let{allowResourceHostOverride:e,hostAttr:t,host:r}=this.methodDescriptor,s=e?this.requestParams[t]||r||"":r||"";return typeof s=="string"?s.replace(se,""):""}path(){let{pathAttr:e,path:t}=this.methodDescriptor,r=this.requestParams[e]||t||"",s=this.params(),i;if(typeof r=="function"){if(i=r(s),typeof i!="string")throw new Error(`[Mappersmith] method descriptor function did not return a string, params=${JSON.stringify(s)}`)}else i=r;let a=new RegExp(J,"g"),c=[],m;for(;(m=a.exec(i))!==null;)c.push(m[1]);for(let l of c){let n=new RegExp(`{${l}\\??}`,"g"),d=s[l];d!=null&&typeof d!="object"&&(i=i.replace(n,this.methodDescriptor.parameterEncoder(d)),delete s[l])}i=i.replace(re,"");let f=i.match(J);if(f)throw new Error(`[Mappersmith] required parameter missing (${f[1]}), "${i}" cannot be resolved`);let u=Object.keys(s).reduce((l,n)=>{let d=this.methodDescriptor.queryParamAlias[n]||n,y=s[n];return y!=null&&(l[d]=y),l},{}),p=M(u,this.methodDescriptor.parameterEncoder);if(typeof p=="string"&&p.length!==0){let l=i.includes("?");i+=`${l?"&":"?"}${p}`}return i[0]!=="/"&&i.length>0&&(i=`/${i}`),i}pathTemplate(){let e=this.methodDescriptor.path,t=r=>r[0]!=="/"?`/${r}`:r;return t(typeof e=="function"?e(this.params()):e)}url(){return`${this.host()}${this.path()}`}headers(){let e=this.methodDescriptor.headersAttr,t=this.requestParams[e]||{};if(typeof t=="function")return t;let r={...this.methodDescriptor.headers,...t};return O(r)}header(e){let t=e.toLowerCase();if(t in this.headers())return this.headers()[t]}body(){return this.requestParams[this.methodDescriptor.bodyAttr]}auth(){return this.requestParams[this.methodDescriptor.authAttr]}timeout(){return this.requestParams[this.methodDescriptor.timeoutAttr]}signal(){return this.requestParams[this.methodDescriptor.signalAttr]}enhance(e,t){let r=this.methodDescriptor.authAttr,s=this.methodDescriptor.bodyAttr,i=this.methodDescriptor.headersAttr,a=this.methodDescriptor.hostAttr,c=this.methodDescriptor.timeoutAttr,m=this.methodDescriptor.pathAttr,f=this.methodDescriptor.signalAttr,u=h({},this.requestParams,e.params),p=this.requestParams[i],l=h({},p,e.headers);u[i]=l,e.auth&&(u[r]=e.auth),e.body&&(u[s]=e.body),e.host&&(u[a]=e.host),e.timeout&&(u[c]=e.timeout),e.path&&(u[m]=e.path),e.signal&&(u[f]=e.signal);let n={...this.requestContext,...t};return new o(this.methodDescriptor,u,n)}isBinary(){return this.methodDescriptor.binary}};var oe=o=>!(!o||!o()),v=class{Promise;manifest;GatewayClassFactory;maxMiddlewareStackExecutionAllowed;constructor(e,t,r){if(!e)throw new Error(`[Mappersmith] invalid manifest (${e})`);if(!oe(t))throw new Error("[Mappersmith] gateway class not configured (configs.gateway)");if(!r.Promise)throw new Error("[Mappersmith] Promise not configured (configs.Promise)");this.Promise=r.Promise,this.manifest=new S(e,r),this.GatewayClassFactory=t,this.maxMiddlewareStackExecutionAllowed=r.maxMiddlewareStackExecutionAllowed}build(){let e={_manifest:this.manifest};return this.manifest.eachResource((t,r)=>{e[t]=this.buildResource(t,r)}),e}buildResource(e,t){let r={};return t.reduce((i,a)=>{let c=(m,f)=>{let u=new C(a.descriptor,m,f);return this.invokeMiddlewares(String(e),a.name,u)};return{...i,[a.name]:c}},r)}invokeMiddlewares(e,t,r){let s=this.manifest.createMiddleware({resourceName:e,resourceMethod:t}),i=this.GatewayClassFactory(),a=this.manifest.gatewayConfigs,c={middleware:null,returnedInvalidRequest:!1,abortExecution:!1},m=()=>this.Promise.resolve(r),f=(n,d)=>()=>{let y=g=>{throw c.abortExecution=!0,g};return this.Promise.resolve().then(()=>d.prepareRequest(n,y)).then(g=>{if(g instanceof C)return g;c.returnedInvalidRequest=!0;let b=typeof g,_=(b==="object"||b==="function")&&g.name||b;throw new Error(`[Mappersmith] middleware "${d.__name}" should return "Request" but returned "${_}"`)}).catch(g=>{throw c.middleware=d.__name||null,g})},u=s.reduce(f,m),p=0,l=()=>u().catch(n=>{let{returnedInvalidRequest:d,abortExecution:y,middleware:g}=c;if(d||y)throw n;let b=new Error(`[Mappersmith] middleware "${g}" failed in the request phase: ${n.message}`);throw b.stack=n.stack,b}).then(n=>{if(p++,p>this.maxMiddlewareStackExecutionAllowed)throw new Error(`[Mappersmith] infinite loop detected (middleware stack invoked ${p} times). Check the use of "renew" in one of the middleware.`);let d=l,y=(_,W)=>()=>W.response(_,d,n),g=()=>new i(n,a).call();return s.reduce(y,g)()});return new this.Promise((n,d)=>{l().then(y=>n(y)).catch(d)})}};var ie=/^application\/(json|.*\+json)/,R=class o{originalRequest;responseStatus;responseData;responseHeaders;errors;timeElapsed;constructor(e,t,r,s,i){let a=e.requestParams&&e.requestParams.auth;if(a){let c={...a,password:"***"};this.originalRequest=e.enhance({auth:c})}else this.originalRequest=e;this.responseStatus=t,this.responseData=r??null,this.responseHeaders=s||{},this.errors=i||[],this.timeElapsed=null}request(){return this.originalRequest}status(){return this.responseStatus===1223?204:this.responseStatus}success(){let e=this.status();return e>=200&&e<400}headers(){return O(this.responseHeaders)}header(e){let t=e.toLowerCase();if(t in this.headers())return this.headers()[t]}rawData(){return this.responseData}data(){if(this.isContentTypeJSON()&&this.responseData!==null)try{return JSON.parse(this.responseData)}catch{}return this.responseData}isContentTypeJSON(){let e=this.header("content-type");return e===void 0?!1:ie.test(e)}error(){let e=this.errors[this.errors.length-1]||null;return typeof e=="string"?new Error(e):e}enhance(e){let t={...this.headers(),...e.headers||{}},r=new o(this.request(),e.status||this.status(),e.rawData||this.rawData(),t,e.error?[...this.errors,e.error]:[...this.errors]);return r.timeElapsed=this.timeElapsed,r}},G=R;var U="2.45.0";var w={context:{},middleware:[],Promise:typeof Promise=="function"?Promise:null,fetch:typeof fetch=="function"?fetch:null,maxMiddlewareStackExecutionAllowed:2,gateway:null,gatewayConfigs:{emulateHTTP:!1,enableHTTP408OnTimeouts:!1,XHR:{withCredentials:!1,configure:null},HTTP:{useSocketConnectionTimeout:!1,configure:null,onRequestWillStart:null,onRequestSocketAssigned:null,onSocketLookup:null,onSocketConnect:null,onSocketSecureConnect:null,onResponseReadable:null,onResponseEnd:null},Fetch:{credentials:"omit"}}},ne=o=>{console.warn("The use of setContext is deprecated - you need to find another way to pass data between your middlewares."),w.context=h(w.context,o)};function I(o){let e=()=>w.gateway;return new v(o,e,w).build()}var z=o=>o&&o.name==="TimeoutError",E=o=>{let e=new Error(o);return e.name="TimeoutError",e};var ae=/^(delete|put|patch)/i,P=class{request;configs;successCallback;failCallback;constructor(e,t){this.request=e,this.configs=t,this.successCallback=function(){},this.failCallback=function(){}}get(){throw new Error("Not implemented")}head(){throw new Error("Not implemented")}post(){throw new Error("Not implemented")}put(){throw new Error("Not implemented")}patch(){throw new Error("Not implemented")}delete(){throw new Error("Not implemented")}options(){return this.configs}shouldEmulateHTTP(){return this.options().emulateHTTP&&ae.test(this.request.method())}call(){let e=H();if(!w.Promise)throw new Error("[Mappersmith] Promise not configured (configs.Promise)");return new w.Promise((t,r)=>{this.successCallback=s=>{s.timeElapsed=H()-e,t(s)},this.failCallback=s=>{s.timeElapsed=H()-e,r(s)};try{this[this.request.method()].apply(this,arguments)}catch(s){let i=s;this.dispatchClientError(i.message,i)}})}dispatchResponse(e){e.success()?this.successCallback(e):this.failCallback(e)}dispatchClientError(e,t){z(t)&&this.options().enableHTTP408OnTimeouts?this.failCallback(new R(this.request,408,e,{},[t])):this.failCallback(new R(this.request,400,e,{},[t]))}prepareBody(e,t){let r=this.request.body();this.shouldEmulateHTTP()&&(r=r||{},D(r)&&(r._method=e),t["x-http-method-override"]=e);let s=M(r);return s&&D(r)&&(t["content-type"]="application/x-www-form-urlencoded;charset=utf-8"),s}};var L;try{L=window.btoa}catch{L=k}var N=class extends P{canceled=!1;timer;get(){let e=this.createXHR();e.open("GET",this.request.url(),!0),this.setHeaders(e,{}),this.configureTimeout(e),this.configureBinary(e),this.configureAbort(e),e.send()}head(){let e=this.createXHR();e.open("HEAD",this.request.url(),!0),this.setHeaders(e,{}),this.configureTimeout(e),this.configureBinary(e),this.configureAbort(e),e.send()}post(){this.performRequest("post")}put(){this.performRequest("put")}patch(){this.performRequest("patch")}delete(){this.performRequest("delete")}configureBinary(e){this.request.isBinary()&&(e.responseType="blob")}configureTimeout(e){this.canceled=!1,this.timer=void 0;let t=this.request.timeout();t&&(e.timeout=t,e.addEventListener("timeout",()=>{this.canceled=!0,this.timer&&clearTimeout(this.timer);let r=E(`Timeout (${t}ms)`);this.dispatchClientError(r.message,r)}),this.timer=setTimeout(()=>{this.canceled=!0;let r=E(`Timeout (${t}ms)`);this.dispatchClientError(r.message,r)},t+1))}configureAbort(e){let t=this.request.signal();t&&(t.addEventListener("abort",()=>{e.abort()}),e.addEventListener("abort",()=>{this.dispatchClientError("The operation was aborted",new Error("The operation was aborted"))}))}configureCallbacks(e){e.addEventListener("load",()=>{this.canceled||(this.timer&&clearTimeout(this.timer),this.dispatchResponse(this.createResponse(e)))}),e.addEventListener("error",r=>{if(this.canceled)return;this.timer&&clearTimeout(this.timer);let s=r?r.message||r.name:e.responseText,i="Network error",a=s?`: ${s}`:"",c=new Error(`${i}${a}`);this.dispatchClientError(i,c)});let t=this.options().XHR;t.withCredentials&&(e.withCredentials=!0),t.configure&&t.configure(e)}performRequest(e){let t=this.shouldEmulateHTTP()?"post":e,r=this.createXHR();r.open(t.toUpperCase(),this.request.url(),!0);let s={},i=this.prepareBody(e,s);this.setHeaders(r,s),this.configureTimeout(r),this.configureBinary(r),this.configureAbort(r),r.send(i)}createResponse(e){let t=e.status,r=this.request.isBinary()?e.response:e.responseText,s=K(e.getAllResponseHeaders());return new G(this.request,t,r,s)}setHeaders(e,t){let r=this.request.auth(),s=h(t,{...this.request.headers(),...r?{authorization:`Basic ${L(`${r.username}:${r.password}`)}`}:{}});Object.keys(s).forEach(i=>{e.setRequestHeader(i,`${s[i]}`)})}createXHR(){let e=new XMLHttpRequest;return this.configureCallbacks(e),e}};var j=class extends P{get(){this.performRequest("get")}head(){this.performRequest("head")}post(){this.performRequest("post")}put(){this.performRequest("put")}patch(){this.performRequest("patch")}delete(){this.performRequest("delete")}performRequest(e){let t=w.fetch;if(!t)throw new Error('[Mappersmith] global fetch does not exist, please assign "configs.fetch" to a valid implementation');let r={},s=this.prepareBody(e,r),i=this.request.auth();if(i){let n=i.username||"",d=i.password||"";r.authorization=`Basic ${k(`${n}:${d}`)}`}let a=h(r,this.request.headers()),c=this.shouldEmulateHTTP()?"post":e,m=this.request.signal(),f=h({method:c,headers:a,body:s,signal:m},this.options().Fetch),u=this.request.timeout(),p=null,l=!1;u&&(p=setTimeout(()=>{l=!0;let n=E(`Timeout (${u}ms)`);this.dispatchClientError(n.message,n)},u)),t(this.request.url(),f).then(n=>{if(l)return;p&&clearTimeout(p);let d;this.request.isBinary()?typeof n.buffer=="function"?d=n.buffer():d=n.arrayBuffer():d=n.text(),d.then(y=>{this.dispatchResponse(this.createResponse(n,y))})}).catch(n=>{l||(p&&clearTimeout(p),this.dispatchClientError(n.message,n))})}createResponse(e,t){let r=e.status,s={};return e.headers.forEach((i,a)=>{s[a]=i}),new G(this.request,r,t,s)}};var Q=null,$=null;try{Q=eval('typeof __TEST_SERVICE_WORKER__ === "undefined" && typeof process === "object" ? process : undefined')}catch(o){}typeof XMLHttpRequest<"u"?$=N:typeof Q<"u"?$=void 0:typeof self<"u"&&($=j);w.gateway=$;export{R as Response,w as configs,I as default,I as forge,ne as setContext,U as version}; //# sourceMappingURL=mappersmith.production.min.mjs.map