@automationcloud/client
Advanced tools
Comparing version 1.4.2 to 1.4.3
@@ -1,1 +0,1 @@ | ||
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.AutomationCloud=e():t.AutomationCloud=e()}(self,(function(){return t={739:t=>{self,t.exports=(()=>{"use strict";var t={300:(t,e)=>{var n=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n)return n;throw new Error("unable to locate global object")}();t.exports=e=n.fetch,n.fetch&&(e.default=n.fetch.bind(n)),e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response},395:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AuthAgent=void 0,e.AuthAgent=class{}},614:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BasicAuthAgent=void 0;const s=n(395),r=n(20);class o extends s.AuthAgent{constructor(t){super(),this.params=t}async getHeader(){const{username:t,password:e}=this.params,n=`${t}:${e}`;return"Basic "+r.toBase64(n)}invalidate(){}}e.BasicAuthAgent=o},924:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BearerAuthAgent=void 0;const s=n(395);class r extends s.AuthAgent{constructor(t){super(),this.params=t}async getHeader(){const{prefix:t="Bearer",token:e}=this.params;return e?`${t} ${e}`:null}invalidate(){}}e.BearerAuthAgent=r},12:function(t,e,n){var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||e.hasOwnProperty(n)||s(e,t,n)};Object.defineProperty(e,"__esModule",{value:!0}),r(n(26),e),r(n(614),e),r(n(924),e),r(n(890),e),r(n(658),e)},26:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NoAuthAgent=void 0;const s=n(395);class r extends s.AuthAgent{async getHeader(){return null}invalidate(){}}e.NoAuthAgent=r},890:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AuthNotSupportedError=e.OAuth1Agent=void 0;const s=n(395),r=n(222);class o extends s.AuthAgent{async getHeader(t){throw new a}invalidate(){}}e.OAuth1Agent=o;class a extends r.Exception{constructor(){super("This auth agent is not supported in browser environment.")}}e.AuthNotSupportedError=a},658:function(t,e,n){var s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.OAuth2Agent=e.OAuth2GrantType=void 0;const r=n(458),o=s(n(91)),a=n(395);var i;!function(t){t.CLIENT_CREDENTIALS="client_credentials",t.REFRESH_TOKEN="refresh_token",t.AUTHORIZATION_CODE="authorization_code",t.PASSWORD="password"}(i=e.OAuth2GrantType||(e.OAuth2GrantType={}));class c extends a.AuthAgent{constructor(t){super(),this.params=Object.assign({fetch:o.default},t)}async getHeader(){const t=await this.getAccessToken();return t?"Bearer "+t:null}async createToken(t){const{tokenUrl:e,fetch:n}=this.params,s=new r.Request({fetch:n}),o=Object.entries(t).filter((([t,e])=>null!=e)),a=await s.send("post",e,{body:new URLSearchParams(o)}),i=await a.json();return{accessToken:i.access_token,accessExpiresIn:i.expires_in,refreshToken:i.refresh_token}}setTokens(t){const{accessToken:e,accessExpiresIn:n,refreshToken:s}=t,r=n?Date.now()+1e3*n:null;this.params.accessToken=e,this.params.expiresAt=r,s&&(this.params.refreshToken=s)}invalidate(){this.params.accessToken=null,this.params.expiresAt=null}async getAccessToken(){const t=[this.tryCachedAccessToken,this.tryRefreshToken,this.tryClientSecret];for(const e of t)try{const t=await e.call(this);if(t)return t}catch(t){this.invalidate()}return null}async tryCachedAccessToken(){const{accessToken:t,expiresAt:e,minValiditySeconds:n=300}=this.params,s=null!=e&&e-1e3*n>Date.now();return t&&s?t:null}async tryRefreshToken(){const{refreshToken:t,clientId:e,clientSecret:n}=this.params;if(!t)return null;try{const s=await this.createToken({grant_type:i.REFRESH_TOKEN,client_id:e,client_secret:n,refresh_token:t});return this.setTokens(s),s.accessToken}catch(t){throw this.params.refreshToken=null,t}}async tryClientSecret(){const{clientId:t,clientSecret:e}=this.params;if(!e)return null;const n=await this.createToken({grant_type:i.CLIENT_CREDENTIALS,client_id:t,client_secret:e});return this.setTokens(n),n.accessToken}}e.OAuth2Agent=c},222:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Exception=void 0;class n extends Error{constructor(){super(...arguments),this.name=this.constructor.name,this.status=500,this.details={}}}e.Exception=n},91:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default="undefined"!=typeof window&&window.fetch?fetch.bind(window):n(300)},863:function(t,e,n){var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||e.hasOwnProperty(n)||s(e,t,n)},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.Response=void 0,r(n(458),e),r(n(12),e),r(n(157),e),r(n(687),e);const a=o(n(210));e.Response=a.default},458:function(t,e,n){var s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.RequestFailedError=e.Request=e.DEFAULT_REQUEST_CONFIG=e.NETWORK_ERRORS=void 0;const r=n(222),o=n(12),a=s(n(91));e.NETWORK_ERRORS=["EAI_AGAIN","EHOSTDOWN","EHOSTUNREACH","ECONNABORTED","ECONNREFUSED","ECONNRESET","EPIPE"],e.DEFAULT_REQUEST_CONFIG={baseUrl:"",auth:new o.NoAuthAgent,retryAttempts:4,retryDelay:500,retryDelayIncrement:500,retryStatusCodes:[429,502,503,504],authInvalidateStatusCodes:[401,403],authInvalidateInterval:6e4,headers:{},fetch:a.default},e.Request=class{constructor(t){this.authInvalidatedAt=0,this.config=Object.assign(Object.assign({},e.DEFAULT_REQUEST_CONFIG),t)}async get(t,e={}){return await this.sendJson("get",t,e)}async post(t,e={}){return await this.sendJson("post",t,e)}async put(t,e={}){return await this.sendJson("put",t,e)}async delete(t,e={}){return await this.sendJson("delete",t,e)}async sendJson(t,e,n={}){const{body:s,query:r,headers:o}=n,a=await this.send(t,e,{headers:Object.assign({"content-type":"application/json"},o),query:r,body:s?JSON.stringify(s):null}),{status:i}=a;return 204===i||"0"===a.headers.get("content-length")?null:await a.json()}async send(t,n,s={}){var r,o,a;const{fetch:i}=this.config,c=Math.max(this.config.retryAttempts+1,1);let u,l;for(let h=0;h<c;h++){let c=!1,d=this.config.retryDelay+this.config.retryDelayIncrement*h;try{const e=await this.prepareRequestSpec(t,n,s),r=await i(e.url,{method:e.method,headers:e.headers,body:e.body});if(!r.ok)throw this.config.authInvalidateStatusCodes.includes(r.status)?(c=Date.now()-this.authInvalidatedAt>this.config.authInvalidateInterval,this.authInvalidatedAt=Date.now(),d=0,this.config.auth.invalidate()):c=this.config.retryStatusCodes.includes(r.status),await this.createErrorFromResponse(e,r);return r}catch(i){const h=null===(r=i.details)||void 0===r?void 0:r.status,p=null===(o=i.details)||void 0===o?void 0:o.statusText,f={method:t,url:n,headers:null!==(a=s.headers)&&void 0!==a?a:{},status:h,statusText:p};if(c||e.NETWORK_ERRORS.includes(i.code)){u=i,l=f,this.onRetry(i,f),await new Promise((t=>setTimeout(t,d)));continue}throw this.onError(i,f),i}}throw this.onError(u,l),u}async sendRaw(t,e,n={}){const s=await this.prepareRequestSpec(t,e,n),{fetch:r}=this.config;return await r(s.url,{method:s.method,headers:s.headers,body:s.body})}async prepareRequestSpec(t,e,n={}){var s,r;const{auth:o}=this.config,{body:a}=n,i=this.prepareUrl(e,n),c=null!==(s=await o.getHeader({url:i,method:t,body:a}))&&void 0!==s?s:"";return{method:t,url:i,headers:this.mergeHeaders({"content-type":null!==(r=this.inferContentTypeFromBody(a))&&void 0!==r?r:""},this.config.headers||{},{authorization:c},n.headers||{}),body:a}}prepareUrl(t,e){var n;const{baseUrl:s}=this.config,r=s&&"/"!==s.slice(-1)?s+"/":s,o=new URL("/"===t[0]?t.slice(1):t,r||void 0);return o.search=new URLSearchParams(Object.entries(null!==(n=e.query)&&void 0!==n?n:{})).toString(),o.toString()}inferContentTypeFromBody(t){switch(!0){case null==t:return null;case t instanceof URLSearchParams:return"application/x-www-form-urlencoded";case"object"==typeof t:return"application/json";case"string"==typeof t:return"text/plain";default:return null}}mergeHeaders(...t){const e={};for(const n of t)for(const[t,s]of Object.entries(n))s&&(e[t.toLowerCase()]=s);return e}async createErrorFromResponse(t,e){return new i(t,e)}onRetry(t,e){}onError(t,e){}};class i extends r.Exception{constructor(t,e){super(`Request failed: ${e.status} ${e.statusText}`),this.details={method:t.method,url:t.url,requestHeaders:t.headers,status:e.status,statusText:e.statusText},Object.defineProperty(this,"requestSpec",{enumerable:!1,value:t}),Object.defineProperty(this,"response",{enumerable:!1,value:e})}}e.RequestFailedError=i},210:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default="undefined"==typeof Response?n(300).Response:Response},157:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0})},20:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.toBase64=void 0,e.toBase64=function(t){return btoa(t)}},687:function(t,e,n){var s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.fetchMock=void 0;const r=s(n(210));e.fetchMock=function(t,e={},n){const s={called:!1,calledCount:0,params:[]},o=(o,a)=>new Promise(((i,c)=>{const u=Object.assign({status:200},t);if(s.called=!0,s.calledCount+=1,s.params.push({fullUrl:o,fetchOptions:a}),n)return c(n);i(new r.default(JSON.stringify(e),u))}));return o.spy=s,o}}},e={};return function n(s){if(e[s])return e[s].exports;var r=e[s]={exports:{}};return t[s].call(r.exports,r,r.exports,n),r.exports}(863)})()},729:t=>{"use strict";var e=Object.prototype.hasOwnProperty,n="~";function s(){}function r(t,e,n){this.fn=t,this.context=e,this.once=n||!1}function o(t,e,s,o,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var i=new r(s,o||t,a),c=n?n+e:e;return t._events[c]?t._events[c].fn?t._events[c]=[t._events[c],i]:t._events[c].push(i):(t._events[c]=i,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new s:delete t._events[e]}function i(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(n=!1)),i.prototype.eventNames=function(){var t,s,r=[];if(0===this._eventsCount)return r;for(s in t=this._events)e.call(t,s)&&r.push(n?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},i.prototype.listeners=function(t){var e=n?n+t:t,s=this._events[e];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,o=s.length,a=new Array(o);r<o;r++)a[r]=s[r].fn;return a},i.prototype.listenerCount=function(t){var e=n?n+t:t,s=this._events[e];return s?s.fn?1:s.length:0},i.prototype.emit=function(t,e,s,r,o,a){var i=n?n+t:t;if(!this._events[i])return!1;var c,u,l=this._events[i],h=arguments.length;if(l.fn){switch(l.once&&this.removeListener(t,l.fn,void 0,!0),h){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,e),!0;case 3:return l.fn.call(l.context,e,s),!0;case 4:return l.fn.call(l.context,e,s,r),!0;case 5:return l.fn.call(l.context,e,s,r,o),!0;case 6:return l.fn.call(l.context,e,s,r,o,a),!0}for(u=1,c=new Array(h-1);u<h;u++)c[u-1]=arguments[u];l.fn.apply(l.context,c)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(t,l[u].fn,void 0,!0),h){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,e);break;case 3:l[u].fn.call(l[u].context,e,s);break;case 4:l[u].fn.call(l[u].context,e,s,r);break;default:if(!c)for(d=1,c=new Array(h-1);d<h;d++)c[d-1]=arguments[d];l[u].fn.apply(l[u].context,c)}}return!0},i.prototype.on=function(t,e,n){return o(this,t,e,n,!1)},i.prototype.once=function(t,e,n){return o(this,t,e,n,!0)},i.prototype.removeListener=function(t,e,s,r){var o=n?n+t:t;if(!this._events[o])return this;if(!e)return a(this,o),this;var i=this._events[o];if(i.fn)i.fn!==e||r&&!i.once||s&&i.context!==s||a(this,o);else{for(var c=0,u=[],l=i.length;c<l;c++)(i[c].fn!==e||r&&!i[c].once||s&&i[c].context!==s)&&u.push(i[c]);u.length?this._events[o]=1===u.length?u[0]:u:a(this,o)}return this},i.prototype.removeAllListeners=function(t){var e;return t?(e=n?n+t:t,this._events[e]&&a(this,e)):(this._events=new s,this._eventsCount=0),this},i.prototype.off=i.prototype.removeListener,i.prototype.addListener=i.prototype.on,i.prefixed=n,i.EventEmitter=i,t.exports=i},330:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.AcRequest=e.AcApi=void 0;const s=n(739);e.AcApi=class{constructor(t){this.params=t;const e="string"==typeof t.auth?new s.BasicAuthAgent({username:t.auth}):new s.OAuth2Agent({clientId:t.auth.clientId,clientSecret:t.auth.clientSecret,tokenUrl:t.apiTokenUrl});this.request=new r({baseUrl:t.apiUrl,auth:e,retryAttempts:t.requestRetryCount,retryDelay:t.requestRetryDelay})}async createJob(t){const{serviceId:e,category:n,input:s}=t;return await this.request.post("/jobs",{body:{serviceId:e,category:n,input:s}})}async getJob(t){return await this.request.get(`/jobs/${t}`)}async getJobAccessToken(t){return(await this.request.get(`/jobs/${t}/end-user`)).token}async getJobEvents(t,e){const{data:n}=await this.request.get(`/jobs/${t}/events`,{query:{offset:e}});return n}async getJobOutputData(t,e){var n;try{return await this.request.get(`/jobs/${t}/outputs/${e}`)}catch(t){if(404===(null===(n=t.details)||void 0===n?void 0:n.status))return null;throw t}}async sendJobInput(t,e,n){return await this.request.post(`/jobs/${t}/inputs`,{body:{key:e,data:n}})}async cancelJob(t){await this.request.post(`/jobs/${t}/cancel`)}async queryPreviousOutputs(t,e,n=[]){const{data:s}=await this.request.post(`/services/${t}/previous-job-outputs`,{body:{inputs:n},query:{key:e}});return s}};class r extends s.Request{async createErrorFromResponse(t,e){var n;if(null===(n=e.headers.get("content-type"))||void 0===n?void 0:n.startsWith("application/json")){const t=await e.json();if(t.name&&t.message){const e=new Error(t.message);return e.name=t.name,e.code=t.code,e.details=t.details,e}}return super.createErrorFromResponse(t,e)}}e.AcRequest=r},967:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Client=void 0;const s=n(330),r=n(909),o=n(157),a=n(894);e.Client=class{constructor(t){this.logger=console,this.config=Object.assign({apiUrl:"https://api.automationcloud.net",apiTokenUrl:"https://auth.automationcloud.net/auth/realms/automationcloud/protocol/openid-connect/token",vaultUrl:"https://vault.automationcloud.net",pollInterval:1e3,requestRetryCount:4,requestRetryDelay:500,autoTrack:!0},t),this.api=new s.AcApi({logger:this.logger,apiTokenUrl:this.config.apiTokenUrl,apiUrl:this.config.apiUrl,auth:this.config.auth,requestRetryCount:this.config.requestRetryCount,requestRetryDelay:this.config.requestRetryDelay}),this.vault=new a.Vault(this)}async getJob(t){const e=new r.Job(this);return await e.trackExisting(t),e}async queryPreviousOutput(t,e=[]){const n=await this.api.queryPreviousOutputs(this.config.serviceId,t,e);return n.length?n[0]:null}async createJob(t={}){return await this._createJob(Object.assign({category:o.JobCategory.TEST,input:{}},t))}async _createJob(t){const e=new r.Job(this,t);return await e.start(),e}}},313:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.JobTrackError=e.JobFailedError=e.JobOutputWaitError=e.JobAlreadyStartedError=e.JobNotInitializedError=void 0;const s=n(222);class r extends s.Exception{constructor(){super("Invalid state: job not yet initialized")}}e.JobNotInitializedError=r;class o extends s.Exception{constructor(t={}){super("Job is already initialized"),this.details=t}}e.JobAlreadyStartedError=o;class a extends s.Exception{constructor(t,e={}){super(t),this.message=t,this.details=e}}e.JobOutputWaitError=a;class i extends s.Exception{constructor(t){var e,n,s;super(null!==(e=null==t?void 0:t.message)&&void 0!==e?e:"Unknown error"),this.name=null!==(n=null==t?void 0:t.code)&&void 0!==n?n:"UnknownError",this.details=Object.assign({category:null!==(s=null==t?void 0:t.category)&&void 0!==s?s:"server"},null==t?void 0:t.details)}}e.JobFailedError=i;class c extends s.Exception{constructor(t){super(`Job tracking failed: ${t.message}`),this.details={cause:t}}}e.JobTrackError=c},222:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Exception=void 0;class n extends Error{constructor(){super(...arguments),this.name=this.constructor.name,this.status=500,this.details={}}}e.Exception=n},863:function(t,e,n){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||Object.prototype.hasOwnProperty.call(e,n)||s(e,t,n)};Object.defineProperty(e,"__esModule",{value:!0}),r(n(330),e),r(n(967),e),r(n(222),e),r(n(313),e),r(n(909),e),r(n(273),e),r(n(157),e),r(n(894),e)},909:function(t,e,n){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&s(e,t,n);return r(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.Job=void 0;const a=n(729),i=o(n(313)),c=n(157);e.Job=class{constructor(t,e={}){this.client=t,this._events=new a.EventEmitter,this._inputsMap=new Map,this._outputsMap=new Map,this._state=c.JobState.CREATED,this._error=null,this._awaitingInputKey=null,this._trackPromise=null,this._jobId=null,this._jobEventOffset=0,this._isTracking=!1,this._initParams=Object.assign({category:c.JobCategory.TEST,input:{}},e)}get jobId(){if(!this._jobId)throw new i.JobNotInitializedError;return this._jobId}async start(){if(this._jobId)throw new i.JobAlreadyStartedError(this.jobId);const{category:t,input:e}=this._initParams,{serviceId:n}=this.client.config,{id:s,state:r}=await this.api.createJob({serviceId:n,category:t,input:e});this._jobId=s,this._setState(r);for(const[t,n]of Object.entries(e))this._inputsMap.set(t,{key:t,data:n});this.client.config.autoTrack&&this.startTracking()}async trackExisting(t){if(this._jobId)throw new i.JobAlreadyStartedError({jobId:this.jobId});const{state:e,category:n}=await this.api.getJob(t);this._jobId=t,this._initParams.category=n,this._setState(e),this.startTracking()}startTracking(){this._trackPromise||(this._isTracking=!0,this._trackPromise=this._track(),this._trackPromise.catch((t=>{})).then((()=>{this._isTracking=!1,this._trackPromise=null})))}stopTracking(){this._isTracking=!1}getState(){return this._state}_setState(t){const e=this._state;this._state=t,this._events.emit("stateChanged",t,e)}getErrorInfo(){return this._error}getAwaitingInputKey(){return this._awaitingInputKey}async getAccessToken(){return await this.api.getJobAccessToken(this.jobId)}async submitInput(t,e){await this.api.sendJobInput(this.jobId,t,e),this._inputsMap.set(t,{key:t,data:e})}async getOutput(t){const e=this._outputsMap.get(t);if(e)return e.data;const n=await this.api.getJobOutputData(this.jobId,t);return null==n?void 0:n.data}async waitForCompletion(){await this._trackPromise}async cancel(){await this.api.cancelJob(this.jobId)}async waitForOutputs(...t){return await this._waitFor((()=>{const e=this._checkOutputs(t);if(null!=e)return e;if(this.getState()===c.JobState.FAIL)throw new i.JobOutputWaitError("Job failed, and specified outputs were not emitted",{state:this.getState(),jobId:this.jobId});if(this.getState()===c.JobState.SUCCESS)throw new i.JobOutputWaitError("Job succeeded, but specified outputs were not emitted",{state:this.getState(),jobId:this.jobId})}))}async _waitFor(t){return new Promise(((e,n)=>{const s=()=>{try{const n=t();void 0!==n&&(o(),e(n))}catch(t){o(),n(t)}},r=t=>{o(),n(t)},o=()=>{this._events.off("trackTick",s),this._events.off("trackError",r)};this._events.on("trackTick",s),this._events.on("trackError",r),s()}))}onAwaitingInput(t,e){return this._createJobEventHandler("awaitingInput",(async n=>{if("*"===t||n===t){const s=await e(n);void 0!==s&&await this.submitInput(t,s)}}))}onOutput(t,e){return this._createJobEventHandler("output",(async n=>{this._matchKey(t,n.key)&&await e(n.data)}))}onDynamicOutput(t,e){return this._createJobEventHandler("output",(async n=>{(n.key.startsWith(t+":")||this._matchKey(t,n.key))&&await e(n.key,n.data)}))}onAnyOutput(t){return this._createJobEventHandler("output",(async e=>{await t(e.key,e.data)}))}onOutputEvent(t,e){return this.onDynamicOutput("events",(async(n,s)=>{s&&"object"==typeof s&&this._matchKey(t,s.type)&&await e(s)}))}onStateChanged(t){return this._createJobEventHandler("stateChanged",t)}onSuccess(t){return this._createJobEventHandler("success",t)}onFail(t){return this._createJobEventHandler("fail",t)}async _track(){for(;this._isTracking;){const{pollInterval:t}=this.client.config;try{const t=await this.api.getJobEvents(this.jobId,this._jobEventOffset);this._jobEventOffset+=t.length;for(const e of t)await this._processJobEvent(e);this._events.emit("trackTick")}catch(t){const e=new i.JobTrackError(t);throw this._events.emit("trackError",e),e}switch(this._state){case c.JobState.SUCCESS:return;case c.JobState.FAIL:throw new i.JobFailedError(this._error)}await new Promise((e=>setTimeout(e,t)))}}async _processJobEvent(t){const e=t.key;switch(t.name){case"awaitingInput":this._setState(c.JobState.AWAITING_INPUT),this._awaitingInputKey=e,this._events.emit("awaitingInput",e);break;case"createOutput":{const t=await this.api.getJobOutputData(this.jobId,e);if(t){const n=t.data;this._outputsMap.set(e,{key:e,data:n}),this._events.emit("output",{key:e,data:n})}}break;case"processing":this._setState(c.JobState.PROCESSING);break;case"success":this._setState(c.JobState.SUCCESS),this._events.emit("success");break;case"fail":{const{error:t}=await this.api.getJob(this.jobId);this._setState(c.JobState.FAIL),this._error=Object.assign({category:"server",code:"UnknownError",message:"Unknown error"},t);const e=new i.JobFailedError(this._error);this._events.emit("fail",e)}}}_checkOutputs(t){const e=[];for(const n of t){const t=this._outputsMap.get(n);if(!t)break;e.push(t.data)}return e.length===t.length?e:null}get api(){return this.client.api}_createJobEventHandler(t,e){const n=async(...t)=>{await e(...t)};return this._events.on(t,n),()=>this._events.off(t,n)}_matchKey(t,e){if(t.endsWith(":*")){const n=t.split(":")[0];return e.startsWith(n+":")}return e===t}}},273:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0})},157:(t,e)=>{"use strict";var n,s;Object.defineProperty(e,"__esModule",{value:!0}),e.JobCategory=e.JobState=void 0,(s=e.JobState||(e.JobState={})).CREATED="created",s.SCHEDULED="scheduled",s.PROCESSING="processing",s.AWAITING_INPUT="awaitingInput",s.AWAITING_TDS="awaitingTds",s.PENDING="pending",s.SUCCESS="success",s.FAIL="fail",(n=e.JobCategory||(e.JobCategory={})).LIVE="live",n.TEST="test"},894:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Vault=void 0;const s=n(739);function r(t){return"string"==typeof t?t:[t.name,t.label,t.placeholder].map((t=>t.replace(/_/g,""))).join("_")}e.Vault=class{constructor(t){this.client=t;const{config:e}=t,n="string"==typeof e.auth?new s.BasicAuthAgent({username:e.auth}):new s.OAuth2Agent({clientId:e.auth.clientId,clientSecret:e.auth.clientSecret,tokenUrl:e.apiTokenUrl});this.request=new s.Request({baseUrl:e.vaultUrl,auth:n})}get api(){return this.client.api}async createOtp(){const{id:t}=await this.request.post("/otp");return t}async createPanToken(t,e){const n=null!=e?e:await this.createOtp(),{panToken:s}=await this.request.post("/pan",{body:{otp:n,pan:t}});return s}getPaymentIframeUrl(t,e={}){var n,s,o;const a=[["otp",t],["css",e.cssUrl],["name",e.name],["fields",null===(n=e.fields)||void 0===n?void 0:n.map(r).join(",")],["brands",null===(s=e.brands)||void 0===s?void 0:s.join(",")],["validateOnInput",!0===e.validateOnInput?"on":void 0]].filter((t=>null!=t[1]));return(null!==(o=e.iframeUrl)&&void 0!==o?o:"https://vault.automationcloud.net/forms/index.html")+"?"+a.map((t=>{var e;return`${t[0]}=${encodeURIComponent(null!==(e=t[1])&&void 0!==e?e:"")}`})).join("&")}getSingleInputIframeUrl(t,e={}){var n;const s=[["otp",t],["css",e.cssUrl],["inputType",e.inputType],["pattern",e.pattern],["minlength",e.minlength],["maxlength",e.maxlength],["required",e.required],["validateOnInput",!0===e.validateOnInput?"on":void 0]].filter((t=>null!=t[1]));return(null!==(n=e.iframeUrl)&&void 0!==n?n:"https://vault.automationcloud.net/forms/single-input.html")+"?"+s.map((t=>{var e;return`${t[0]}=${encodeURIComponent(null!==(e=t[1])&&void 0!==e?e:"")}`})).join("&")}}}},e={},function n(s){if(e[s])return e[s].exports;var r=e[s]={exports:{}};return t[s].call(r.exports,r,r.exports,n),r.exports}(863);var t,e})); | ||
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.AutomationCloud=e():t.AutomationCloud=e()}(self,(function(){return t={739:t=>{self,t.exports=(()=>{"use strict";var t={300:(t,e)=>{var n=function(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==n)return n;throw new Error("unable to locate global object")}();t.exports=e=n.fetch,n.fetch&&(e.default=n.fetch.bind(n)),e.Headers=n.Headers,e.Request=n.Request,e.Response=n.Response},395:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AuthAgent=void 0,e.AuthAgent=class{}},614:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BasicAuthAgent=void 0;const s=n(395),r=n(20);class o extends s.AuthAgent{constructor(t){super(),this.params=t}async getHeader(){const{username:t,password:e}=this.params,n=`${t}:${e}`;return"Basic "+r.toBase64(n)}invalidate(){}}e.BasicAuthAgent=o},924:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.BearerAuthAgent=void 0;const s=n(395);class r extends s.AuthAgent{constructor(t){super(),this.params=t}async getHeader(){const{prefix:t="Bearer",token:e}=this.params;return e?`${t} ${e}`:null}invalidate(){}}e.BearerAuthAgent=r},12:function(t,e,n){var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||e.hasOwnProperty(n)||s(e,t,n)};Object.defineProperty(e,"__esModule",{value:!0}),r(n(26),e),r(n(614),e),r(n(924),e),r(n(890),e),r(n(658),e)},26:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.NoAuthAgent=void 0;const s=n(395);class r extends s.AuthAgent{async getHeader(){return null}invalidate(){}}e.NoAuthAgent=r},890:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AuthNotSupportedError=e.OAuth1Agent=void 0;const s=n(395),r=n(222);class o extends s.AuthAgent{async getHeader(t){throw new a}invalidate(){}}e.OAuth1Agent=o;class a extends r.Exception{constructor(){super("This auth agent is not supported in browser environment.")}}e.AuthNotSupportedError=a},658:function(t,e,n){var s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.OAuth2Agent=e.OAuth2GrantType=void 0;const r=n(458),o=s(n(91)),a=n(395);var i;!function(t){t.CLIENT_CREDENTIALS="client_credentials",t.REFRESH_TOKEN="refresh_token",t.AUTHORIZATION_CODE="authorization_code",t.PASSWORD="password"}(i=e.OAuth2GrantType||(e.OAuth2GrantType={}));class c extends a.AuthAgent{constructor(t){super(),this.params=Object.assign({fetch:o.default},t)}async getHeader(){const t=await this.getAccessToken();return t?"Bearer "+t:null}async createToken(t){const{tokenUrl:e,fetch:n}=this.params,s=new r.Request({fetch:n}),o=Object.entries(t).filter((([t,e])=>null!=e)),a=await s.send("post",e,{body:new URLSearchParams(o)}),i=await a.json();return{accessToken:i.access_token,accessExpiresIn:i.expires_in,refreshToken:i.refresh_token}}setTokens(t){const{accessToken:e,accessExpiresIn:n,refreshToken:s}=t,r=n?Date.now()+1e3*n:null;this.params.accessToken=e,this.params.expiresAt=r,s&&(this.params.refreshToken=s)}invalidate(){this.params.accessToken=null,this.params.expiresAt=null}async getAccessToken(){const t=[this.tryCachedAccessToken,this.tryRefreshToken,this.tryClientSecret];for(const e of t)try{const t=await e.call(this);if(t)return t}catch(t){this.invalidate()}return null}async tryCachedAccessToken(){const{accessToken:t,expiresAt:e,minValiditySeconds:n=300}=this.params;return t&&(null==e||e-1e3*n>Date.now())?t:null}async tryRefreshToken(){const{refreshToken:t,clientId:e,clientSecret:n}=this.params;if(!t)return null;try{const s=await this.createToken({grant_type:i.REFRESH_TOKEN,client_id:e,client_secret:n,refresh_token:t});return this.setTokens(s),s.accessToken}catch(t){throw this.params.refreshToken=null,t}}async tryClientSecret(){const{clientId:t,clientSecret:e}=this.params;if(!e)return null;const n=await this.createToken({grant_type:i.CLIENT_CREDENTIALS,client_id:t,client_secret:e});return this.setTokens(n),n.accessToken}}e.OAuth2Agent=c},222:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Exception=void 0;class n extends Error{constructor(){super(...arguments),this.name=this.constructor.name,this.status=500,this.details={}}}e.Exception=n},91:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default="undefined"!=typeof window&&window.fetch?fetch.bind(window):n(300)},863:function(t,e,n){var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||e.hasOwnProperty(n)||s(e,t,n)},o=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.Response=void 0,r(n(458),e),r(n(395),e),r(n(12),e),r(n(157),e),r(n(687),e);const a=o(n(210));e.Response=a.default},458:function(t,e,n){var s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.RequestFailedError=e.Request=e.DEFAULT_REQUEST_CONFIG=e.NETWORK_ERRORS=void 0;const r=n(222),o=n(12),a=s(n(91));e.NETWORK_ERRORS=["EAI_AGAIN","EHOSTDOWN","EHOSTUNREACH","ECONNABORTED","ECONNREFUSED","ECONNRESET","EPIPE"],e.DEFAULT_REQUEST_CONFIG={baseUrl:"",auth:new o.NoAuthAgent,retryAttempts:4,retryDelay:500,retryDelayIncrement:500,retryStatusCodes:[429,502,503,504],authInvalidateStatusCodes:[401,403],authInvalidateInterval:6e4,headers:{},fetch:a.default},e.Request=class{constructor(t){this.authInvalidatedAt=0,this.config=Object.assign(Object.assign({},e.DEFAULT_REQUEST_CONFIG),t)}async get(t,e={}){return await this.sendJson("get",t,e)}async post(t,e={}){return await this.sendJson("post",t,e)}async put(t,e={}){return await this.sendJson("put",t,e)}async delete(t,e={}){return await this.sendJson("delete",t,e)}async sendJson(t,e,n={}){const{body:s,query:r,headers:o}=n,a=await this.send(t,e,{headers:Object.assign({"content-type":"application/json"},o),query:r,body:s?JSON.stringify(s):null}),{status:i}=a;return 204===i||"0"===a.headers.get("content-length")?null:await a.json()}async send(t,n,s={}){var r,o,a;const{fetch:i}=this.config,c=Math.max(this.config.retryAttempts+1,1);let u,l;for(let h=0;h<c;h++){let c=!1,d=this.config.retryDelay+this.config.retryDelayIncrement*h;try{const e=await this.prepareRequestSpec(t,n,s),r=await i(e.url,{method:e.method,headers:e.headers,body:e.body});if(!r.ok)throw this.config.authInvalidateStatusCodes.includes(r.status)?(c=Date.now()-this.authInvalidatedAt>this.config.authInvalidateInterval,this.authInvalidatedAt=Date.now(),d=0,this.config.auth.invalidate()):c=this.config.retryStatusCodes.includes(r.status),await this.createErrorFromResponse(e,r);return r}catch(i){const h=null===(r=i.details)||void 0===r?void 0:r.status,p=null===(o=i.details)||void 0===o?void 0:o.statusText,f={method:t,url:n,headers:null!==(a=s.headers)&&void 0!==a?a:{},status:h,statusText:p};if(c||e.NETWORK_ERRORS.includes(i.code)){u=i,l=f,this.onRetry(i,f),await new Promise((t=>setTimeout(t,d)));continue}throw this.onError(i,f),i}}throw this.onError(u,l),u}async sendRaw(t,e,n={}){const s=await this.prepareRequestSpec(t,e,n),{fetch:r}=this.config;return await r(s.url,{method:s.method,headers:s.headers,body:s.body})}async prepareRequestSpec(t,e,n={}){var s,r;const{auth:o}=this.config,{body:a}=n,i=this.prepareUrl(e,n),c=null!==(s=await o.getHeader({url:i,method:t,body:a}))&&void 0!==s?s:"";return{method:t,url:i,headers:this.mergeHeaders({"content-type":null!==(r=this.inferContentTypeFromBody(a))&&void 0!==r?r:""},this.config.headers||{},{authorization:c},n.headers||{}),body:a}}prepareUrl(t,e){var n;const{baseUrl:s}=this.config,r=s&&"/"!==s.slice(-1)?s+"/":s,o=new URL("/"===t[0]?t.slice(1):t,r||void 0);return o.search=new URLSearchParams(Object.entries(null!==(n=e.query)&&void 0!==n?n:{})).toString(),o.toString()}inferContentTypeFromBody(t){switch(!0){case null==t:return null;case t instanceof URLSearchParams:return"application/x-www-form-urlencoded";case"object"==typeof t:return"application/json";case"string"==typeof t:return"text/plain";default:return null}}mergeHeaders(...t){const e={};for(const n of t)for(const[t,s]of Object.entries(n))s&&(e[t.toLowerCase()]=s);return e}async createErrorFromResponse(t,e){return new i(t,e)}onRetry(t,e){}onError(t,e){}};class i extends r.Exception{constructor(t,e){super(`Request failed: ${e.status} ${e.statusText}`),this.details={method:t.method,url:t.url,requestHeaders:t.headers,status:e.status,statusText:e.statusText},Object.defineProperty(this,"requestSpec",{enumerable:!1,value:t}),Object.defineProperty(this,"response",{enumerable:!1,value:e})}}e.RequestFailedError=i},210:(t,e,n)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default="undefined"==typeof Response?n(300).Response:Response},157:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0})},20:(t,e)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.toBase64=void 0,e.toBase64=function(t){return btoa(t)}},687:function(t,e,n){var s=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(e,"__esModule",{value:!0}),e.fetchMock=void 0;const r=s(n(210));e.fetchMock=function(t,e={},n){const s={called:!1,calledCount:0,params:[]},o=(o,a)=>new Promise(((i,c)=>{const u=Object.assign({status:200},t);if(s.called=!0,s.calledCount+=1,s.params.push({fullUrl:o,fetchOptions:a}),n)return c(n);i(new r.default(JSON.stringify(e),u))}));return o.spy=s,o}}},e={};return function n(s){if(e[s])return e[s].exports;var r=e[s]={exports:{}};return t[s].call(r.exports,r,r.exports,n),r.exports}(863)})()},729:t=>{"use strict";var e=Object.prototype.hasOwnProperty,n="~";function s(){}function r(t,e,n){this.fn=t,this.context=e,this.once=n||!1}function o(t,e,s,o,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var i=new r(s,o||t,a),c=n?n+e:e;return t._events[c]?t._events[c].fn?t._events[c]=[t._events[c],i]:t._events[c].push(i):(t._events[c]=i,t._eventsCount++),t}function a(t,e){0==--t._eventsCount?t._events=new s:delete t._events[e]}function i(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(n=!1)),i.prototype.eventNames=function(){var t,s,r=[];if(0===this._eventsCount)return r;for(s in t=this._events)e.call(t,s)&&r.push(n?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},i.prototype.listeners=function(t){var e=n?n+t:t,s=this._events[e];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,o=s.length,a=new Array(o);r<o;r++)a[r]=s[r].fn;return a},i.prototype.listenerCount=function(t){var e=n?n+t:t,s=this._events[e];return s?s.fn?1:s.length:0},i.prototype.emit=function(t,e,s,r,o,a){var i=n?n+t:t;if(!this._events[i])return!1;var c,u,l=this._events[i],h=arguments.length;if(l.fn){switch(l.once&&this.removeListener(t,l.fn,void 0,!0),h){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,e),!0;case 3:return l.fn.call(l.context,e,s),!0;case 4:return l.fn.call(l.context,e,s,r),!0;case 5:return l.fn.call(l.context,e,s,r,o),!0;case 6:return l.fn.call(l.context,e,s,r,o,a),!0}for(u=1,c=new Array(h-1);u<h;u++)c[u-1]=arguments[u];l.fn.apply(l.context,c)}else{var d,p=l.length;for(u=0;u<p;u++)switch(l[u].once&&this.removeListener(t,l[u].fn,void 0,!0),h){case 1:l[u].fn.call(l[u].context);break;case 2:l[u].fn.call(l[u].context,e);break;case 3:l[u].fn.call(l[u].context,e,s);break;case 4:l[u].fn.call(l[u].context,e,s,r);break;default:if(!c)for(d=1,c=new Array(h-1);d<h;d++)c[d-1]=arguments[d];l[u].fn.apply(l[u].context,c)}}return!0},i.prototype.on=function(t,e,n){return o(this,t,e,n,!1)},i.prototype.once=function(t,e,n){return o(this,t,e,n,!0)},i.prototype.removeListener=function(t,e,s,r){var o=n?n+t:t;if(!this._events[o])return this;if(!e)return a(this,o),this;var i=this._events[o];if(i.fn)i.fn!==e||r&&!i.once||s&&i.context!==s||a(this,o);else{for(var c=0,u=[],l=i.length;c<l;c++)(i[c].fn!==e||r&&!i[c].once||s&&i[c].context!==s)&&u.push(i[c]);u.length?this._events[o]=1===u.length?u[0]:u:a(this,o)}return this},i.prototype.removeAllListeners=function(t){var e;return t?(e=n?n+t:t,this._events[e]&&a(this,e)):(this._events=new s,this._eventsCount=0),this},i.prototype.off=i.prototype.removeListener,i.prototype.addListener=i.prototype.on,i.prefixed=n,i.EventEmitter=i,t.exports=i},330:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.AcRequest=e.AcApi=void 0;const s=n(739);e.AcApi=class{constructor(t){this.params=t;const e="string"==typeof t.auth?new s.BasicAuthAgent({username:t.auth}):new s.OAuth2Agent({clientId:t.auth.clientId,clientSecret:t.auth.clientSecret,tokenUrl:t.apiTokenUrl});this.request=new r({baseUrl:t.apiUrl,auth:e,retryAttempts:t.requestRetryCount,retryDelay:t.requestRetryDelay})}async createJob(t){const{serviceId:e,category:n,input:s}=t;return await this.request.post("/jobs",{body:{serviceId:e,category:n,input:s}})}async getJob(t){return await this.request.get(`/jobs/${t}`)}async getJobAccessToken(t){return(await this.request.get(`/jobs/${t}/end-user`)).token}async getJobEvents(t,e){const{data:n}=await this.request.get(`/jobs/${t}/events`,{query:{offset:e}});return n}async getJobOutput(t,e){var n;try{return await this.request.get(`/jobs/${t}/outputs/${e}`)}catch(t){if(404===(null===(n=t.details)||void 0===n?void 0:n.status))return null;throw t}}async sendJobInput(t,e,n){return await this.request.post(`/jobs/${t}/inputs`,{body:{key:e,data:n}})}async cancelJob(t){await this.request.post(`/jobs/${t}/cancel`)}async queryPreviousOutputs(t,e,n=[]){const{data:s}=await this.request.post(`/services/${t}/previous-job-outputs`,{body:{inputs:n},query:{key:e}});return s}};class r extends s.Request{async createErrorFromResponse(t,e){var n;if(null===(n=e.headers.get("content-type"))||void 0===n?void 0:n.startsWith("application/json")){const t=await e.json();if(t.name&&t.message){const e=new Error(t.message);return e.name=t.name,e.code=t.code,e.details=t.details,e}}return super.createErrorFromResponse(t,e)}}e.AcRequest=r},967:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Client=void 0;const s=n(330),r=n(909),o=n(157),a=n(894);e.Client=class{constructor(t){this.logger=console,this.config=Object.assign({apiUrl:"https://api.automationcloud.net",apiTokenUrl:"https://auth.automationcloud.net/auth/realms/automationcloud/protocol/openid-connect/token",vaultUrl:"https://vault.automationcloud.net",pollInterval:1e3,requestRetryCount:4,requestRetryDelay:500,autoTrack:!0},t),this.api=new s.AcApi({logger:this.logger,apiTokenUrl:this.config.apiTokenUrl,apiUrl:this.config.apiUrl,auth:this.config.auth,requestRetryCount:this.config.requestRetryCount,requestRetryDelay:this.config.requestRetryDelay}),this.vault=new a.Vault(this)}async getJob(t){const e=new r.Job(this);return await e.trackExisting(t),e}async queryPreviousOutput(t,e=[]){const n=await this.api.queryPreviousOutputs(this.config.serviceId,t,e);return n.length?n[0]:null}async createJob(t={}){return await this._createJob(Object.assign({category:o.JobCategory.TEST,input:{}},t))}async _createJob(t){const e=new r.Job(this,t);return await e.start(),e}}},313:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.JobTrackError=e.JobFailedError=e.JobOutputWaitError=e.JobAlreadyStartedError=e.JobNotInitializedError=void 0;const s=n(222);class r extends s.Exception{constructor(){super("Invalid state: job not yet initialized")}}e.JobNotInitializedError=r;class o extends s.Exception{constructor(t={}){super("Job is already initialized"),this.details=t}}e.JobAlreadyStartedError=o;class a extends s.Exception{constructor(t,e={}){super(t),this.message=t,this.details=e}}e.JobOutputWaitError=a;class i extends s.Exception{constructor(t){var e,n,s;super(null!==(e=null==t?void 0:t.message)&&void 0!==e?e:"Unknown error"),this.name=null!==(n=null==t?void 0:t.code)&&void 0!==n?n:"UnknownError",this.details=Object.assign({category:null!==(s=null==t?void 0:t.category)&&void 0!==s?s:"server"},null==t?void 0:t.details)}}e.JobFailedError=i;class c extends s.Exception{constructor(t){super(`Job tracking failed: ${t.message}`),this.details={cause:t}}}e.JobTrackError=c},222:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Exception=void 0;class n extends Error{constructor(){super(...arguments),this.name=this.constructor.name,this.status=500,this.details={}}}e.Exception=n},863:function(t,e,n){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__exportStar||function(t,e){for(var n in t)"default"===n||Object.prototype.hasOwnProperty.call(e,n)||s(e,t,n)};Object.defineProperty(e,"__esModule",{value:!0}),r(n(330),e),r(n(967),e),r(n(222),e),r(n(313),e),r(n(909),e),r(n(273),e),r(n(157),e),r(n(894),e)},909:function(t,e,n){"use strict";var s=this&&this.__createBinding||(Object.create?function(t,e,n,s){void 0===s&&(s=n),Object.defineProperty(t,s,{enumerable:!0,get:function(){return e[n]}})}:function(t,e,n,s){void 0===s&&(s=n),t[s]=e[n]}),r=this&&this.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}:function(t,e){t.default=e}),o=this&&this.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)"default"!==n&&Object.prototype.hasOwnProperty.call(t,n)&&s(e,t,n);return r(e,t),e};Object.defineProperty(e,"__esModule",{value:!0}),e.Job=void 0;const a=n(729),i=o(n(313)),c=n(157);e.Job=class{constructor(t,e={}){this.client=t,this._events=new a.EventEmitter,this._inputsMap=new Map,this._outputsMap=new Map,this._state=c.JobState.CREATED,this._error=null,this._awaitingInputKey=null,this._trackPromise=null,this._jobId=null,this._jobEventOffset=0,this._isTracking=!1,this._initParams=Object.assign({category:c.JobCategory.TEST,input:{}},e)}get jobId(){if(!this._jobId)throw new i.JobNotInitializedError;return this._jobId}async start(){if(this._jobId)throw new i.JobAlreadyStartedError(this.jobId);const{category:t,input:e}=this._initParams,{serviceId:n}=this.client.config,{id:s,state:r}=await this.api.createJob({serviceId:n,category:t,input:e});this._jobId=s,this._setState(r);for(const[t,n]of Object.entries(e))this._inputsMap.set(t,{key:t,data:n});this.client.config.autoTrack&&this.startTracking()}async trackExisting(t){if(this._jobId)throw new i.JobAlreadyStartedError({jobId:this.jobId});const{state:e,category:n}=await this.api.getJob(t);this._jobId=t,this._initParams.category=n,this._setState(e),this.startTracking()}startTracking(){this._trackPromise||(this._isTracking=!0,this._trackPromise=this._track(),this._trackPromise.catch((t=>{})).then((()=>{this._isTracking=!1,this._trackPromise=null})))}stopTracking(){this._isTracking=!1}getState(){return this._state}_setState(t){const e=this._state;this._state=t,this._events.emit("stateChanged",t,e)}getErrorInfo(){return this._error}getAwaitingInputKey(){return this._awaitingInputKey}async getAccessToken(){return await this.api.getJobAccessToken(this.jobId)}async submitInput(t,e){await this.api.sendJobInput(this.jobId,t,e),this._inputsMap.set(t,{key:t,data:e})}async getOutput(t){var e;let n=null!==(e=this._outputsMap.get(t))&&void 0!==e?e:null;return n||(n=await this.api.getJobOutput(this.jobId,t),n&&this._outputsMap.set(t,n)),null==n?void 0:n.data}async waitForCompletion(){await this._trackPromise}async cancel(){await this.api.cancelJob(this.jobId)}async waitForOutputs(...t){return await this._waitFor((()=>{const e=this._checkOutputs(t);if(null!=e)return e;if(this.getState()===c.JobState.FAIL)throw new i.JobOutputWaitError("Job failed, and specified outputs were not emitted",{state:this.getState(),jobId:this.jobId});if(this.getState()===c.JobState.SUCCESS)throw new i.JobOutputWaitError("Job succeeded, but specified outputs were not emitted",{state:this.getState(),jobId:this.jobId})}))}async _waitFor(t){return new Promise(((e,n)=>{const s=()=>{try{const n=t();void 0!==n&&(o(),e(n))}catch(t){o(),n(t)}},r=t=>{o(),n(t)},o=()=>{this._events.off("trackTick",s),this._events.off("trackError",r)};this._events.on("trackTick",s),this._events.on("trackError",r),s()}))}onAwaitingInput(t,e){return this._createJobEventHandler("awaitingInput",(async n=>{if("*"===t||n===t){const s=await e(n);void 0!==s&&await this.submitInput(t,s)}}))}onOutput(t,e){return this._createJobEventHandler("output",(async n=>{this._matchKey(t,n.key)&&await e(n.data)}))}onDynamicOutput(t,e){return this._createJobEventHandler("output",(async n=>{(n.key.startsWith(t+":")||this._matchKey(t,n.key))&&await e(n.key,n.data)}))}onAnyOutput(t){return this._createJobEventHandler("output",(async e=>{await t(e.key,e.data)}))}onOutputEvent(t,e){return this.onDynamicOutput("events",(async(n,s)=>{s&&"object"==typeof s&&this._matchKey(t,s.type)&&await e(s)}))}onStateChanged(t){return this._createJobEventHandler("stateChanged",t)}onSuccess(t){return this._createJobEventHandler("success",t)}onFail(t){return this._createJobEventHandler("fail",t)}async _track(){for(;this._isTracking;){const{pollInterval:t}=this.client.config;try{const t=await this.api.getJobEvents(this.jobId,this._jobEventOffset);this._jobEventOffset+=t.length;for(const e of t)await this._processJobEvent(e);this._events.emit("trackTick")}catch(t){const e=new i.JobTrackError(t);throw this._events.emit("trackError",e),e}switch(this._state){case c.JobState.SUCCESS:return;case c.JobState.FAIL:throw new i.JobFailedError(this._error)}await new Promise((e=>setTimeout(e,t)))}}async _processJobEvent(t){const e=t.key;switch(t.name){case"awaitingInput":this._setState(c.JobState.AWAITING_INPUT),this._awaitingInputKey=e,this._events.emit("awaitingInput",e);break;case"createOutput":{const t=await this.api.getJobOutput(this.jobId,e);if(t){const n=t.data;this._outputsMap.set(e,{key:e,data:n}),this._events.emit("output",{key:e,data:n})}}break;case"processing":this._setState(c.JobState.PROCESSING);break;case"success":this._setState(c.JobState.SUCCESS),this._events.emit("success");break;case"fail":{const{error:t}=await this.api.getJob(this.jobId);this._setState(c.JobState.FAIL),this._error=Object.assign({category:"server",code:"UnknownError",message:"Unknown error"},t);const e=new i.JobFailedError(this._error);this._events.emit("fail",e)}}}_checkOutputs(t){const e=[];for(const n of t){const t=this._outputsMap.get(n);if(!t)break;e.push(t.data)}return e.length===t.length?e:null}get api(){return this.client.api}_createJobEventHandler(t,e){const n=async(...t)=>{await e(...t)};return this._events.on(t,n),()=>this._events.off(t,n)}_matchKey(t,e){if(t.endsWith(":*")){const n=t.split(":")[0];return e.startsWith(n+":")}return e===t}}},273:(t,e)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0})},157:(t,e)=>{"use strict";var n,s;Object.defineProperty(e,"__esModule",{value:!0}),e.JobCategory=e.JobState=void 0,(s=e.JobState||(e.JobState={})).CREATED="created",s.SCHEDULED="scheduled",s.PROCESSING="processing",s.AWAITING_INPUT="awaitingInput",s.AWAITING_TDS="awaitingTds",s.PENDING="pending",s.SUCCESS="success",s.FAIL="fail",(n=e.JobCategory||(e.JobCategory={})).LIVE="live",n.TEST="test"},894:(t,e,n)=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Vault=void 0;const s=n(739);function r(t){return"string"==typeof t?t:[t.name,t.label,t.placeholder].map((t=>t.replace(/_/g,""))).join("_")}e.Vault=class{constructor(t){this.client=t;const{config:e}=t,n="string"==typeof e.auth?new s.BasicAuthAgent({username:e.auth}):new s.OAuth2Agent({clientId:e.auth.clientId,clientSecret:e.auth.clientSecret,tokenUrl:e.apiTokenUrl});this.request=new s.Request({baseUrl:e.vaultUrl,auth:n})}get api(){return this.client.api}async createOtp(){const{id:t}=await this.request.post("/otp");return t}async createPanToken(t,e){const n=null!=e?e:await this.createOtp(),{panToken:s}=await this.request.post("/pan",{body:{otp:n,pan:t}});return s}getPaymentIframeUrl(t,e={}){var n,s,o;const a=[["otp",t],["css",e.cssUrl],["name",e.name],["fields",null===(n=e.fields)||void 0===n?void 0:n.map(r).join(",")],["brands",null===(s=e.brands)||void 0===s?void 0:s.join(",")],["validateOnInput",!0===e.validateOnInput?"on":void 0]].filter((t=>null!=t[1]));return(null!==(o=e.iframeUrl)&&void 0!==o?o:"https://vault.automationcloud.net/forms/index.html")+"?"+a.map((t=>{var e;return`${t[0]}=${encodeURIComponent(null!==(e=t[1])&&void 0!==e?e:"")}`})).join("&")}getSingleInputIframeUrl(t,e={}){var n;const s=[["otp",t],["css",e.cssUrl],["inputType",e.inputType],["pattern",e.pattern],["minlength",e.minlength],["maxlength",e.maxlength],["required",e.required],["validateOnInput",!0===e.validateOnInput?"on":void 0]].filter((t=>null!=t[1]));return(null!==(n=e.iframeUrl)&&void 0!==n?n:"https://vault.automationcloud.net/forms/single-input.html")+"?"+s.map((t=>{var e;return`${t[0]}=${encodeURIComponent(null!==(e=t[1])&&void 0!==e?e:"")}`})).join("&")}}}},e={},function n(s){if(e[s])return e[s].exports;var r=e[s]={exports:{}};return t[s].call(r.exports,r,r.exports,n),r.exports}(863);var t,e})); |
@@ -21,3 +21,3 @@ import { Request, RequestSpec } from '@automationcloud/request'; | ||
getJobEvents(jobId: string, offset: number): Promise<AcJobEvent[]>; | ||
getJobOutputData(jobId: string, key: string): Promise<AcJobOutput | null>; | ||
getJobOutput(jobId: string, key: string): Promise<AcJobOutput | null>; | ||
sendJobInput(jobId: string, key: string, data: any): Promise<AcJobInput>; | ||
@@ -24,0 +24,0 @@ cancelJob(jobId: string): Promise<void>; |
@@ -65,3 +65,3 @@ "use strict"; | ||
} | ||
async getJobOutputData(jobId, key) { | ||
async getJobOutput(jobId, key) { | ||
var _a; | ||
@@ -81,6 +81,3 @@ try { | ||
const body = await this.request.post(`/jobs/${jobId}/inputs`, { | ||
body: { | ||
key, | ||
data, | ||
}, | ||
body: { key, data }, | ||
}); | ||
@@ -87,0 +84,0 @@ return body; |
@@ -221,7 +221,10 @@ "use strict"; | ||
async getOutput(key) { | ||
const cached = this._outputsMap.get(key); | ||
if (cached) { | ||
return cached.data; | ||
var _a; | ||
let output = (_a = this._outputsMap.get(key)) !== null && _a !== void 0 ? _a : null; | ||
if (!output) { | ||
output = await this.api.getJobOutput(this.jobId, key); | ||
if (output) { | ||
this._outputsMap.set(key, output); | ||
} | ||
} | ||
const output = await this.api.getJobOutputData(this.jobId, key); | ||
return output === null || output === void 0 ? void 0 : output.data; | ||
@@ -467,3 +470,3 @@ } | ||
{ | ||
const jobOutput = await this.api.getJobOutputData(this.jobId, key); | ||
const jobOutput = await this.api.getJobOutput(this.jobId, key); | ||
if (jobOutput) { | ||
@@ -470,0 +473,0 @@ const data = jobOutput.data; |
{ | ||
"name": "@automationcloud/client", | ||
"version": "1.4.2", | ||
"version": "1.4.3", | ||
"description": "JavaScript/TypeScript Client Library for Automation Cloud API", | ||
@@ -43,3 +43,3 @@ "main": "out/main/index.js", | ||
"dependencies": { | ||
"@automationcloud/request": "^3.2.1", | ||
"@automationcloud/request": "^3.3.1", | ||
"eventemitter3": "^4.0.7" | ||
@@ -46,0 +46,0 @@ }, |
@@ -79,3 +79,3 @@ // Copyright 2020 UBIO Limited | ||
async getJobOutputData(jobId: string, key: string): Promise<AcJobOutput | null> { | ||
async getJobOutput(jobId: string, key: string): Promise<AcJobOutput | null> { | ||
try { | ||
@@ -94,6 +94,3 @@ const body = await this.request.get(`/jobs/${jobId}/outputs/${key}`); | ||
const body = await this.request.post(`/jobs/${jobId}/inputs`, { | ||
body: { | ||
key, | ||
data, | ||
}, | ||
body: { key, data }, | ||
}); | ||
@@ -100,0 +97,0 @@ return body; |
@@ -223,7 +223,9 @@ // Copyright 2020 UBIO Limited | ||
async getOutput(key: string): Promise<any> { | ||
const cached = this._outputsMap.get(key); | ||
if (cached) { | ||
return cached.data; | ||
let output = this._outputsMap.get(key) ?? null; | ||
if (!output) { | ||
output = await this.api.getJobOutput(this.jobId, key); | ||
if (output) { | ||
this._outputsMap.set(key, output); | ||
} | ||
} | ||
const output = await this.api.getJobOutputData(this.jobId, key); | ||
return output?.data; | ||
@@ -478,3 +480,3 @@ } | ||
case 'createOutput': { | ||
const jobOutput = await this.api.getJobOutputData(this.jobId, key); | ||
const jobOutput = await this.api.getJobOutput(this.jobId, key); | ||
if (jobOutput) { | ||
@@ -481,0 +483,0 @@ const data = jobOutput.data; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
189989
3101