@testim/testim-cli 4.111.0 → 4.112.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli.js CHANGED
@@ -405,7 +405,7 @@ Please make sure the CLI has stable access to the internet. ${Ec()?"(Internal: n
405
405
  `;return this.driver.executeJS(n,t.locatedElement)}async safariPreUploadActions(t){let r={width:"150px",height:"150px",left:"10px",top:"10px"};try{return await this.forceInputToBeVisible(t,r)}catch(n){throw ma.error("failed to set input file in Safari recovery",{err:n}),n}}async uploadFilesAndForceVisibility(t,r){try{this.driver.isSafari()&&await this.safariPreUploadActions(r),await this.uploadFiles(t,r)}catch(n){let o="The element is not editable",i="The element is not focusable",a="An element command could not be completed because the element is not visible on the page.",l="element not interactable",c="element is not pointer- or keyboard interactable",d="invalid element state: Element is not currently interactable and may not be manipulated",m="Element must not be hidden, disabled or read-only",u="is not reachable by keyboard",g=n?n.message:"";if(g===d||g.startsWith(m)||g.startsWith(o)||g.startsWith(i)||g.startsWith(a)||g.includes(u)||g.includes(l)||g.includes(c)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw ma.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(De(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=L.flags.overrideAzureStorageUrl.isEnabled(),n=L.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:o,context:i,step:a,stepActionUtils:l,driver:c}=this,d=await o.utils.addTokenToFileUrls(i.project.id,a.fileUrls,l.testimServicesApi,r,ma);if(d.length===0)throw new Error("No files urls to upload");if(n&&(d=await Promise.all(d.map(async({name:u,url:g})=>{let h=await Nt(g);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),c.isSafari()||c.isFirefox()||c.isEdgeChromium()){await this.driver.executeJS(`
406
406
  const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
407
407
  const downloadAndUploadFile = ${iI()};
408
- return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Zy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ga,ha,rb=w(()=>{"use strict";ga=require("url");ue();ha=class extends V{async updateBaseUrl(e){let t=new ga.URL(e),r=new ga.URL(this.context.recordedBaseUrl),n=new ga.URL(this.context.baseUrl);return t.host===r.host&&r.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var ya,sb=w(()=>{"use strict";ue();B();ya=class extends V{async performAction(){await ae(this.step.durationMS||0)}}});var ba,nb=w(()=>{"use strict";ue();ba=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var qn,ob=w(()=>{"use strict";ue();qn=class extends V{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(r,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t,apiCallAsync:r}=this.sessionPlayerInit;return typeof r=="function"&&r.length===2?r(t,e):new Promise(n=>{t(e,n)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Ta,ib=w(()=>{"use strict";ue();Ta=class extends V{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var ab,vp,Sp,cb=w(()=>{"use strict";ab=S(require("@applitools/spec-driver-webdriverio"));io();Te();vp=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=nd["@applitools/eyes-sdk-core"]||"N/A",{makeSDK:r}=require("@applitools/eyes-sdk-core");this.sdk=r({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:ab.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=Z(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},Sp=new vp});var ub,lb,zn,pb=w(()=>{"use strict";ub=S(require("lodash"));ue();$();cb();lb=C("pixel-validation-step-action"),zn=class extends V{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||o,l=await Sp.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let g=await l.openEyes({driver:this.driver.client,config:r,logger:n}),f={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};ub.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(f,i.applitoolsStepSettings),lb.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await g.check({settings:f}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await g.close()}}catch(g){lb.error("Applitools SDK step failed",{err:g,info:g.info}),d={isApplitoolsSdkResult:!0,success:!1,err:g}}return await Sp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var vs,Ep=w(()=>{"use strict";fs();K();oa();vs=class extends ar{async executeCliCode(){var h,f,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(f=(h=t.company)==null?void 0:h.activePlan)==null?void 0:f.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o="",id:i=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,g=await ms(o,i,a,m,l,c,d,u);return this.checkCodeResponse(g)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof oe?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var cr,db=w(()=>{"use strict";Ep();cr=class extends vs{isFailedResult(e){return e===!1}}});var wa,mb=w(()=>{"use strict";Ep();wa=class extends vs{isFailedResult(e){return!e}}});var va,fb=w(()=>{"use strict";fs();ue();K();va=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await ds(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof Rt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof oe?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var kr,gb=w(()=>{"use strict";ue();kr=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ye,hb=w(()=>{"use strict";ue();ye=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Sa,yb=w(()=>{"use strict";ue();Sa=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ea,bb=w(()=>{"use strict";ue();Ea=class extends V{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function aI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Ia(s,e){aI(cI,e),e.registerLocateStepActionUtils(Wn.getUtils(s))}var cI,Ip=w(()=>{"use strict";fy();yy();Ay();xy();Py();Oy();My();Ny();Uy();Fy();$y();Wy();Vy();qy();Jy();tb();rb();sb();nb();ob();ib();pb();db();mb();fb();gb();hb();yb();bb();cI={locate:Wn,scroll:ea,mouse:ta,submit:la,text:sa,"special-key":ia,"user-code":Gt,"validation-code-step":Gt,"wait-for-code-step":Gt,"action-code-step":Gt,"condition-step":ws,"skip-code-step":ws,"element-code-step":ws,"evaluate-expression":ra,"text-validation":Gn,"wait-for-text-validation":Gn,"select-option":ca,"drop-file":da,"input-file":fa,hover:ua,navigation:ha,wheel:pa,sleep:ya,refresh:ba,"keyboard-shortcut-step":aa,"api-validation":qn,"api-action":qn,"api-code-step":Gt,"extract-text":Ta,"simple-ui-verification":zn,"wait-for-simple-ui-verification":zn,"cli-validation-download-file":kr,"cli-wait-for-download-file":kr,"network-validation-step":kr,"cli-validation-code-step":cr,"cli-wait-for-code-step":cr,"cli-action-code-step":cr,"cli-api-code-step":cr,"cli-condition-step":wa,"node-package":va,"email-code-step":Gt,"cli-email-code-step":cr,"sfdc-internal-test-step":Ea,"sfdc-recorded-step":Sa,"sfdc-step-login":ye,"sfdc-step-loginas":ye,"sfdc-step-logout":ye,"sfdc-step-sobjectcreate":ye,"sfdc-step-sobjectdelete":ye,"sfdc-step-findrecord":ye,"sfdc-step-quickaction":ye,"sfdc-step-sobjectedit":ye,"sfdc-step-sobjectvalidate":ye,"sfdc-step-launchapp":ye,"sfdc-step-wait-for-page-load":ye,"sfdc-step-closeconsoletabs":ye,"sfdc-step-relatedlistaction":ye,"sfdc-step-permission-validation":ye,"sfdc-step-convert-lead-to-opportunity":ye,"sfdc-step-quotelineeditor":ye,"sfdc-document-validation":kr,"sfdc-step-flow-screen-completion":ye,"sfdc-step-sobjectverifyoptions":ye}});var Tb,lI,Ss,Rp=w(()=>{"use strict";Tb=["simple-ui-verification","wait-for-simple-ui-verification"],lI=[...Tb,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor","sfdc-document-validation","sfdc-step-flow-screen-completion","sfdc-step-sobjectverifyoptions"],Ss=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=lI.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,n),e.context.data.maxTotalStepTime=r}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return Tb.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var vb={};H(vb,{SeleniumTestPlayer:()=>Kn});var wb,uI,Kn,Ap=w(()=>{"use strict";B();wb=require("@applitools/eyes-sdk-core");Dn();K();$();gp();ly();Tp();Qi();dy();wp();Te();Ip();Rp();uI=C("SeleniumTestPlayer"),Kn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new Ss(Zi());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Z();this.driver=n??new Ar;let d=new Xi(this.driver);this.stepActionFactory=new c(d),Ia(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ji(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=py(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new bs(this.driver),FrameLocator:m,portSelector:Yi,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:wb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof oe&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){uI.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(r);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Cp={};H(Cp,{WorkerSelenium:()=>xp});function dI(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>N(`Got event ${t}`))}var Ra,pI,xp,Pp=w(()=>{"use strict";B();We();jn();$();_t();ii();ne();mp();K();Ap();Te();it();Ra=C("worker-selenium"),pI=1e9,xp=class extends Lt{initPlayer(t){return new Kn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){N("in WorkerSelenium getBrowserOnce"),ee.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ys(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await i.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:o,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),N("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),N("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,pI),await this.windowUtils.validatePageIsAvailable(),N("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof It||d||m?new It(`Page '${l}' is not available`):(Ra.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Wo(),initializedFromCache:Vo()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=Z(),{driver:i,sessionPlayer:a}=r,l=n||"runner";ee.onWaitToTestComplete(this.id),dI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===q.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await bn(this.options))[this.testId]);let d=async()=>ce(new Promise((u,g)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(g)}),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var g;throw u instanceof oe&&((g=a.stopPlayingOnTestTimeout)==null||g.call(a)),u}).then(async u=>{await o.drain(),u.stepsResults=null,u.resultId=this.testResultId,i.isAlive()||(Ra.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let g=i.maxKeepAliveGap();g>=3e4&&(Ra.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=g);let f={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${f.success?"passed":"failed"}`).catch(()=>{}),f});i.start(),N("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),N("right after super.runTestOnce in workerSelenium");let u=await d();return N("right after runSeleniumTest"),u}catch(u){throw Ra.error("failed to run test once",{err:u}),u}}}});var Sb,Eb,qe,mI,fI,kp,vt,Aa=w(()=>{"use strict";Sb=S(require("ora")),Eb=S(require("jimp"));pe();He();he();$();ne();Te();le();qe=C("mobile-grid-service"),mI="https://tdc.tricentis-cloud.com",fI="https://ui.headspin.io",kp=class{constructor(){this.gridsAppIdGetter={[O.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[O.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[O.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[O.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[O.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[O.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===O.TESTIM_TDC||e===O.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===O.TESTIM_HEADSPIN?`${r||Za}/${tc}/devices`:t===O.TESTIM_TDC?`${r||ec}/${tc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await Ge({url:r,headers:n,body:o})}catch(i){throw qe.debug(`error while locking device ${t}`,{error:i}),i.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):i}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let o=await be(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw qe.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t,r){let n=await js(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===O.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===O.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([O.BROWSERSTACK,O.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:o,gridId:i}){var a,l,c;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let d=await Ll({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n){let{executionId:o,testId:i,testResultId:a}=e,{project:l,projectData:{type:c}={},company:{companyId:d=""}={},gridData:{gridId:m="",type:u=""}={}}=n,g=t.capabilities,h=g.platformName,f;if(u===O.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:T}=Z();f=T(t.capabilities)}else f=await this.getDeviceFromAppiumCapabilities(g,t,r,h,u,l,c,d,m);let y=await this.buildRemoteResultLink(n.gridData,t.sessionId,g);return await Tr(l,o,i,a,"RUNNING",{device:f,...y&&{remoteResultLink:y}}),qe.info("device details updated on testResult",{testResultId:a,executionId:o,testId:i,device:f,remoteResultLink:y,gridType:u}),f}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===O.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),i=Number(o[0]),a=Number(o[1]);return{scaleFactor:e.pixelRatio,width:i,height:a}}try{let{AppiumApi:o}=Z(),i=new o(t,r.sessionId,null),[a,l]=await Promise.all([i.getScreenshot(),i.getDeviceSize()]),c=Buffer.from(a,"base64"),d=await Eb.default.read(c),m=d.getWidth(),u=d.getHeight();return{scaleFactor:m/l.width,width:m,height:u}}catch(o){return qe.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,o,i,a,l,c){let[d,m]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:o,projectId:i,projectType:a,companyId:l,gridId:c})]),u=this.getOsVersion(e,o);return{name:m??"",model:e.deviceModel,udid:e.udid,osVersion:u,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===O.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ls}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===O.SAUCELABS?r.testobject_test_report_url:e.type===O.TESTIM_TVC?r.replayUrl:e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC?`${e.type===O.TESTIM_HEADSPIN?fI:mI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let r=(await be(`${wd}/devices`)).find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,geo:"local",osVersion:r.osVersion,osType:r.deviceType.toLowerCase(),scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:o,testResultId:i}=r,a=await this.getTmaDeviceDetails(e),{project:l}=t;return await Tr(l,n,o,i,"RUNNING",{device:a}),qe.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,o=t.mobileApp,i=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:o,gridHost:e.host});return i?(L.flags.allowFixingAppIdStructure.isEnabled()&&(qe.info("fixing gridAppId structure",{gridAppId:i,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Ml({gridAppId:i,gridId:e.gridId,projectId:r,gridType:n,appId:o.appId,gridHost:e.host})),i):t.getAppPathByGridType(n,e.gridId,o)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await un({appId:e,projectId:t});return{appUrl:`${fe}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(Td*60))+1)*60*1e3,Math.max(bd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let a={[O.BROWSERSTACK]:{name:"Browserstack"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[O.P_CLOUDY]:{name:"pCloudy"}}[o].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,Sb.default)(`uploading app to ${a} please wait..`).start();try{qe.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Dl({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),qe.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:o,mobileAppId:i}){let a=t.get(i);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:o});return t.set(i,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",o,{executionId:i,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:g=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){qe.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:i});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,o=T.mobileApp,e.nativeApp=o}else qe.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:i}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,f=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=g===O.BROWSERSTACK||g===O.TESTIM_TVC||g===O.P_CLOUDY;if(f){let T=t.projectData.type,I=await this.verifyAppStillExistsOnGrid({gridAppId:f,gridData:m,projectType:T});I&&(qe.info("app exists on grid, using gridAppId",{gridAppId:f,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=f),!I&&y&&(qe.info("app not exists on grid, uploading it",{gridAppId:f,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:g,mobileAppId:h})),!I&&!y&&qe.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:i})}return!f&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:g,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:o,host:i,key:a,type:l,apiUrl:c}=t;if(l===O.BROWSERSTACK){let u=`${Ls}/recent_apps`,g=await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a});return Array.isArray(g)?g.some(h=>h.app_url===e):!1}if(l===O.SAUCELABS){let g=`${i.includes("eu-central-1")?Ed:Sd}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:g,user:o,key:a})).items.some(f=>f.id===e)}if(l===O.TESTIM_HEADSPIN||l===O.TESTIM_TDC){let u=`${c}/${rc}/apps`;return c||(u=`${l===O.TESTIM_HEADSPIN?Za:ec}/${rc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===O.TESTIM_TVC){let u=`${vd}/versions/${e}/info`,g=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:g,authType:"Upload-Token"}),!0}catch(h){return h.status!==404&&qe.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===O.P_CLOUDY){let u=await this.getPCloudyAuthToken(i,o,a),g=`https://${i}/api/drive`,h=await Tc({url:g,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await be(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await be(e,void 0,n)}},vt=new kp});function Ib({nativeAppMetadata:s,appPath:e,gridInfo:t}){if(!s&&!e||!s)throw Error("Application not specified. Please provide the required application for execution and try again.");if(!s.id&&!s.activity&&!s.packageName)throw Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");if(t.mode!=="local"&&!gI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function hI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==O.TESTIM_TDC&&e.type!==O.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function yI(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,o=[{executionId:t},{testResultId:r}];return e&&o.push({testName:e}),n&&o.push({customTag:n}),o}function bI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===O.TESTIM_TDC,a=s===O.TESTIM_HEADSPIN,l=i?"tdc":"headspin",c=a&&L.flags.enableBatchHeadSpin.isEnabled(),d=i&&(L.flags.enableBatchTDC.isEnabled()||L.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=L.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture`]:!0,...L.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...o&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:yI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:300}}}function xa(s){return"id"in s?s.id:s.packageName}function TI(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function wI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:o}){let{fullReset:i,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=TI(n,t.gridData.type));let m=()=>i===void 0&&n?!0:typeof i=="string"?i!=="false":i;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":xa(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!i,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...o&&{"appium:appWaitActivity":`${o}, *`},...r&&{"appium:appPackage":xa(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Or({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:o=""}){switch(s){case"ios":return{platformName:"iOS",[`${o}autoAcceptAlerts`]:!0,[`${o}automationName`]:"XCUITest",[`${o}fullReset`]:!0,...t&&{[`${o}bundleId`]:xa(t)},...r&&{[`${o}app`]:r},...e};case"android":return{platformName:"Android",[`${o}autoGrantPermissions`]:!0,[`${o}automationName`]:"UiAutomator2",...n&&{[`${o}appWaitActivity`]:`${n}, *`},...t&&{[`${o}appPackage`]:xa(t),[`${o}appActivity`]:t.activity??".*"},...r&&{[`${o}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Rb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=bI(i.type,o,n);return wI({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Pa({osVersion:s,mobileConfig:e}){let{staticAllocation:t,dynamicAllocation:r}=e;return s||(t!=null&&t.osVersion?t==null?void 0:t.osVersion:r!=null&&r.osVersionRegex?r==null?void 0:r.osVersionRegex:".*")}function ka({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e,i=r===O.P_CLOUDY;return s||(n!=null&&n.deviceName?i?n.deviceUdid:n.deviceName:o!=null&&o.deviceNameRegex?t==="android"&&o.deviceNameRegex===".*"&&i?sc:o.deviceNameRegex:t==="ios"&&r===O.BROWSERSTACK?"iPhone.*":i?t==="ios"?"apple":sc:".*")}function vI(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function SI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Ca(s,Es)}}function Ab(s,e,t){return s?Object.entries(s).reduce((r,[n,o])=>{if(e(n)){if(!t)return r[n]=o,r;let i=n.replace(t,"");r[i]=o}return r},{}):{}}function EI(s){return Ab(s,e=>e.startsWith("browserstack."),"browserstack.")}function II(s){return Ab(s,e=>!e.startsWith("browserstack."))}function xb(s){return!s||!Cb(s)?"2.0.0":s}function Cb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Pb({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,o=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,i=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&o.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&i.test(s),d=l||c;if(t){let m=Cb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Ca(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let o=`${e}${r}`;t[o]=n}),t}function RI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=vI(o,s),g=Pa({osVersion:l,mobileConfig:d}),h=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),f=ze(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y=L.flags.enableWaldoRunner.isEnabled(),T={device:h,os_version:g,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":f,...y&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:u}};return Or({projectType:s,sessionCaps:T,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function AI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:g}=o,h=L.flags.enableAppium2pCloudy.isEnabled(),f=Pa({osVersion:l,mobileConfig:d}),y=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:g}),T=/^[a-zA-Z]+$/.test(y),I={...f!==".*"&&{pCloudy_DeviceVersion:f},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:i.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...I,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Id),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=SI(b)),t="",Or({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Es}})}function xI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Pa({osVersion:l,mobileConfig:d}),g=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,_r.omit)({...n.saucelabs},["automationName","platformName"]),f={...h["sauce:options"]};if(delete h["sauce:options"],Pb({osVersion:h.platformVersion||u,projectType:s,appiumVersion:f.appiumVersion})){let T={debug:!0,networkLogs:!0},I={user:o.user,key:o.key,name:i.testResultId,build:i.executionId,appiumVersion:xb(f.appiumVersion),deviceName:g,tags:Object.values(i)},b={"appium:platformVersion":u,"appium:deviceName":g,...Ca(h,Es),"sauce:options":{...T,...I,...(0,_r.omit)(f,"appiumVersion")}};return Or({projectType:s,sessionCaps:b,appiumPrefix:Es,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":o.user,"saucelabs.key":o.key,platformVersion:u,deviceName:g,tags:Object.values(i),name:i.testResultId,build:i.executionId,...h,...f};return Or({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function CI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Pa({osVersion:l,mobileConfig:d}),g=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=EI(n.browserstack),f=(0,_r.omit)(II(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:I}=n.browserstack||{},b=L.flags.enableAppium2BrowserStack.isEnabled();if(b||Pb({osVersion:f.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let E={userName:o.user,accessKey:o.key,appiumVersion:b?"2.0.1":xb(h.appiumVersion),projectName:y||i.project,buildName:T||i.executionId,debug:!0,networkLogs:!0},x={"appium:platformVersion":u,"appium:deviceName":g,...Ca(f,Es),"bstack:options":{...E,...(0,_r.omit)(h,"appiumVersion")}};return Or({projectType:s,sessionCaps:x,appiumPrefix:Es,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let v={os_version:f.platformVersion||u,device:f.deviceName||g,realDevice:!0,name:I||i.testResultId,project:y||i.project,build:T||i.executionId,buildTags:Object.values(i).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...f,...Ca(h,"browserstack.")};return Or({projectType:s,sessionCaps:v,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function PI(s){if(O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type)return Rb(s);if(O.TESTIM_TVC===s.gridInfo.type)return RI(s);if(O.P_CLOUDY===s.gridInfo.type)return AI(s);if(O.SAUCELABS===s.gridInfo.type)return xI(s);if(O.BROWSERSTACK===s.gridInfo.type)return CI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function kI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:o,osVersion:i,deviceUdid:a}=s,l={};return n==="dynamic"&&(!o&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!i&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),o&&(l.manufacturer=o),i&&(l.os_version=i),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function kb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:o}=s,{selectedGrid:i}=(o==null?void 0:o.mobile)||{};if(o!=null&&o.mobile&&(i==null?void 0:i.type)!==e.type)throw Error(`selected grid type ${i.type} is not equal to grid type ${e.type}`);Ib({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=PI(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let m=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",u=kI(r,o==null?void 0:o.mobile);if(!(0,_r.isEmpty)(u)){let g=Object.entries(u).map(([h,f])=>f.split(",").map(y=>y===".*"||y==="="?"":`${h}:${y}`).join(",")).join(" ").trim();l[`${m}:selector`]=g}}let c=e.type===O.TESTIM_TVC?{alwaysMatch:l}:l,d=L.flags.increaseTDCRequestTimeout.isEnabled();return{...a,desiredCapabilities:l,...d&&{connectionRetryTimeout:48e4},capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function _b(s){var h,f;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;Ib({nativeAppMetadata:r,appPath:o,gridInfo:t}),hI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((f=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:f.deviceUdid),m=await vt.getGridDirectConnection(t,d),g=Rb({projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(g["appium:udid"]=d),{...m,desiredCapabilities:g,capabilities:g,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Ob(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,i=Or({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete i.app,i}function Lb(s){var t,r;let e={...s};return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],(t=e.capabilities["sauce:options"])==null||delete t.user,(r=e.capabilities["sauce:options"])==null||delete r.key,delete e.capabilities.key,delete e.capabilities.user,e}var _r,Es,gI,_p=w(()=>{"use strict";le();ne();Aa();_r=require("lodash");B();pe();Es="appium:",gI=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var _a,Mb=w(()=>{"use strict";_a=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var Oa,Nb=w(()=>{"use strict";B();Oa=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Ks;this.getLinksFromUnescapeHTML=Js}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}}});var Op,La,Ub=w(()=>{"use strict";$();Op=C("mobile-frame-locator-mock"),La=class{foundFrameCallback(){return Op.info("foundFrameCallback-mock invoked"),{}}locate(){return Op.info("locate-mock invoked"),{}}async findFrame(){return Op.info("findFrame-mock invoked"),{}}}});var _I,Bb,Fb,Is,Lp=w(()=>{"use strict";_I=S(require("webdriverio")),Bb=require("@applitools/eyes-sdk-core");Mb();Tp();$();Nb();wp();Te();Ip();Ub();Rp();Fb=C("appium-test-player"),Is=class{constructor(e,t,r,n=_I,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Z(),m=new Oa(this.driver);this.stepActionFactory=new c(m),Ia(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Ss(Zi()),this.sessionPlayer=new a(e,{tabService:new _a,cookieUtils:void 0,FrameLocator:La,portSelector:Yi,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Bb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,o={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Fb.info("appium session deleted",{...o}))}catch(i){Fb.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=Z();e.off(i.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function OI(s){return await be(`${s}/api/status`)}async function jb(s,e){return await be(`${s}/api/devices/${e}/status`)}async function $b(s){if((await OI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Wb=w(()=>{"use strict";He()});var Vb={};H(Vb,{WorkerLocalTma:()=>Up});var Lr,Dp,Mp,Np,Up,Gb=w(()=>{"use strict";He();_p();jn();B();$();_t();Lp();Te();Wb();Aa();Lr=C("worker-appium"),Dp=class extends Error{},Mp=class extends Error{},Np=class extends Error{},Up=class extends Lt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=Z(),{DOMParser:n}=await import("linkedom"),o=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}async getBrowserOnce(t,r,n,o){var E;if(ee.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:i,deviceUdid:a,projectData:l}=this.options;await $b(i);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,g=this.options.appId;if(g){let{mobileApp:x}=await vt.getMobileAppDataByAppId({appId:g,projectId:c,token:d});t.nativeApp=x}let h=u==="android"?t.androidActivityWait:null,f=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!f)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:I,version:b},v]=await Promise.all([this.getAppStateFromDevice(i,a,T),jb(i,a)]).catch(x=>{throw this.handleDeviceNotFoundError(x),x});if(Lr.info("device status and app state",{deviceStatus:v,appInstalled:I,version:b,executionId:this.executionId,testResultId:this.testResultId}),!I&&t.isAppFromDevice&&!g)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!I&&y&&(await this.installApp(i,a,y),Lr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let x={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},D=Ob({projectType:u,nativeAppMetadata:f,appPath:y,androidActivityWait:h,sessionTags:x,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),F={capabilities:{udid:a,...D}};Lr.info("requesting new appium session from TMA",{tmaSessionSettings:F,executionId:this.executionId,testResultId:this.testResultId});let R=await this.requestNewAppiumSessionFromTma(i,F,f);this.sessionData=R;let A=await m.attach({sessionId:R.sessionId,capabilities:D});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),Lr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:A.sessionId,testResultId:this.testResultId,nativeAppMetadata:f,sessionCaps:A.capabilities})}catch(x){throw Lr.error("failed to start application",{err:x}),x}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await Ge({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new Np(l):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,l=(await be(i)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var o,i;try{let a=await Nt(n);await Bs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Mp(c,{cause:a})}}handleDeviceNotFoundError(t){var n,o;let r=(o=(n=t.response)==null?void 0:n.body)==null?void 0:o.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Dp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=Z(),{sessionPlayer:i}=r,a=n||"runner";ee.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{i.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await o.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Lr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Lr.error("failed to run test once",{err:c}),c}}}});var qb={};H(qb,{WorkerAppium:()=>Fp});var Hb,Dr,Fp,zb=w(()=>{"use strict";_p();Hb=require("linkedom");jn();$();_t();Lp();Te();Aa();ne();is();Dr=C("worker-appium"),Fp=class extends Lt{initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){ee.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,l=await vt.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),c=a==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},u={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:m,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig},g;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await vt.lockDevice(o,this.options.deviceUdid),g=await _b(u)):g=kb(u),Dr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:Lb(g)});let h=this.getServerAddressFromGrid();this.activeSession=await i.remote(g),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,h,this.options);let f=`${h}/session/${this.activeSession.sessionId}`;this.updateSlotData(f),Dr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Dr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}async startKeepAlive(t){let{errors:r}=Z(),n=async()=>{try{await(t==null?void 0:t.getOrientation())}catch(o){Dr.error("failed to keep appium session alive",{err:o}),r!=null&&r.AppiumSessionTerminatedError&&o instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&yg(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Dr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===O.TESTIM_HEADSPIN||o===O.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:o===O.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:o,directConnectPath:i}=t;if(r&&n&&o&&i)return`${r}://${n}:${o}${i}`}async runTestOnce(t,r){var u,g;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=Z(),{sessionPlayer:a}=r,l=n||"runner";ee.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let c;if(this.options.skipLoadBalancer){let h=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:f,hostname:y,port:T,path:I}=await vt.getHeadSpinDeviceConnection(this.options.gridData,h);c=`${f}://${y}:${T}${I}`}else c=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let d=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:d,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(g=this.options.company)==null?void 0:g.companyId,device:this.device},a.playbackManager.appiumApi=new o(c,this.activeSession.sessionId,Hb.DOMParser),this.startKeepAlive(a.playbackManager.appiumApi),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let h=await new Promise((y,T)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:y,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(T)});return this.stopKeepAlive(),await i.drain(),h.stepsResults=null,h.resultId=this.testResultId,{...h,...t.seleniumPerfStats.getStats()}}catch(h){throw Dr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:h}),this.stopKeepAlive(),h}};try{return await super.runTestOnce(t,r),await m()}catch(h){throw Dr.error("failed to run test once",{err:h}),h}}}});var Da,Kb=w(()=>{"use strict";B();Dn();K();Da=class{constructor(e){this.id=e;this.driver=new Ar}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof oe&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Jb,Ma,Yb=w(()=>{"use strict";Jb=S(require("ws"));B();Ma=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new Jb.default(this._cdpUrl,{timeout:e}),r=Kt(o=>{t.once("open",o)}),n=Kt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let o=this._lastWsId++,i=new Promise((l,c)=>{this._cdpCallbacks.set(o,{resolve:l,reject:c})}),a={method:e,params:t,id:o};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),i}}});var Ua,Bp,Na,Xb=w(()=>{"use strict";B();Ua=S(require("chrome-launcher"));Hu();Yb();mn();Bp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ma}async init(e){var h,f,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=Mi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(f=m.capabilities)==null?void 0:f.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...Ua.Launcher.defaultFlags().filter(I=>I!=="--disable-extensions")];this.chrome=await Ua.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let g=await fr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(g),es(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},Na=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new Bp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var jp={};H(jp,{WorkerExtension:()=>Jn});function LI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Qb(s){return LI(s)?s:new Error(s)}var pt,Jn,Fa=w(()=>{"use strict";We();K();jn();B();$();_t();ne();Kb();Xb();it();pt=C("worker-ext"),Jn=class extends Lt{initPlayer(){return this.options.useChromeLauncher?new Na(this.id):new Da(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(i=this.options.lightweightMode)==null?void 0:i.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw pt.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Wo(),initializedFromCache:Vo(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return ee.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:o}=this;N("WorkerExtension runTestOnce");let i=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ce(e.runTestUsingCDP(d.cdpTestRunner),m,Fe.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof oe))throw u;return pt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let g=await d.url(m);return u.driverUrlFinished=!0,g}catch(g){throw pt.error("error from driver.url",{err:g,testResultId:r,executionId:n,testId:o,url:m,urlLength:m.length}),g}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var g;if(N("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){ee.onWaitToTestStart(this.id),ee.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw pt.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();ee.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Fe.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof oe))throw T;pt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}ee.onWaitToTestComplete(this.id);let f=new AbortController,y=T=>{e.onCompletedCleanup(),pt.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),T.type=Ws.BROWSER_CLOSED,f.abort(T)};m.registerToClosedBrowser(y);try{let T=ce(e.onCompleted(),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG),I=await fc(T,f.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(I.success),I.reason)}catch(E){pt.error("Could not update the grid about the test status",{err:E})}m.isAlive()||(pt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(pt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.keepAliveIssue=b),{...I,...e.seleniumPerfStats.getStats()}}catch(T){throw pt.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:o}),Qb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw pt.warn("failed to start url",{err:h}),Qb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),N("WorkerExtension super.runTestOnce"),await c()}catch(d){throw pt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Wp={};H(Wp,{WorkerExtensionSingleBrowser:()=>$p});var DI,MI,$p,Vp=w(()=>{"use strict";We();B();$();ap();_t();Fa();DI=C("base-worker"),MI=500,$p=class extends Jn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Fn(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return ee.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,o)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(DI.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let o=this.handleQuarantine(t);if(o)return o;N("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ae(MI)}}});var Gp,Ba,Zb=w(()=>{"use strict";Dn();pe();We();Nu();it();Yu();K();$();ne();Jh();ei();Gp=C("worker-manager"),Ba=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],o=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,o),o.id=t,o.uniqueId=n,o.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(Pp(),Cp))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(Gb(),Vb))).WorkerLocalTma:(await Promise.resolve().then(()=>(zb(),qb))).WorkerAppium;default:return Mn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(Vp(),Wp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Fa(),jp))).WorkerExtension}else switch(r){case(vr.find(n=>n===r)&&Mn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(Vp(),Wp))).WorkerExtensionSingleBrowser;case vr.find(n=>n===r):return(await Promise.resolve().then(()=>(Fa(),jp))).WorkerExtension;case hn.find(n=>n===r):return(await Promise.resolve().then(()=>(Pp(),Cp))).WorkerSelenium;default:throw new P(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return N("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{N("after new Worker",r.mode)}}async runTests(e,t,r,n,o,i,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,g)=>new Promise(h=>{var me,tt,St,Mr,k,M,j,z;let f=o.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Vi(r,n,e,o,i,t),this.combinedTestResults={};let T=((me=o.company)==null?void 0:me.ucid)||"",I=(tt=o.company)==null?void 0:tt.companyId,b=(St=o.company)==null?void 0:St.name,v=o.source||"cli",E=o.user,x=(Mr=o.company)==null?void 0:Mr.planType,D=(k=o.company)==null?void 0:k.isStartUp,F=(M=o.projectData)==null?void 0:M.name,R=(j=o.projectData)==null?void 0:j.type,A=o.lightweightMode,_=(z=o.gridData)==null?void 0:z.type,U=(Pe,Et,we,Ha,Xn,qa)=>(d++,_g({executionId:r,projectId:f,testId:Et,resultId:we,ucid:T,companyId:I,companyName:b,projectName:F,companyPlan:x,source:v,user:E,lightweightMode:A,isStartUp:D,projectType:R,appSource:qa,gridType:_}),t.testStartAndReport(Pe,r,we,Ha,Xn)),G=async(Pe,Et,we,Ha,Xn,qa)=>{var Qp,Zp,ed;d--;let rt={...(A==null?void 0:A.onlyTestIdsNoSuite)&&{show:!0},...we.seleniumStats&&{seleniumStats:we.seleniumStats},...we.gridIssues&&{gridIssues:we.gridIssues},...we.keepAliveIssue&&{keepAliveIssue:we.keepAliveIssue},...o.host&&{gridHost:o.host}};if(we.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(we.seleniumPerfMarks),delete we.seleniumPerfMarks),o.grid||o.gridId?(rt.gridName=o.grid||((Qp=o.gridData)==null?void 0:Qp.name),rt.gridType=(Zp=o.gridData)==null?void 0:Zp.type,rt.gridProvider=(ed=o.gridData)==null?void 0:ed.provider):o.localTmaUrl?(rt.gridName="local-tma-from-options",rt.gridType="local-tma"):o.useLocalChromeDriver?(rt.gridName="local-chrome-driver-from-options",rt.gridType="local-chrome"):o.useChromeLauncher?(rt.gridName="chrome-launcher-from-options",rt.gridType="local-chrome"):o.browserstack?rt.gridName="browserstack-from-options":o.saucelabs&&(rt.gridName="saucelabs-from-options"),await t.testEndAndReport(Pe,we,r,Ha,Xn,rt).catch(CT=>Gp.error("testEndAndReport threw an error",{err:CT})),Xn)return;this.combinedTestResults[we.resultId]=we,Og({executionId:r,projectId:f,testId:Et,resultId:we.resultId,result:we,ucid:T,companyId:I,companyName:b,projectName:F,companyPlan:x,source:v,user:E,lightweightMode:A,logger:Gp,isStartUp:D,projectType:R,appSource:qa}),l&&!we.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},Y=(Pe,Et)=>{this.combinedTestResults[Et.resultId]=Et,t.onTestIgnored(Pe,Et.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},X=(Pe,Et)=>t.onGridSlot(Pe,Et);for(o.userData={loginData:{...br(),refreshToken:jo(),authData:br(),token:u,userAccessKey:g},projectId:o.project,company:o.company,servicesUrl:fe},N("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(o,this.customExtensionLocalLocation,r,U,G,X,Y)});try{let u=await Ct(),g=await $o(),h=await m(u,g);if(this.workers.size>0&&this.workers.clear(),c)throw new qt;return h}catch(u){throw Gp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var Yn,ja,Hp,$a,eT=w(()=>{"use strict";Yn=S(require("lodash"));B();$();pe();ne();We();ns();Tu();Nu();he();_t();Zg();K();Zb();ei();({CLI_MODE:ja}=Ut),Hp=C("test-plan-runner"),$a=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}async runTestAllPhases(e,t,r,n,o,i,a,l){let c={},d=new Ba(this.customExtensionLocalLocation),m=async()=>{let f=o.beforeParallel||1,y=!0,T=await d.runTests(e,l,i,a,o,n,f,y);Object.assign(c,T)},u=async()=>{let f=lo||o.parallel,y=!1;N("right before this.workerManager.runTests");let T=await d.runTests(t,l,i,a,o,n,f,y);N("right after this.workerManager.runTests"),Object.assign(c,T)},g=async()=>{let f=o.afterParallel||1,y=!1,T=await d.runTests(r,l,i,a,o,n,f,y);Object.assign(c,T)};Lg({executionId:i,projectId:o.project}),N("right before runBeforeTests");try{return await m(),N("right before runTestPlanTests"),await u(),N("right after runTestPlanTests"),await g(),c}catch(f){if(Hp.error("error running test plan",{err:f}),f instanceof qt)return l.markAllQueuedTests(i,de.ABORTED,"aborted",!1);throw f}finally{await h()}async function h(){var y,T,I,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===ja.SELENIUM){let[{getSessionPlayer:v},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(Te(),Zt)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:x}=v();await x.closeBatch(i,E);return}let f;try{if(!((b=(I=(T=o.company)==null?void 0:T.activePlan)==null?void 0:I.premiumFeatures)!=null&&b.applitools)||(f=await Cl(o.project),Yn.default.isEmpty(f)||!i))return;let{runKey:v,url:E}=f;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:E,apiKey:v}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,l){var b,v,E;let c=se(),d=n.project;lc(c),e.forEach(x=>Object.assign(x,{isBeforeTestPlan:!0})),r.forEach(x=>Object.assign(x,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Li(m,n,i,a),g=Yn.default.chain(m).map(x=>{var D;return((D=x.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(g==null?void 0:g.length)===1?g[0]:null,f=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(x=>x.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,o,f);N("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||ee.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,o,c,l,h),N("before runTestAllPhases");let I=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,o||"All Tests",u);return N("before executionEnd"),await u.executionEnd(c),N("after executionEnd"),{results:I,executionId:c,testPlanName:o,configName:h}}async runTestPlans(e,t){Hp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Yn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await pl(i,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==ja.APPIUM&&await Yl(e,r(c)),await ie(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await ug(e,d);let g=u.overrideExecutionName||d.name;return await ie(c[m],async f=>{let y=await this.runTestPlan(f.beforeTests,f.tests,f.afterTests,u,g,m,t);ee.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:Jl(n[m][E])})),I=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,x)=>Object.assign(E,x),{}),b=Jl(I);Object.assign(o,I);let v=b?T[0].executionId:T.find(E=>!E.status).executionId;return await cl(i,m,{success:b,executions:T,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var l;Hp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),N("before getSuite");let r=await Tf(e,t);if(N("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;N("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===ja.APPIUM&&(a=await un({appId:e.appId,projectId:e.project})),await ie(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==ja.APPIUM&&await Yl(e,c),N("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,o,null,t,i);return N("right after runTestPlan"),await ee.onTestPlanFinished(d.results,o,this.startTime,d.executionId,i),d})}async run(e){let t=An(),r=[];Gs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Yn.default.flattenDeep(r);return N("right before onAllTestPlansFinished"),await ee.onAllTestPlansFinished(n),N("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var nT={};H(nT,{init:()=>nR,run:()=>ZI});async function NI(s){let e=s.project,t=await ml(e);if(t!=null&&t.isExecutionBlocked)throw console.error("You have reached the limit of runs for the billing month, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli"),fn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ds}function UI(s,e){var i,a,l,c,d,m,u,g;let t=Eo(e.activePlan),r=s.parallel;if(t==="free"&&r>rT)throw new P(`The free plan allows only ${rT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let h=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!h)throw new P("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let f=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.runInTurboMode;s.lightweightMode&&!f&&(console.warn(`
408
+ return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Zy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ga,ha,rb=w(()=>{"use strict";ga=require("url");ue();ha=class extends V{async updateBaseUrl(e){let t=new ga.URL(e),r=new ga.URL(this.context.recordedBaseUrl),n=new ga.URL(this.context.baseUrl);return t.host===r.host&&r.host!==n.host&&(t.host=n.host),t.href}async performAction(){let e=this.context.data.testimNavigationStepDestination||this.context.data.url;if(this.step.openInNewTab){await this.driver.client.newWindow(e);return}let t=await this.updateBaseUrl(e);await this.driver.url(t)}}});var ya,sb=w(()=>{"use strict";ue();B();ya=class extends V{async performAction(){await ae(this.step.durationMS||0)}}});var ba,nb=w(()=>{"use strict";ue();ba=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var qn,ob=w(()=>{"use strict";ue();qn=class extends V{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(r,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t,apiCallAsync:r}=this.sessionPlayerInit;return typeof r=="function"&&r.length===2?r(t,e):new Promise(n=>{t(e,n)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var Ta,ib=w(()=>{"use strict";ue();Ta=class extends V{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var ab,vp,Sp,cb=w(()=>{"use strict";ab=S(require("@applitools/spec-driver-webdriverio"));io();Te();vp=class{constructor(){let{EyeSdkBuilder:e}=Z(),t=nd["@applitools/eyes-sdk-core"]||"N/A",{makeSDK:r}=require("@applitools/eyes-sdk-core");this.sdk=r({name:"Testim.io",version:`4.0.1/eyes-sdk-core/${t}`,spec:ab.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=Z(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},Sp=new vp});var ub,lb,zn,pb=w(()=>{"use strict";ub=S(require("lodash"));ue();$();cb();lb=C("pixel-validation-step-action"),zn=class extends V{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||o,l=await Sp.getManager(t,this.context.config.applitoolsConcurrency||5,a,this.runContext.applitoolsIntegrationData),c=this.getTarget()||{},d;try{let g=await l.openEyes({driver:this.driver.client,config:r,logger:n}),f={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};ub.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(f,i.applitoolsStepSettings),lb.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await g.check({settings:f}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await g.close()}}catch(g){lb.error("Applitools SDK step failed",{err:g,info:g.info}),d={isApplitoolsSdkResult:!0,success:!1,err:g}}return await Sp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var vs,Ep=w(()=>{"use strict";fs();K();oa();vs=class extends ar{async executeCliCode(){var h,f,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(f=(h=t.company)==null?void 0:h.activePlan)==null?void 0:f.premiumFeatures)==null?void 0:y.cliAction)&&!r)return{success:"skipped",reason:"CLI action is not enabled in your current plan"};let{code:o="",id:i=""}=e,{incomingParams:a,testResultId:l,retryIndex:c,stepResultId:d}=t,m={config:t.config,data:t.data},u=t.data.timeToPlayStep,g=await ms(o,i,a,m,l,c,d,u);return this.checkCodeResponse(g)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof oe?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var cr,db=w(()=>{"use strict";Ep();cr=class extends vs{isFailedResult(e){return e===!1}}});var wa,mb=w(()=>{"use strict";Ep();wa=class extends vs{isFailedResult(e){return!e}}});var va,fb=w(()=>{"use strict";fs();ue();K();va=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await ds(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof Rt?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof oe?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var kr,gb=w(()=>{"use strict";ue();kr=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ye,hb=w(()=>{"use strict";ue();ye=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Sa,yb=w(()=>{"use strict";ue();Sa=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ea,bb=w(()=>{"use strict";ue();Ea=class extends V{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function aI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function Ia(s,e){aI(cI,e),e.registerLocateStepActionUtils(Wn.getUtils(s))}var cI,Ip=w(()=>{"use strict";fy();yy();Ay();xy();Py();Oy();My();Ny();Uy();Fy();$y();Wy();Vy();qy();Jy();tb();rb();sb();nb();ob();ib();pb();db();mb();fb();gb();hb();yb();bb();cI={locate:Wn,scroll:ea,mouse:ta,submit:la,text:sa,"special-key":ia,"user-code":Gt,"validation-code-step":Gt,"wait-for-code-step":Gt,"action-code-step":Gt,"condition-step":ws,"skip-code-step":ws,"element-code-step":ws,"evaluate-expression":ra,"text-validation":Gn,"wait-for-text-validation":Gn,"select-option":ca,"drop-file":da,"input-file":fa,hover:ua,navigation:ha,wheel:pa,sleep:ya,refresh:ba,"keyboard-shortcut-step":aa,"api-validation":qn,"api-action":qn,"api-code-step":Gt,"extract-text":Ta,"simple-ui-verification":zn,"wait-for-simple-ui-verification":zn,"cli-validation-download-file":kr,"cli-wait-for-download-file":kr,"network-validation-step":kr,"cli-validation-code-step":cr,"cli-wait-for-code-step":cr,"cli-action-code-step":cr,"cli-api-code-step":cr,"cli-condition-step":wa,"node-package":va,"email-code-step":Gt,"cli-email-code-step":cr,"sfdc-internal-test-step":Ea,"sfdc-recorded-step":Sa,"sfdc-step-login":ye,"sfdc-step-loginas":ye,"sfdc-step-logout":ye,"sfdc-step-sobjectcreate":ye,"sfdc-step-sobjectdelete":ye,"sfdc-step-findrecord":ye,"sfdc-step-quickaction":ye,"sfdc-step-sobjectedit":ye,"sfdc-step-sobjectvalidate":ye,"sfdc-step-launchapp":ye,"sfdc-step-wait-for-page-load":ye,"sfdc-step-closeconsoletabs":ye,"sfdc-step-relatedlistaction":ye,"sfdc-step-permission-validation":ye,"sfdc-step-convert-lead-to-opportunity":ye,"sfdc-step-quotelineeditor":ye,"sfdc-document-validation":kr,"sfdc-step-flow-screen-completion":ye,"sfdc-step-sobjectverifyoptions":ye}});var Tb,lI,Ss,Rp=w(()=>{"use strict";Tb=["simple-ui-verification","wait-for-simple-ui-verification"],lI=[...Tb,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor","sfdc-document-validation","sfdc-step-flow-screen-completion","sfdc-step-sobjectverifyoptions"],Ss=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=lI.includes(e.stepType)?[r]:t(r);this.resetStepVariables(r,n),e.context.data.maxTotalStepTime=r}initRetryTime(){this.resetRetryVariables()}getTotalStepRunTime(e){let r=e.context.config.stepTimeout;return Tb.includes(e.stepType)&&(r=e.context.config.applitoolsStepTimeout||18e5),e.step.type.startsWith("sfdc-")&&(r=e.step.defaultTimeout),e.step.useStepTimeout&&e.step.stepTimeout?e.step.stepTimeout:r}getTotalStepTimeLeftToPlay(e,t=this.totalStepTime){let r=Date.now()-e.startTimestamp;return t-r}getCurrentRetryTime(e){return e.retryIndex<this.currentRetryTimes.length?this.currentRetryTimes[e.retryIndex]:this.getTotalStepTimeLeftToPlay(e)}getTotalCurrentRetryTimeLeft(e){let t=Date.now()-this.currentRetryStart;return this.getCurrentRetryTime(e)-t+1e3}getTabTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getDynamicParentTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getFrameTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getLocateTimeout(e){return this.getTotalCurrentRetryTimeLeft(e)}getActionTimeout(e){if(this.isDebuggerConnected)return 6e5;let t=5e3,r=e.step.type,n=3e4;return r==="sleep"?e.step.durationMS+t:Math.max(this.getTotalStepTimeLeftToPlay(e),n)}}});var vb={};H(vb,{SeleniumTestPlayer:()=>Kn});var wb,uI,Kn,Ap=w(()=>{"use strict";B();wb=require("@applitools/eyes-sdk-core");Dn();K();$();gp();ly();Tp();Qi();dy();wp();Te();Ip();Rp();uI=C("SeleniumTestPlayer"),Kn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new Ss(Zi());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Z();this.driver=n??new Ar;let d=new Xi(this.driver);this.stepActionFactory=new c(d),Ia(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ji(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=py(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new bs(this.driver),FrameLocator:m,portSelector:Yi,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:wb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.tabService.setAddFrameHandlerCallBack(this.sessionPlayer.addPlaybackFrameHandler.bind(this.sessionPlayer)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){n!=null&&n.isTabOpener&&this.tabService.addNewPopup(this.id,n.id).catch(()=>null)}async onDone(){var r,n;let{commonConstants:e}=Z(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof oe&&await((n=this.driver)==null?void 0:n.forceEnd().catch(()=>null))}this.sessionPlayer.playbackManager.off(e.playback.RESULT,this.onStepCompleted),Object.assign(this,{sessionPlayer:null,tabService:null,stepActionFactory:null,driver:null})}clearSessionTabs(){this.tabService.clearAllTabs(this.id)}async addTab(e,t={loadInfo:!0}){let r=await this.driver.getTabIds();if(!Array.isArray(r)){uI.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(r);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var Cp={};H(Cp,{WorkerSelenium:()=>xp});function dI(s){let{playback:e}=Z().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>N(`Got event ${t}`))}var Ra,pI,xp,Pp=w(()=>{"use strict";B();We();jn();$();_t();ii();ne();mp();K();Ap();Te();it();Ra=C("worker-selenium"),pI=1e9,xp=class extends Lt{initPlayer(t){return new Kn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){N("in WorkerSelenium getBrowserOnce"),ee.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ys(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await i.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:o,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.SELENIUM}),N("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),N("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,pI),await this.windowUtils.validatePageIsAvailable(),N("in WorkerSelenium after navigate")}catch(c){let d=c.message&&(c.message.startsWith("Malformed URL")||c.message.includes("Reached error page: about:neterror"))&&a==="firefox",m=c.message&&c.message==="invalid argument";throw c instanceof It||d||m?new It(`Page '${l}' is not available`):(Ra.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Wo(),initializedFromCache:Vo()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=Z(),{driver:i,sessionPlayer:a}=r,l=n||"runner";ee.onWaitToTestComplete(this.id),dI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,this.options.mode===q.SELENIUM&&a.setLightweightMode(this.options.lightweightMode),t.sfdcCredential&&a.setSfdcCredential(t.sfdcCredential),o.initialize({serverUrl:this.options.localRCASaver});let c=null;(m=this.options.lightweightMode)!=null&&m.preloadTests&&(c=(await bn(this.options))[this.testId]);let d=async()=>ce(new Promise((u,g)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:u,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,incognito:!1,remoteRunId:t.remoteRunId,preloadedTest:c}).catch(g)}),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var g;throw u instanceof oe&&((g=a.stopPlayingOnTestTimeout)==null||g.call(a)),u}).then(async u=>{await o.drain(),u.stepsResults=null,u.resultId=this.testResultId,i.isAlive()||(Ra.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let g=i.maxKeepAliveGap();g>=3e4&&(Ra.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=g);let f={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${f.success?"passed":"failed"}`).catch(()=>{}),f});i.start(),N("right before super.runTestOnce in workerSelenium");try{await super.runTestOnce(t,r),N("right after super.runTestOnce in workerSelenium");let u=await d();return N("right after runSeleniumTest"),u}catch(u){throw Ra.error("failed to run test once",{err:u}),u}}}});var Sb,Eb,qe,mI,fI,kp,vt,Aa=w(()=>{"use strict";Sb=S(require("ora")),Eb=S(require("jimp"));pe();He();he();$();ne();Te();le();qe=C("mobile-grid-service"),mI="https://tdc.tricentis-cloud.com",fI="https://ui.headspin.io",kp=class{constructor(){this.gridsAppIdGetter={[O.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[O.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[O.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[O.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[O.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[O.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===O.TESTIM_TDC||e===O.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===O.TESTIM_HEADSPIN?`${r||Za}/${tc}/devices`:t===O.TESTIM_TDC?`${r||ec}/${tc}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await Ge({url:r,headers:n,body:o})}catch(i){throw qe.debug(`error while locking device ${t}`,{error:i}),i.status===401?new Error(`failed to lock device ${t}, device may be already locked and in use`):i}}async getHeadSpinDeviceConnection(e,t){let n=`${this.getBaseApiUrl(e)}/device_id:${t}/automation-config`;try{let o=await be(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw qe.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t,r){let n=await js(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===O.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===O.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([O.BROWSERSTACK,O.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:o,gridId:i}){var a,l,c;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let d=await Ll({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n){let{executionId:o,testId:i,testResultId:a}=e,{project:l,projectData:{type:c}={},company:{companyId:d=""}={},gridData:{gridId:m="",type:u=""}={}}=n,g=t.capabilities,h=g.platformName,f;if(u===O.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:T}=Z();f=T(t.capabilities)}else f=await this.getDeviceFromAppiumCapabilities(g,t,r,h,u,l,c,d,m);let y=await this.buildRemoteResultLink(n.gridData,t.sessionId,g);return await Tr(l,o,i,a,"RUNNING",{device:f,...y&&{remoteResultLink:y}}),qe.info("device details updated on testResult",{testResultId:a,executionId:o,testId:i,device:f,remoteResultLink:y,gridType:u}),f}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===O.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),i=Number(o[0]),a=Number(o[1]);return{scaleFactor:e.pixelRatio,width:i,height:a}}try{let{AppiumApi:o}=Z(),i=new o(t,r.sessionId,null),[a,l]=await Promise.all([i.getScreenshot(),i.getDeviceSize()]),c=Buffer.from(a,"base64"),d=await Eb.default.read(c),m=d.getWidth(),u=d.getHeight();return{scaleFactor:m/l.width,width:m,height:u}}catch(o){return qe.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,o,i,a,l,c){let[d,m]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:o,projectId:i,projectType:a,companyId:l,gridId:c})]),u=this.getOsVersion(e,o);return{name:m??"",model:e.deviceModel,udid:e.udid,osVersion:u,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===O.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ls}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===O.SAUCELABS?r.testobject_test_report_url:e.type===O.TESTIM_TVC?r.replayUrl:e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC?`${e.type===O.TESTIM_HEADSPIN?fI:mI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let r=(await be(`${wd}/devices`)).find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,geo:"local",osVersion:r.osVersion,osType:r.deviceType.toLowerCase(),scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:o,testResultId:i}=r,a=await this.getTmaDeviceDetails(e),{project:l}=t;return await Tr(l,n,o,i,"RUNNING",{device:a}),qe.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,o=t.mobileApp,i=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:o,gridHost:e.host});return i?(L.flags.allowFixingAppIdStructure.isEnabled()&&(qe.info("fixing gridAppId structure",{gridAppId:i,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await Ml({gridAppId:i,gridId:e.gridId,projectId:r,gridType:n,appId:o.appId,gridHost:e.host})),i):t.getAppPathByGridType(n,e.gridId,o)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await un({appId:e,projectId:t});return{appUrl:`${fe}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(Td*60))+1)*60*1e3,Math.max(bd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let a={[O.BROWSERSTACK]:{name:"Browserstack"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[O.P_CLOUDY]:{name:"pCloudy"}}[o].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,Sb.default)(`uploading app to ${a} please wait..`).start();try{qe.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await Dl({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),qe.error(`failed to upload app to ${a}`,{error:d,mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId}),new Error(`failed to upload app to ${a}`)}}async verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:t,projectId:r,gridId:n,gridType:o,mobileAppId:i}){let a=t.get(i);if(a!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:o});return t.set(i,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",o,{executionId:i,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:g=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){qe.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:i});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,o=T.mobileApp,e.nativeApp=o}else qe.info("no appId setting appPath from app associated with the test",{projectId:c,testResultId:a,executionId:i}),n=e.downloadableAppPublicLink||"";let h=l||e.mobileApp.appId,f=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=g===O.BROWSERSTACK||g===O.TESTIM_TVC||g===O.P_CLOUDY;if(f){let T=t.projectData.type,I=await this.verifyAppStillExistsOnGrid({gridAppId:f,gridData:m,projectType:T});I&&(qe.info("app exists on grid, using gridAppId",{gridAppId:f,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=f),!I&&y&&(qe.info("app not exists on grid, uploading it",{gridAppId:f,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:g,mobileAppId:h})),!I&&!y&&qe.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:i})}return!f&&y&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:g,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var d,m;let{accessToken:n,user:o,host:i,key:a,type:l,apiUrl:c}=t;if(l===O.BROWSERSTACK){let u=`${Ls}/recent_apps`,g=await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a});return Array.isArray(g)?g.some(h=>h.app_url===e):!1}if(l===O.SAUCELABS){let g=`${i.includes("eu-central-1")?Ed:Sd}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:g,user:o,key:a})).items.some(f=>f.id===e)}if(l===O.TESTIM_HEADSPIN||l===O.TESTIM_TDC){let u=`${c}/${rc}/apps`;return c||(u=`${l===O.TESTIM_HEADSPIN?Za:ec}/${rc}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===O.TESTIM_TVC){let u=`${vd}/versions/${e}/info`,g=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:g,authType:"Upload-Token",userAgent:"Testim-CLI"}),!0}catch(h){return h.status!==404&&qe.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===O.P_CLOUDY){let u=await this.getPCloudyAuthToken(i,o,a),g=`https://${i}/api/drive`,h=await Tc({url:g,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await be(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r,userAgent:n}){let o={Authorization:`${r} ${t}`,...n&&{"User-Agent":n}};return await be(e,void 0,o)}},vt=new kp});function Ib({nativeAppMetadata:s,appPath:e,gridInfo:t}){if(!s&&!e||!s)throw Error("Application not specified. Please provide the required application for execution and try again.");if(!s.id&&!s.activity&&!s.packageName)throw Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");if(t.mode!=="local"&&!gI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function hI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==O.TESTIM_TDC&&e.type!==O.TESTIM_HEADSPIN)throw Error("unsupported grid was detected please make sure to select supported mobile grid for direct connection");if(!s&&!(r!=null&&r.deviceUdid))throw Error("missing device udid or test run config is not static");if(!s&&(r!=null&&r.deviceUdid)&&r.deviceUdid.split(",").length!==1)throw Error("provided static config contains multi devices")}function yI(s){let{testName:e,executionId:t,testResultId:r,customTag:n}=s,o=[{executionId:t},{testResultId:r}];return e&&o.push({testName:e}),n&&o.push({customTag:n}),o}function bI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===O.TESTIM_TDC,a=s===O.TESTIM_HEADSPIN,l=i?"tdc":"headspin",c=a&&L.flags.enableBatchHeadSpin.isEnabled(),d=i&&(L.flags.enableBatchTDC.isEnabled()||L.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=L.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture`]:!0,...L.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...o&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:yI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:300}}}function xa(s){return"id"in s?s.id:s.packageName}function TI(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function wI({projectType:s,sessionCaps:e,options:t,nativeAppMetadata:r,appPath:n,androidActivityWait:o}){let{fullReset:i,setNoReset:a}=t,l={"appium:app":n},c=n==null?void 0:n.startsWith("http");n&&!c&&(l=TI(n,t.gridData.type));let m=()=>i===void 0&&n?!0:typeof i=="string"?i!=="false":i;switch(s){case"ios":return{...e,platformName:"iOS","appium:autoAcceptAlerts":!0,"appium:automationName":"XCUITest","appium:fullReset":m(),...r&&{"appium:bundleId":xa(r)},...n&&l};case"android":return{...e,platformName:"Android","appium:fullReset":!!i,"appium:autoGrantPermissions":!a,"appium:automationName":"UiAutomator2",...o&&{"appium:appWaitActivity":`${o}, *`},...r&&{"appium:appPackage":xa(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Or({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:o=""}){switch(s){case"ios":return{platformName:"iOS",[`${o}autoAcceptAlerts`]:!0,[`${o}automationName`]:"XCUITest",[`${o}fullReset`]:!0,...t&&{[`${o}bundleId`]:xa(t)},...r&&{[`${o}app`]:r},...e};case"android":return{platformName:"Android",[`${o}autoGrantPermissions`]:!0,[`${o}automationName`]:"UiAutomator2",...n&&{[`${o}appWaitActivity`]:`${n}, *`},...t&&{[`${o}appPackage`]:xa(t),[`${o}appActivity`]:t.activity??".*"},...r&&{[`${o}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Rb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=bI(i.type,o,n);return wI({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Pa({osVersion:s,mobileConfig:e}){let{staticAllocation:t,dynamicAllocation:r}=e;return s||(t!=null&&t.osVersion?t==null?void 0:t.osVersion:r!=null&&r.osVersionRegex?r==null?void 0:r.osVersionRegex:".*")}function ka({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e,i=r===O.P_CLOUDY;return s||(n!=null&&n.deviceName?i?n.deviceUdid:n.deviceName:o!=null&&o.deviceNameRegex?t==="android"&&o.deviceNameRegex===".*"&&i?sc:o.deviceNameRegex:t==="ios"&&r===O.BROWSERSTACK?"iPhone.*":i?t==="ios"?"apple":sc:".*")}function vI(s,e){let{androidToken:t,iosToken:r}=s,n=e==="ios";if(!t&&!r)throw Error("missing access token for testim virtual cloud");if(n&&!r)throw Error("missing ios token for testim virtual cloud");if(!n&&!t)throw Error("missing android token for testim virtual cloud");return n?r:t}function SI(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Ca(s,Es)}}function Ab(s,e,t){return s?Object.entries(s).reduce((r,[n,o])=>{if(e(n)){if(!t)return r[n]=o,r;let i=n.replace(t,"");r[i]=o}return r},{}):{}}function EI(s){return Ab(s,e=>e.startsWith("browserstack."),"browserstack.")}function II(s){return Ab(s,e=>!e.startsWith("browserstack."))}function xb(s){return!s||!Cb(s)?"2.0.0":s}function Cb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Pb({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,o=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,i=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&o.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&i.test(s),d=l||c;if(t){let m=Cb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Ca(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let o=`${e}${r}`;t[o]=n}),t}function RI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=vI(o,s),g=Pa({osVersion:l,mobileConfig:d}),h=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),f=ze(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y=L.flags.enableWaldoRunner.isEnabled(),T={device:h,os_version:g,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":f,...y&&{"waldo:automationName":"WaldoTestim"},"waldo:options":{token:u}};return Or({projectType:s,sessionCaps:T,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function AI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:g}=o,h=L.flags.enableAppium2pCloudy.isEnabled(),f=Pa({osVersion:l,mobileConfig:d}),y=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:g}),T=/^[a-zA-Z]+$/.test(y),I={...f!==".*"&&{pCloudy_DeviceVersion:f},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:i.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...I,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Id),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=SI(b)),t="",Or({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Es}})}function xI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Pa({osVersion:l,mobileConfig:d}),g=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,_r.omit)({...n.saucelabs},["automationName","platformName"]),f={...h["sauce:options"]};if(delete h["sauce:options"],Pb({osVersion:h.platformVersion||u,projectType:s,appiumVersion:f.appiumVersion})){let T={debug:!0,networkLogs:!0},I={user:o.user,key:o.key,name:i.testResultId,build:i.executionId,appiumVersion:xb(f.appiumVersion),deviceName:g,tags:Object.values(i)},b={"appium:platformVersion":u,"appium:deviceName":g,...Ca(h,Es),"sauce:options":{...T,...I,...(0,_r.omit)(f,"appiumVersion")}};return Or({projectType:s,sessionCaps:b,appiumPrefix:Es,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":o.user,"saucelabs.key":o.key,platformVersion:u,deviceName:g,tags:Object.values(i),name:i.testResultId,build:i.executionId,...h,...f};return Or({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function CI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=Pa({osVersion:l,mobileConfig:d}),g=ka({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=EI(n.browserstack),f=(0,_r.omit)(II(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:I}=n.browserstack||{},b=L.flags.enableAppium2BrowserStack.isEnabled();if(b||Pb({osVersion:f.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let E={userName:o.user,accessKey:o.key,appiumVersion:b?"2.0.1":xb(h.appiumVersion),projectName:y||i.project,buildName:T||i.executionId,debug:!0,networkLogs:!0},x={"appium:platformVersion":u,"appium:deviceName":g,...Ca(f,Es),"bstack:options":{...E,...(0,_r.omit)(h,"appiumVersion")}};return Or({projectType:s,sessionCaps:x,appiumPrefix:Es,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let v={os_version:f.platformVersion||u,device:f.deviceName||g,realDevice:!0,name:I||i.testResultId,project:y||i.project,build:T||i.executionId,buildTags:Object.values(i).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...f,...Ca(h,"browserstack.")};return Or({projectType:s,sessionCaps:v,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function PI(s){if(O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type)return Rb(s);if(O.TESTIM_TVC===s.gridInfo.type)return RI(s);if(O.P_CLOUDY===s.gridInfo.type)return AI(s);if(O.SAUCELABS===s.gridInfo.type)return xI(s);if(O.BROWSERSTACK===s.gridInfo.type)return CI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function kI(s,e){var c,d;let{staticAllocation:t,dynamicAllocation:r,type:n}=e||{},{deviceName:o,osVersion:i,deviceUdid:a}=s,l={};return n==="dynamic"&&(!o&&((c=r==null?void 0:r.selector)!=null&&c.manufacturer)&&(l.manufacturer=r.selector.manufacturer),!i&&((d=r==null?void 0:r.selector)!=null&&d.osVersion)&&(l.os_version=r.selector.osVersion)),n==="static"&&!a&&(t!=null&&t.deviceUdid)&&(l.device_id=t.deviceUdid),o&&(l.manufacturer=o),i&&(l.os_version=i),a&&(l.device_id=a,delete l.os_version,delete l.manufacturer),l}function kb(s){let{gridInfo:e,nativeAppMetadata:t,options:r,appPath:n,testRunConfig:o}=s,{selectedGrid:i}=(o==null?void 0:o.mobile)||{};if(o!=null&&o.mobile&&(i==null?void 0:i.type)!==e.type)throw Error(`selected grid type ${i.type} is not equal to grid type ${e.type}`);Ib({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=PI(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let m=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",u=kI(r,o==null?void 0:o.mobile);if(!(0,_r.isEmpty)(u)){let g=Object.entries(u).map(([h,f])=>f.split(",").map(y=>y===".*"||y==="="?"":`${h}:${y}`).join(",")).join(" ").trim();l[`${m}:selector`]=g}}let c=e.type===O.TESTIM_TVC?{alwaysMatch:l}:l,d=L.flags.increaseTDCRequestTimeout.isEnabled();return{...a,desiredCapabilities:l,...d&&{connectionRetryTimeout:48e4},capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function _b(s){var h,f;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;Ib({nativeAppMetadata:r,appPath:o,gridInfo:t}),hI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((f=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:f.deviceUdid),m=await vt.getGridDirectConnection(t,d),g=Rb({projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(g["appium:udid"]=d),{...m,desiredCapabilities:g,capabilities:g,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function Ob(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s,i=Or({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n});return e==="ios"&&delete i.app,i}function Lb(s){var t,r;let e={...s};return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],(t=e.capabilities["sauce:options"])==null||delete t.user,(r=e.capabilities["sauce:options"])==null||delete r.key,delete e.capabilities.key,delete e.capabilities.user,e}var _r,Es,gI,_p=w(()=>{"use strict";le();ne();Aa();_r=require("lodash");B();pe();Es="appium:",gI=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var _a,Mb=w(()=>{"use strict";_a=class{constructor(){this.sessionTabs={}}on(){}tabCount(){}getAllOpenTabIds(){return[]}isSessionTab(){return!1}getAllTabInfos(){return{}}async addNewTab(){}addOpenerStepId(){}addOpenerStep(){}getTabUtilsByTabIdAndSessionId(){}getTabUtilsByTabId(){return{}}getTabInfo(){return{}}getTabUtils(){return{}}getMainTabInfo(){}getMainTabUtils(){return{}}getMainTabId(){return null}async isMainTabExists(){return!1}clearAllTabs(){}async switchTab(){}async getTabDetails(){}async isMainTabIncognito(){return!1}async getTabIdByTabInfo(){return NaN}}});var Oa,Nb=w(()=>{"use strict";B();Oa=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=Ks;this.getLinksFromUnescapeHTML=Js}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}async executeInAut(e,t){throw new Error("not implemented (mobile)")}extractTargetText(e){throw new Error("not implemented (mobile)")}getCookie(e){throw new Error("not implemented (mobile)")}setCookie(e){throw new Error("not implemented (mobile)")}async getNextDynamicParent(e,t){throw new Error("not implemented (mobile)")}}});var Op,La,Ub=w(()=>{"use strict";$();Op=C("mobile-frame-locator-mock"),La=class{foundFrameCallback(){return Op.info("foundFrameCallback-mock invoked"),{}}locate(){return Op.info("locate-mock invoked"),{}}async findFrame(){return Op.info("findFrame-mock invoked"),{}}}});var _I,Bb,Fb,Is,Lp=w(()=>{"use strict";_I=S(require("webdriverio")),Bb=require("@applitools/eyes-sdk-core");Mb();Tp();$();Nb();wp();Te();Ip();Ub();Rp();Fb=C("appium-test-player"),Is=class{constructor(e,t,r,n=_I,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Z(),m=new Oa(this.driver);this.stepActionFactory=new c(m),Ia(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Ss(Zi()),this.sessionPlayer=new a(e,{tabService:new _a,cookieUtils:void 0,FrameLocator:La,portSelector:Yi,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Bb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,o={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Fb.info("appium session deleted",{...o}))}catch(i){Fb.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=Z();e.off(i.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function OI(s){return await be(`${s}/api/status`)}async function jb(s,e){return await be(`${s}/api/devices/${e}/status`)}async function $b(s){if((await OI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Wb=w(()=>{"use strict";He()});var Vb={};H(Vb,{WorkerLocalTma:()=>Up});var Lr,Dp,Mp,Np,Up,Gb=w(()=>{"use strict";He();_p();jn();B();$();_t();Lp();Te();Wb();Aa();Lr=C("worker-appium"),Dp=class extends Error{},Mp=class extends Error{},Np=class extends Error{},Up=class extends Lt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=Z(),{DOMParser:n}=await import("linkedom"),o=new r(this.sessionData.serverAddress,this.sessionData.sessionId,n);return t.sessionPlayer.playbackManager.appiumApi=o,o}async getBrowserOnce(t,r,n,o){var E;if(ee.onGetSession(this.id,this.testName,t.runMode),!this.options.localTmaUrl||!this.options.deviceUdid)throw new Error("Missing localTmaUrl or deviceUdid");let{localTmaUrl:i,deviceUdid:a,projectData:l}=this.options;await $b(i);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,g=this.options.appId;if(g){let{mobileApp:x}=await vt.getMobileAppDataByAppId({appId:g,projectId:c,token:d});t.nativeApp=x}let h=u==="android"?t.androidActivityWait:null,f=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!f)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:I,version:b},v]=await Promise.all([this.getAppStateFromDevice(i,a,T),jb(i,a)]).catch(x=>{throw this.handleDeviceNotFoundError(x),x});if(Lr.info("device status and app state",{deviceStatus:v,appInstalled:I,version:b,executionId:this.executionId,testResultId:this.testResultId}),!I&&t.isAppFromDevice&&!g)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!I&&y&&(await this.installApp(i,a,y),Lr.info("Application installed successfully",{deviceUdid:a,executionId:this.executionId,testResultId:this.testResultId}));try{let x={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(E=this.options.projectData)==null?void 0:E.name}-${this.options.project}`},D=Ob({projectType:u,nativeAppMetadata:f,appPath:y,androidActivityWait:h,sessionTags:x,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),F={capabilities:{udid:a,...D}};Lr.info("requesting new appium session from TMA",{tmaSessionSettings:F,executionId:this.executionId,testResultId:this.testResultId});let R=await this.requestNewAppiumSessionFromTma(i,F,f);this.sessionData=R;let A=await m.attach({sessionId:R.sessionId,capabilities:D});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),Lr.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:A.sessionId,testResultId:this.testResultId,nativeAppMetadata:f,sessionCaps:A.capabilities})}catch(x){throw Lr.error("failed to start application",{err:x}),x}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await Ge({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new Np(l):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,l=(await be(i)).find(c=>"id"in c?c.id===n:c.packageName===n);return l?{appInstalled:!0,version:l.version}:{appInstalled:!1,version:""}}async installApp(t,r,n){var o,i;try{let a=await Nt(n);await Bs(`${this.baseDevicePath(t,r)}/apps`,{},{file:{buffer:a.body,fileName:"app"}})}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message,c="Failed to install app";throw l&&(c=`${c}: ${l}`),new Mp(c,{cause:a})}}handleDeviceNotFoundError(t){var n,o;let r=(o=(n=t.response)==null?void 0:n.body)==null?void 0:o.message;if(t.status===404&&typeof r=="string"&&(r!=null&&r.startsWith("Ensure that the requested device")))throw new Dp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=Z(),{sessionPlayer:i}=r,a=n||"runner";ee.onWaitToTestComplete(this.id),i.playbackManager.executionId=t.executionId,i.playbackManager.executionName=t.executionName,i.playbackManager.appiumSessionData={...this.sessionData,device:this.device},await this.initAndGetAppiumAPI(r),o.initialize({serverUrl:this.options.localRCASaver});let l=async()=>{try{let c=await new Promise((m,u)=>{i.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:a,resolve:m,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(u)});return await o.drain(),c.stepsResults=null,c.resultId=this.testResultId,{...c,...t.seleniumPerfStats.getStats()}}catch(c){throw Lr.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw Lr.error("failed to run test once",{err:c}),c}}}});var qb={};H(qb,{WorkerAppium:()=>Fp});var Hb,Dr,Fp,zb=w(()=>{"use strict";_p();Hb=require("linkedom");jn();$();_t();Lp();Te();Aa();ne();is();Dr=C("worker-appium"),Fp=class extends Lt{initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){ee.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,l=await vt.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),c=a==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.uniqueId}`},u={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:m,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig},g;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await vt.lockDevice(o,this.options.deviceUdid),g=await _b(u)):g=kb(u),Dr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:Lb(g)});let h=this.getServerAddressFromGrid();this.activeSession=await i.remote(g),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,h,this.options);let f=`${h}/session/${this.activeSession.sessionId}`;this.updateSlotData(f),Dr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Dr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}async startKeepAlive(t){let{errors:r}=Z(),n=async()=>{try{await(t==null?void 0:t.getOrientation())}catch(o){Dr.error("failed to keep appium session alive",{err:o}),r!=null&&r.AppiumSessionTerminatedError&&o instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&yg(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Dr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===O.TESTIM_HEADSPIN||o===O.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`:o===O.P_CLOUDY?`https://${t}/appiumcloud/wd/hub`:`https://${t}:${r}/wd/hub`}getDirectAddressConnection(t){let{directConnectProtocol:r,directConnectHost:n,directConnectPort:o,directConnectPath:i}=t;if(r&&n&&o&&i)return`${r}://${n}:${o}${i}`}async runTestOnce(t,r){var u,g;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=Z(),{sessionPlayer:a}=r,l=n||"runner";ee.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let c;if(this.options.skipLoadBalancer){let h=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:f,hostname:y,port:T,path:I}=await vt.getHeadSpinDeviceConnection(this.options.gridData,h);c=`${f}://${y}:${T}${I}`}else c=this.getDirectAddressConnection(this.activeSession.capabilities)||this.getServerAddressFromGrid();let d=this.activeSession.capabilities;a.playbackManager.appiumSessionData={env:"remote",capabilities:d,sessionId:this.activeSession.sessionId,sessionToken:this.options.gridData.accessToken,gridType:this.options.gridData.type,projectType:this.options.projectData.type,gridId:this.options.gridData.gridId,companyId:(g=this.options.company)==null?void 0:g.companyId,device:this.device},a.playbackManager.appiumApi=new o(c,this.activeSession.sessionId,Hb.DOMParser),this.startKeepAlive(a.playbackManager.appiumApi),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let h=await new Promise((y,T)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:y,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(T)});return this.stopKeepAlive(),await i.drain(),h.stepsResults=null,h.resultId=this.testResultId,{...h,...t.seleniumPerfStats.getStats()}}catch(h){throw Dr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:h}),this.stopKeepAlive(),h}};try{return await super.runTestOnce(t,r),await m()}catch(h){throw Dr.error("failed to run test once",{err:h}),h}}}});var Da,Kb=w(()=>{"use strict";B();Dn();K();Da=class{constructor(e){this.id=e;this.driver=new Ar}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof oe&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Jb,Ma,Yb=w(()=>{"use strict";Jb=S(require("ws"));B();Ma=class{constructor(){this._cdpWs=null;this._cdpUrl=null;this._cdpCallbacks=new Map}async initSession(e,t=500){await this.stopSession(),this._cdpUrl=e,await this.initCDPWebsocket(t)}async initCDPWebsocket(e=500){if(this._cdpWs)return this._cdpWs;let t=new Jb.default(this._cdpUrl,{timeout:e}),r=Kt(o=>{t.once("open",o)}),n=Kt(o=>{t.once("error",o)}).catch(()=>{t.close(),t.removeAllListeners()});return t.on("message",o=>this.onCDPMessage(o)),this._cdpWs=Promise.race([r,n]).then(()=>t),this._cdpWs}onCDPMessage(e){var n;let t=JSON.parse(e),r=this._cdpCallbacks.get(t.id);r&&(this._cdpCallbacks.delete(t.id),t.error?r.reject(new Error(t.error)):(n=t.result.exceptionDetails)!=null&&n.exception?r.reject(new Error(t.result.exceptionDetails.exception.description)):r.resolve(t.result))}async stopSession(){let e=this._cdpWs;if(this._cdpUrl=null,this._cdpWs=null,this._cdpCallbacks.clear(),e)try{return(await e).close()}catch{return}}async cdpCommand(e,t,r){let n=await this.initCDPWebsocket();this._lastWsId||=0;let o=this._lastWsId++,i=new Promise((l,c)=>{this._cdpCallbacks.set(o,{resolve:l,reject:c})}),a={method:e,params:t,id:o};return r&&Object.assign(a,{sessionId:r}),n.send(JSON.stringify(a)),i}}});var Ua,Bp,Na,Xb=w(()=>{"use strict";B();Ua=S(require("chrome-launcher"));Hu();Yb();mn();Bp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Ma}async init(e){var h,f,y,T;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c,mode:d}=e,m=Mi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c,mode:d}),u=[...((h=m.desiredCapabilities)==null?void 0:h.chromeOptions.args)??[],...((T=(y=(f=m.capabilities)==null?void 0:f.alwaysMatch)==null?void 0:y["goog:chromeOptions"])==null?void 0:T.args)??[],...Ua.Launcher.defaultFlags().filter(I=>I!=="--disable-extensions")];this.chrome=await Ua.launch({chromeFlags:u,startingUrl:void 0,ignoreDefaultFlags:!0}),this.chrome.process.once("exit",()=>{this._isAlive=!1}),this.chrome.process.once("close",()=>{this._isAlive=!1}),this._isAlive=!0;let g=await fr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(g),es(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},Na=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new Bp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var jp={};H(jp,{WorkerExtension:()=>Jn});function LI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Qb(s){return LI(s)?s:new Error(s)}var pt,Jn,Fa=w(()=>{"use strict";We();K();jn();B();$();_t();ne();Kb();Xb();it();pt=C("worker-ext"),Jn=class extends Lt{initPlayer(){return this.options.useChromeLauncher?new Na(this.id):new Da(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(i=this.options.lightweightMode)==null?void 0:i.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps,mode:q.EXTENSION})}catch(a){throw pt.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Wo(),initializedFromCache:Vo(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return ee.onGetSession(this.id,this.testName,e.runMode),this._getBrowserOnce(e,t,r,n)}isUsingChromeLauncher(e){return Boolean(this.options.useChromeLauncher)}async updateTestStatusOnGrid(e,t,r){var o;let n=t?"passed":"failed";if(this.lambdatestService.isLambdatestRun()&&await e.executeJS(`lambda-status=${n}`),"browserstack"in this.options&&((o=this.options.browserstack)!=null&&o["browserstack.user"])){let i={action:"setSessionStatus",arguments:{status:n,reason:r}};await e.execute(`browserstack_executor: ${JSON.stringify(i)}`)}}async runTestOnce(e,t){let{testResultId:r,executionId:n,testId:o}=this;N("WorkerExtension runTestOnce");let i=async d=>{let m=this.options.timeoutWasGiven?Math.max(1e4,this.options.timeout):this.options.testStartTimeout;try{return await ce(e.runTestUsingCDP(d.cdpTestRunner),m,Fe.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof oe))throw u;return pt.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let g=await d.url(m);return u.driverUrlFinished=!0,g}catch(g){throw pt.error("error from driver.url",{err:g,testResultId:r,executionId:n,testId:o,url:m,urlLength:m.length}),g}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var g;if(N("WorkerExtension runExtTest"),((g=this.options.lightweightMode)==null?void 0:g.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){ee.onWaitToTestStart(this.id),ee.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw pt.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();ee.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Fe.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof oe))throw T;pt.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}ee.onWaitToTestComplete(this.id);let f=new AbortController,y=T=>{e.onCompletedCleanup(),pt.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),T.type=Ws.BROWSER_CLOSED,f.abort(T)};m.registerToClosedBrowser(y);try{let T=ce(e.onCompleted(),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG),I=await fc(T,f.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(I.success),I.reason)}catch(E){pt.error("Could not update the grid about the test status",{err:E})}m.isAlive()||(pt.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(pt.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.keepAliveIssue=b),{...I,...e.seleniumPerfStats.getStats()}}catch(T){throw pt.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:o}),Qb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw pt.warn("failed to start url",{err:h}),Qb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),N("WorkerExtension super.runTestOnce"),await c()}catch(d){throw pt.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Wp={};H(Wp,{WorkerExtensionSingleBrowser:()=>$p});var DI,MI,$p,Vp=w(()=>{"use strict";We();B();$();ap();_t();Fa();DI=C("base-worker"),MI=500,$p=class extends Jn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Fn(this.id,this.releaseSlotOnTestFinished,t,this.options.company.companyId,this.options.slotService,this.testPlayer),this.testPlayer=null}onQueueCompleted(){return this._releasePlayer()}async getBrowserOnce(t,r,n,o){return ee.onGetSession(this.id,`worker ${this.id}`,t.runMode),this._getBrowserOnce(t,r,n,o)}async getTestPlayer(t,r){return this.testPlayer&&!this.testPlayer.driver.isAlive()&&(DI.warn("WorkerExtensionSingleBrowser is releasing a dead player",{workerId:this.id}),await this._releasePlayer()),this.testPlayer||(this.testPlayer=await super.getTestPlayer(t,r)),this.testPlayer}async runTest(t,r,n){let o=this.handleQuarantine(t);if(o)return o;N("before runTest onTestStarted single browser");let i=await this.onTestStarted(this.id,t.testId,t.testResultId,n,t.retryKey);t.baseUrl=i.config.baseUrl;let a=await this.getTestPlayer(t,r);return t.markClearBrowser(),await this.runTestOnce(t,a)}async runTestCleanup(){var t;if(!this.executionQueue.hasMoreTests()){await this.onQueueCompleted();return}(t=this.options.lightweightMode)!=null&&t.general&&await ae(MI)}}});var Gp,Ba,Zb=w(()=>{"use strict";Dn();pe();We();Nu();it();Yu();K();$();ne();Jh();ei();Gp=C("worker-manager"),Ba=class{constructor(e){this.customExtensionLocalLocation=e;this.workerIdCount=0;this.parallelCount=0;this.workers=new Map;this.combinedTestResults={};this.workerUniqueIds=[];this.onWorkerFinished=async(e,...t)=>{this.workers.has(e)&&(this.workers.delete(e),this.executionQueue.hasMoreTests()&&this.workers.size<this.parallelCount&&this.runWorker(...t))};this.runWorker=async(...e)=>{let t=++this.workerIdCount;this.workers.set(t,null);let r=this.executionQueue.getNext();if(!r){this.workers.delete(t);return}let n=this.workerUniqueIds[t%this.parallelCount],o=await this.createWorker(r.runConfig.browserValue,...e);this.workers.set(t,o),o.id=t,o.uniqueId=n,o.run(r,this.onWorkerFinished,...e)}}async getWorkerType({mode:e,localTmaUrl:t},r){if(e)switch(e){case q.SELENIUM:return(await Promise.resolve().then(()=>(Pp(),Cp))).WorkerSelenium;case q.APPIUM:return t?(await Promise.resolve().then(()=>(Gb(),Vb))).WorkerLocalTma:(await Promise.resolve().then(()=>(zb(),qb))).WorkerAppium;default:return Mn.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(await Promise.resolve().then(()=>(Vp(),Wp))).WorkerExtensionSingleBrowser:(await Promise.resolve().then(()=>(Fa(),jp))).WorkerExtension}else switch(r){case(vr.find(n=>n===r)&&Mn.isFeatureAvailableForProject("useSameBrowserForMultiTests")):return(await Promise.resolve().then(()=>(Vp(),Wp))).WorkerExtensionSingleBrowser;case vr.find(n=>n===r):return(await Promise.resolve().then(()=>(Fa(),jp))).WorkerExtension;case hn.find(n=>n===r):return(await Promise.resolve().then(()=>(Pp(),Cp))).WorkerSelenium;default:throw new P(`browser ${r} is not supported`)}}async createWorker(e,...t){let r=t[0],n=await this.getWorkerType({mode:r.mode,localTmaUrl:r.localTmaUrl},e);try{return N("before new Worker",r.mode),new n(this.executionQueue,...t)}finally{N("after new Worker",r.mode)}}async runTests(e,t,r,n,o,i,a,l){if(e&&e.length===0)return;let c=!1,d=0,m=(u,g)=>new Promise(h=>{var me,tt,St,Mr,k,M,j,z;let f=o.project,y=e.length;this.parallelCount=a,this.workerUniqueIds=this.generateUniqueIds(this.parallelCount),this.executionQueue=new Vi(r,n,e,o,i,t),this.combinedTestResults={};let T=((me=o.company)==null?void 0:me.ucid)||"",I=(tt=o.company)==null?void 0:tt.companyId,b=(St=o.company)==null?void 0:St.name,v=o.source||"cli",E=o.user,x=(Mr=o.company)==null?void 0:Mr.planType,D=(k=o.company)==null?void 0:k.isStartUp,F=(M=o.projectData)==null?void 0:M.name,R=(j=o.projectData)==null?void 0:j.type,A=o.lightweightMode,_=(z=o.gridData)==null?void 0:z.type,U=(Pe,Et,we,Ha,Xn,qa)=>(d++,_g({executionId:r,projectId:f,testId:Et,resultId:we,ucid:T,companyId:I,companyName:b,projectName:F,companyPlan:x,source:v,user:E,lightweightMode:A,isStartUp:D,projectType:R,appSource:qa,gridType:_}),t.testStartAndReport(Pe,r,we,Ha,Xn)),G=async(Pe,Et,we,Ha,Xn,qa)=>{var Qp,Zp,ed;d--;let rt={...(A==null?void 0:A.onlyTestIdsNoSuite)&&{show:!0},...we.seleniumStats&&{seleniumStats:we.seleniumStats},...we.gridIssues&&{gridIssues:we.gridIssues},...we.keepAliveIssue&&{keepAliveIssue:we.keepAliveIssue},...o.host&&{gridHost:o.host}};if(we.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(we.seleniumPerfMarks),delete we.seleniumPerfMarks),o.grid||o.gridId?(rt.gridName=o.grid||((Qp=o.gridData)==null?void 0:Qp.name),rt.gridType=(Zp=o.gridData)==null?void 0:Zp.type,rt.gridProvider=(ed=o.gridData)==null?void 0:ed.provider):o.localTmaUrl?(rt.gridName="local-tma-from-options",rt.gridType="local-tma"):o.useLocalChromeDriver?(rt.gridName="local-chrome-driver-from-options",rt.gridType="local-chrome"):o.useChromeLauncher?(rt.gridName="chrome-launcher-from-options",rt.gridType="local-chrome"):o.browserstack?rt.gridName="browserstack-from-options":o.saucelabs&&(rt.gridName="saucelabs-from-options"),await t.testEndAndReport(Pe,we,r,Ha,Xn,rt).catch(CT=>Gp.error("testEndAndReport threw an error",{err:CT})),Xn)return;this.combinedTestResults[we.resultId]=we,Og({executionId:r,projectId:f,testId:Et,resultId:we.resultId,result:we,ucid:T,companyId:I,companyName:b,projectName:F,companyPlan:x,source:v,user:E,lightweightMode:A,logger:Gp,isStartUp:D,projectType:R,appSource:qa}),l&&!we.success&&(this.executionQueue.stop(),c=!0),(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},Y=(Pe,Et)=>{this.combinedTestResults[Et.resultId]=Et,t.onTestIgnored(Pe,Et.resultId),d--,(Object.keys(this.combinedTestResults).length===y||c&&d===0)&&h(this.combinedTestResults)},X=(Pe,Et)=>t.onGridSlot(Pe,Et);for(o.userData={loginData:{...br(),refreshToken:jo(),authData:br(),token:u,userAccessKey:g},projectId:o.project,company:o.company,servicesUrl:fe},N("in localStrategy before createWorker");this.workers.size<this.parallelCount&&this.executionQueue.hasMoreTests();)this.runWorker(o,this.customExtensionLocalLocation,r,U,G,X,Y)});try{let u=await Ct(),g=await $o(),h=await m(u,g);if(this.workers.size>0&&this.workers.clear(),c)throw new qt;return h}catch(u){throw Gp.error("failed running parallel workers",{executionId:r,err:u}),u}}generateUniqueIds(e){return Array.from({length:e},(t,r)=>`worker-${r+1}`)}}});var Yn,ja,Hp,$a,eT=w(()=>{"use strict";Yn=S(require("lodash"));B();$();pe();ne();We();ns();Tu();Nu();he();_t();Zg();K();Zb();ei();({CLI_MODE:ja}=Ut),Hp=C("test-plan-runner"),$a=class{constructor(e){this.customExtensionLocalLocation=e;this.startTime=Date.now()}async runTestAllPhases(e,t,r,n,o,i,a,l){let c={},d=new Ba(this.customExtensionLocalLocation),m=async()=>{let f=o.beforeParallel||1,y=!0,T=await d.runTests(e,l,i,a,o,n,f,y);Object.assign(c,T)},u=async()=>{let f=lo||o.parallel,y=!1;N("right before this.workerManager.runTests");let T=await d.runTests(t,l,i,a,o,n,f,y);N("right after this.workerManager.runTests"),Object.assign(c,T)},g=async()=>{let f=o.afterParallel||1,y=!1,T=await d.runTests(r,l,i,a,o,n,f,y);Object.assign(c,T)};Lg({executionId:i,projectId:o.project}),N("right before runBeforeTests");try{return await m(),N("right before runTestPlanTests"),await u(),N("right after runTestPlanTests"),await g(),c}catch(f){if(Hp.error("error running test plan",{err:f}),f instanceof qt)return l.markAllQueuedTests(i,de.ABORTED,"aborted",!1);throw f}finally{await h()}async function h(){var y,T,I,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===ja.SELENIUM){let[{getSessionPlayer:v},{makeSDK:E}]=await Promise.all([Promise.resolve().then(()=>(Te(),Zt)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:x}=v();await x.closeBatch(i,E);return}let f;try{if(!((b=(I=(T=o.company)==null?void 0:T.activePlan)==null?void 0:I.premiumFeatures)!=null&&b.applitools)||(f=await Cl(o.project),Yn.default.isEmpty(f)||!i))return;let{runKey:v,url:E}=f;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:E,apiKey:v}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,l){var b,v,E;let c=se(),d=n.project;lc(c),e.forEach(x=>Object.assign(x,{isBeforeTestPlan:!0})),r.forEach(x=>Object.assign(x,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Li(m,n,i,a),g=Yn.default.chain(m).map(x=>{var D;return((D=x.overrideTestConfig)==null?void 0:D.name)||""}).uniq().compact().value(),h=(g==null?void 0:g.length)===1?g[0]:null,f=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(x=>x.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,o,f);N("before testListInfoPromise");let T=await y;(E=n.lightweightMode)!=null&&E.onlyTestIdsNoSuite||ee.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,o,c,l,h),N("before runTestAllPhases");let I=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,o||"All Tests",u);return N("before executionEnd"),await u.executionEnd(c),N("after executionEnd"),{results:I,executionId:c,testPlanName:o,configName:h}}async runTestPlans(e,t){Hp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Yn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await pl(i,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==ja.APPIUM&&await Yl(e,r(c)),await ie(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await ug(e,d);let g=u.overrideExecutionName||d.name;return await ie(c[m],async f=>{let y=await this.runTestPlan(f.beforeTests,f.tests,f.afterTests,u,g,m,t);ee.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(E=>({executionId:E,status:Jl(n[m][E])})),I=Object.keys(n[m]).map(E=>n[m][E]).reduce((E,x)=>Object.assign(E,x),{}),b=Jl(I);Object.assign(o,I);let v=b?T[0].executionId:T.find(E=>!E.status).executionId;return await cl(i,m,{success:b,executions:T,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var l;Hp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),N("before getSuite");let r=await Tf(e,t);if(N("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;N("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode===ja.APPIUM&&(a=await un({appId:e.appId,projectId:e.project})),await ie(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==ja.APPIUM&&await Yl(e,c),N("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,o,null,t,i);return N("right after runTestPlan"),await ee.onTestPlanFinished(d.results,o,this.startTime,d.executionId,i),d})}async run(e){let t=An(),r=[];Gs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Yn.default.flattenDeep(r);return N("right before onAllTestPlansFinished"),await ee.onAllTestPlansFinished(n),N("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var nT={};H(nT,{init:()=>nR,run:()=>ZI});async function NI(s){let e=s.project,t=await ml(e);if(t!=null&&t.isExecutionBlocked)throw console.error("You have reached the limit of runs for the billing month, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli"),fn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ds}function UI(s,e){var i,a,l,c,d,m,u,g;let t=Eo(e.activePlan),r=s.parallel;if(t==="free"&&r>rT)throw new P(`The free plan allows only ${rT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let h=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!h)throw new P("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let f=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.runInTurboMode;s.lightweightMode&&!f&&(console.warn(`
409
409
  Turbo mode is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Turbo mode disabled for this run.`),s.lightweightMode=void 0)}if(e.tvcLicense&&((d=s.gridData)==null?void 0:d.type)===O.TESTIM_TVC){let h=e.tvcLicense.expireAt||1;if(Date.now()>h&&!e.churnedByL2C)throw new P("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let f=Number(e.tvcLicense.maxParallel);if(r>f)throw new P(`Your license allows only ${f} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}if(e.tdcLicense&&((m=s.gridData)==null?void 0:m.type)===O.TESTIM_TDC){let h=e.tdcLicense.expireAt||1;if(Date.now()>h)throw new P("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted")}let n=s.retentionDays;if(!n)return;let o=(g=(u=e.activePlan)==null?void 0:u.premiumFeatures)==null?void 0:g.resultRetention;if(n>o)throw new P(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function FI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await NI(s)}catch(t){if([P,Ds].some(r=>t instanceof r))throw t;qp.error("could not validate cli account",{err:t})}}function BI(s){let e=br();return df({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function jI(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(L.flags.useNewWSCLI.isEnabled()&&!e&&!t)return Tt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(ji(),Bh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>($i(),Wh));r.init(s)}}function $I(s,e){let{branch:t,autoDetect:r}=s;if(bg(e,r),!e&&!r)throw new P(`branch ${t} does not exist, run aborted.`)}async function WI(s,e){let{id:t,type:r}=e,o=sT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&L.flags.sfdcHybridCompany.isEnabled(),i=An();o&&(s.sfdcCredential=await il({projectId:t,branch:i}))}function VI(s,e){let{id:t,name:r,activePlan:n={}}=e,o=Boolean(n.isPoc),i=Boolean(n.isStartUp),a=Eo(n);a==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<tT?tT:s.newBrowserWaitTimeout),L.setCompanyId(t),L.setIsPOC(o),L.setIsStartUp(i),L.setPlanType(a),kt.setPlanType(a),s.company={ucid:"",companyId:t,name:r,planType:a,isPOC:o,isStartUp:i,activePlan:n}}function GI(s,e){s.editorUrl=_s||e.editorUrl}function HI(s,e){s.allGrids=e}function qI(s,e){s.authData=e}function zI(s,e){let{id:t,name:r,type:n,defaults:o}=e;L.setProjectId(t),L.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:o}}async function KI(s){var e;s.gridData=await pg(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}function JI(s,e){s.mode=["android","ios"].includes(e.type||"")?"appium":s.mode}function YI(s,e){s.getBrowserRetries=["android","ios"].includes(e.type||"")?1:s.getBrowserRetries}async function XI(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(yt("user-override-file",t),s.mockNetworkRules=await Zm(s.overrideMappingFile))}async function QI(s,e){N("in runner.js runRunner");let{project:t,remoteRunId:r,useLocalChromeDriver:n,useChromeLauncher:o}=s;r||(s.source=n||o?"cli-local":"cli"),await jf(),N("in runner.js after checkNpmVersion"),await FI(s),N("in runRunner before tunnel.connect"),await mi(s),N("in runRunner after tunnel.connect");let a=await new $a(e).run(s);return N("before tunnel.disconnect"),await fi(s),await rR(s.slotService,t,s.company.companyId),N("after tunnel.disconnect and gridService.keepAlive.end"),a}function eR(s){var e;kt.shouldShowFreeGridRunWarning((e=s.gridData)==null?void 0:e.type)&&console.log(`
410
410
  \x1B[4m\x1B[36mOur Free grid offers basic service performance.
411
411
  If you need faster results, contact us to upgrade your plan and dramatically improve your tests\u2019 run times.\x1B[0m