@testim/testim-cli 4.65.0 → 4.66.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. ${ic()?"(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 Zi.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",f=n?n.message:"";if(f===d||f.startsWith(m)||f.startsWith(o)||f.startsWith(i)||f.startsWith(a)||f.includes(u)||f.includes(l)||f.includes(c)){await this.forceInputToBeVisible(r),await this.uploadFiles(t,r);return}throw Zi.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(Le(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=M.flags.overrideAzureStorageUrl.isEnabled(),n=M.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:o,context:i,step:a,stepActionUtils:l,driver:c}=this,d=await o.utils.addTokenToFileUrl(i.project.id,a.fileUrls,l.testimServicesApi,r,Zi);if(d.length===0)throw new Error("No files urls to upload");if(n&&(d=await Promise.all(d.map(async({name:u,url:f})=>{let g=await Nt(f);return{name:u,url:`data:${g.type};base64,${Buffer.from(g.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 = ${ZS()};
408
- return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Oy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ta,ra,Dy=T(()=>{"use strict";ta=require("url");ue();ra=class extends W{async updateBaseUrl(e){let t=new ta.URL(e),r=new ta.URL(this.context.recordedBaseUrl),n=new ta.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 sa,My=T(()=>{"use strict";ue();B();sa=class extends W{async performAction(){await oe(this.step.durationMS||0)}}});var na,Ny=T(()=>{"use strict";ue();na=class extends W{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Un,Uy=T(()=>{"use strict";ue();Un=class extends W{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,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 oa,Fy=T(()=>{"use strict";ue();oa=class extends W{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 By,rp,sp,jy=T(()=>{"use strict";By=v(require("@applitools/spec-driver-webdriverio"));Xn();Te();rp=class{constructor(){let{EyeSdkBuilder:e}=se(),t=Vp["@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:By.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=se(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},sp=new rp});var Wy,$y,Fn,Vy=T(()=>{"use strict";Wy=v(require("lodash"));ue();j();jy();$y=x("pixel-validation-step-action"),Fn=class extends W{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 f=await l.openEyes({driver:this.driver.client,config:r,logger:n}),h={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};Wy.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),$y.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await f.check({settings:h}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){$y.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await sp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Is,np=T(()=>{"use strict";kr();q();qi();Is=class extends lr{async executeCliCode(){var g,h,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(h=(g=t.company)==null?void 0:g.activePlan)==null?void 0:h.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,f=await hs(o,i,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ne?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ur,Gy=T(()=>{"use strict";np();ur=class extends Is{isFailedResult(e){return e===!1}}});var ia,Hy=T(()=>{"use strict";np();ia=class extends Is{isFailedResult(e){return!e}}});var aa,qy=T(()=>{"use strict";kr();ue();q();aa=class extends W{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await gs(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 ne?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Dr,zy=T(()=>{"use strict";ue();Dr=class extends W{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ve,Ky=T(()=>{"use strict";ue();ve=class extends W{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 ca,Jy=T(()=>{"use strict";ue();ca=class extends W{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 la,Yy=T(()=>{"use strict";ue();la=class extends W{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 eI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function ua(s,e){eI(tI,e),e.registerLocateStepActionUtils(Dn.getUtils(s))}var tI,op=T(()=>{"use strict";zh();Yh();oy();iy();cy();py();fy();gy();hy();Ty();wy();vy();Iy();Ay();Ly();Dy();My();Ny();Uy();Fy();Vy();Gy();Hy();qy();zy();Ky();Jy();Yy();tI={locate:Dn,scroll:$i,mouse:Wi,submit:Ji,text:Gi,"special-key":zi,"user-code":qt,"validation-code-step":qt,"wait-for-code-step":qt,"action-code-step":qt,"condition-step":Ss,"skip-code-step":Ss,"element-code-step":Ss,"evaluate-expression":Vi,"text-validation":Nn,"wait-for-text-validation":Nn,"select-option":Ki,"drop-file":Qi,"input-file":ea,hover:Yi,navigation:ra,wheel:Xi,sleep:sa,refresh:na,"api-validation":Un,"api-action":Un,"api-code-step":qt,"extract-text":oa,"simple-ui-verification":Fn,"wait-for-simple-ui-verification":Fn,"cli-validation-download-file":Dr,"cli-wait-for-download-file":Dr,"network-validation-step":Dr,"cli-validation-code-step":ur,"cli-wait-for-code-step":ur,"cli-action-code-step":ur,"cli-api-code-step":ur,"cli-condition-step":ia,"node-package":aa,"email-code-step":qt,"cli-email-code-step":ur,"sfdc-internal-test-step":la,"sfdc-recorded-step":ca,"sfdc-step-login":ve,"sfdc-step-loginas":ve,"sfdc-step-logout":ve,"sfdc-step-sobjectcreate":ve,"sfdc-step-sobjectdelete":ve,"sfdc-step-findrecord":ve,"sfdc-step-quickaction":ve,"sfdc-step-sobjectedit":ve,"sfdc-step-sobjectvalidate":ve,"sfdc-step-launchapp":ve,"sfdc-step-wait-for-page-load":ve,"sfdc-step-closeconsoletabs":ve,"sfdc-step-relatedlistaction":ve,"sfdc-step-permission-validation":ve,"sfdc-step-convert-lead-to-opportunity":ve,"sfdc-step-quotelineeditor":ve,"sfdc-document-validation":Dr}});var Xy,rI,Rs,ip=T(()=>{"use strict";Xy=["simple-ui-verification","wait-for-simple-ui-verification"],rI=[...Xy,"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"],Rs=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=rI.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 Xy.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 Zy={};V(Zy,{SeleniumTestPlayer:()=>Bn});var Qy,Bn,ap=T(()=>{"use strict";B();Qy=require("@applitools/eyes-sdk-core");Pn();q();Ju();$h();Zu();Wh();Hh();ep();Te();op();ip();Bn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new Rs(ji());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=se();this.driver=n??new Pr;let d=new Bi(this.driver);this.stepActionFactory=new c(d),ua(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ui(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=Gh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new vs(this.driver),FrameLocator:m,portSelector:Fi,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Qy.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}=se(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof ne&&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 n=(await this.driver.getTabIds()).at(-1);return await this.tabService.addNewTab(this.id,n,e,t),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 eb={};V(eb,{WorkerSelenium:()=>cp});function nI(s){let{playback:e}=se().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>N(`Got event ${t}`))}var pa,sI,cp,tb=T(()=>{"use strict";B();$e();Ln();j();Ot();qo();ae();zu();q();ap();Te();pa=x("worker-selenium"),sI=1e9,cp=class extends at{initPlayer(t){return new Bn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){N("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ws(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}),N("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),N("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,sI),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`):(pa.error("failed to navigate to page",{baseUrl:l,err:c}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=se(),{driver:i,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),nI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,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 fn(this.options))[this.testId]);let d=async()=>ce(new Promise((u,f)=>{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(f)}),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ne&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await o.drain(),u.stepsResults=null,u.resultId=this.testResultId,i.isAlive()||(pa.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=i.maxKeepAliveGap();f>=3e4&&(pa.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let h={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h});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 pa.error("failed to run test once",{err:u}),u}}}});var rb,He,oI,iI,lp,vt,da=T(()=>{"use strict";j();ae();le();ye();Ke();rb=v(require("ora")),He=x("mobile-grid-service"),oI="https://tdc.tricentis-cloud.com",iI="https://ui.headspin.io",lp=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)?`${t}/lock`:""}getBaseApiUrl(e){return e===O.TESTIM_HEADSPIN?`${ad}/devices`:e===O.TESTIM_TDC?`${ld}/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.type),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await Ge({url:r,headers:n,body:o})}catch(i){throw He.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.type)}/device_id:${t}/automation-config`;try{let o=await Ee(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw He.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t){let r=await Vs(`${ja}/access`,void 0,{Authorization:`Basic ${Buffer.from(`${e}:${t}`).toString("base64")}`});return JSON.parse(r).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){if(this.isTdcOrHeadSpinGrid(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`};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;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let c=await gl({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=c==null?void 0:c[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return(l=e.mobile)==null?void 0:l.version.split("-")[0];if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let c=e.pCloudy_DeviceFullName.split("_");return`${c[0]} ${c[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r){var E;let{executionId:n,testId:o,testResultId:i}=e,{project:a,projectData:{type:l}={},company:{companyId:c=""}={},gridData:{gridId:d="",type:m=""}={}}=r,u=t.capabilities,f=await this.getDeviceNameFromSessionCaps({capabilities:u,gridType:m,projectId:a,projectType:l,companyId:c,gridId:d}),g=u.platformVersion;!g&&m===O.BROWSERSTACK&&(g=(E=u.mobile)==null?void 0:E.version.split("-")[1]),!g&&m===O.TESTIM_TVC&&(g=u.os_version);let h={name:f??"",model:u.deviceModel,osVersion:g,udid:u.udid,osType:u.platformName,scaleFactor:u.pixelRatio,isVirtual:m===O.TESTIM_TVC,...m===O.TESTIM_TVC&&{model:u.deviceModel||t.capabilities.device,height:t.capabilities.screen.height,width:t.capabilities.screen.width,scaleFactor:t.capabilities.screen.scale}},y=await this.buildRemoteResultLink(r.gridData,t.sessionId,u);return await Er(a,n,o,i,"RUNNING",{device:h,...y&&{remoteResultLink:y}}),He.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:h,remoteResultLink:y,gridType:m}),h}async buildRemoteResultLink(e,t,r){return e.type===O.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ns}/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?iI:oI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let t=await Ee(`${fd}/devices`),r=t==null?void 0:t.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,resolution:`${r.width}x${r.height}`,geo:"local",manufacturer:r.model,osVersion:r.osVersion,type:r.deviceType||"",osType:r.osType,isLandscape:r.screenMirror.orientation==="LANDSCAPE",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 Er(l,n,o,i,"RUNNING",{device:a}),He.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getMobileAppDataByAppId({appId:e,projectId:t,token:r,executionId:n,testResultId:o}){try{let i=await Kc({appId:e,projectId:t});if(!i)throw He.error("mobile app not found",{appId:e,projectId:t,executionId:n,testResultId:o}),new Error("mobile app not found");return{appUrl:`${me}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}catch(i){throw He.error("error while getting app details",{error:i,appId:e,projectId:t,executionId:n,testResultId:o}),i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(id*60))+1)*60*1e3,Math.max(od,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let i={[O.BROWSERSTACK]:{name:"Browserstack",appPath:"browserStackAppId"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid",appPath:"testimTvcAppId"},[O.P_CLOUDY]:{name:"pCloudy",appPath:"pCloudyAppId"}},a=i[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,rb.default)(`uploading app to ${a} please wait..`).start();try{He.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await hl({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});c.succeed(`app uploaded successfully to ${a}`);let m=i[o].appPath;return d[m]}catch(d){throw c.fail(`failed to upload app to ${a}`),He.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&&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:f="",host:g=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:i});let I=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d,executionId:i,testResultId:a});n=I.appUrl,o=I.mobileApp,e.nativeApp=o}else He.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,y=this.gridsAppIdGetter[f]({testRunHandler:e,mobileApp:o,gridHost:g}),E=f===O.BROWSERSTACK||f===O.TESTIM_TVC||f===O.P_CLOUDY;if(y){let I=t.projectData.type,b=await this.verifyAppStillExistsOnGrid({gridAppId:y,gridData:m,projectType:I});b&&(He.info("app exists on grid, using gridAppId",{gridAppId:y,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=y),!b&&E&&(He.info("app not exists on grid, uploading it",{gridAppId:y,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!b&&!E&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:i})}return!y&&E&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var c,d;let{accessToken:n,user:o,host:i,key:a,type:l}=t;if(l===O.BROWSERSTACK){let m=`${Ns}/recent_apps`;return(await this.fetchWithUserAndPasswordAuth({url:m,user:o,key:a})).some(f=>f.app_url===e)}if(l===O.SAUCELABS){let u=`${i.includes("eu-central-1")?md:dd}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a})).items.some(g=>g.id===e)}if(l===O.TESTIM_HEADSPIN||l===O.TESTIM_TDC){let m=l===O.TESTIM_HEADSPIN?`${cd}/apps`:`${ud}/apps`;return(await this.fetchWithTokenAuth({url:m,accessToken:n,authType:"Bearer"})).apps.some(f=>f.app_id===e)}if(l===O.TESTIM_TVC){let m=`${pd}/versions/${e}/info`,u=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:m,accessToken:u,authType:"Upload-Token"}),!0}catch(f){return f.status!==404&&He.error("error while verifying app exists on TVC",{error:f}),!1}}if(l===O.P_CLOUDY){let m=await this.getPCloudyAuthToken(o,a),u=`${ja}/drive`,f=await rc({url:u,body:{token:m,filter:"all"},headers:{contentType:null}});return(d=(c=JSON.parse(f).result)==null?void 0:c.files)==null?void 0:d.some(h=>h.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 Ee(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await Ee(e,void 0,n)}},vt=new lp});function up({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"&&!aI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function cI({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 lI(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 uI(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&&M.flags.enableBatchHeadSpin.isEnabled(),d=i&&(M.flags.enableBatchTDC.isEnabled()||M.flags.headSpinTdcEnableFlagCapability.isEnabled());return{[`${l}:capture`]:!0,...M.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...o&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:lI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n}}}function ma(s){return"id"in s?s.id:s.packageName}function pI(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function dI({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=pI(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":ma(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":ma(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function fa({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:o=""}){switch(s){case"ios":return{...e,platformName:"iOS",[`${o}autoAcceptAlerts`]:!0,[`${o}automationName`]:"XCUITest",[`${o}fullReset`]:!0,...t&&{[`${o}bundleId`]:ma(t)},...r&&{[`${o}app`]:r}};case"android":return{...e,platformName:"Android",[`${o}autoGrantPermissions`]:!0,[`${o}automationName`]:"UiAutomator2",...n&&{[`${o}appWaitActivity`]:n},...t&&{[`${o}appPackage`]:ma(t),[`${o}appActivity`]:t.activity??".*"},...r&&{[`${o}app`]:r}};default:throw Error(`unsupported mobile project ${s}`)}}function nb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=uI(i.type,o,n);return dI({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function pp({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 dp({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?$a:o.deviceNameRegex:t==="ios"&&r===O.BROWSERSTACK?"iPhone.*":i?t==="ios"?"apple":$a:".*")}function mI(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 fI({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=mI(o,s),f=pp({osVersion:l,mobileConfig:d}),g=dp({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=qe(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y={device:g,os_version:f,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":h,"waldo:options":{token:u}};return fa({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function gI({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:f}=o,g=pp({osVersion:l,mobileConfig:d}),h=dp({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),y=/^[a-zA-Z]+$/.test(h),E={...g!==".*"&&{pCloudy_DeviceVersion:g},...y&&{pCloudy_DeviceManufacturer:h},...!y&&{pCloudy_DeviceFullName:h}},I={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...E,pCloudy_DurationInMinutes:n.duration?Number(n.duration):gd,pCloudy_ApplicationName:t,newCommandTimeout:120,fullReset:!0};return t="",fa({projectType:s,sessionCaps:I,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function hI(s,e){let t=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]\.\*\)\.\*$/,r=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]\.\*\)\.\*$/,n=e==="android"&&t.test(s),o=e==="ios"&&r.test(s);return n||o}function yI({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=m===O.BROWSERSTACK?"browserstack":"saucelabs",f=pp({osVersion:l,mobileConfig:d}),g=dp({deviceName:c,mobileConfig:d,projectType:s,gridType:m});if(hI(f,s)&&m===O.SAUCELABS){let y={appiumVersion:"latest",user:o.user,key:o.key,debug:!0,networkLogs:!0,tags:Object.values(i),name:i.testResultId,build:i.executionId};return fa({projectType:s,sessionCaps:{"appium:platformVersion":f,"appium:deviceName":g,"sauce:options":y},appiumPrefix:"appium:",nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let h={...m===O.BROWSERSTACK&&{os_version:f,device:g,realDevice:!0,project:i.project,buildTags:Object.values(i).join(",")},...m===O.SAUCELABS&&{platformVersion:f,deviceName:g,tags:Object.values(i)},name:i.testResultId,build:i.executionId,[`${u}.user`]:o.user,[`${u}.key`]:o.key,[`${u}.debug`]:!0,[`${u}.networkLogs`]:!0};return fa({projectType:s,sessionCaps:h,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function ob(s){return O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type?nb(s):O.TESTIM_TVC===s.gridInfo.type?fI(s):O.P_CLOUDY===s.gridInfo.type?gI(s):yI(s)}function bI(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 ib(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}`);up({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=ob(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let d=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",m=bI(r,o==null?void 0:o.mobile);if(!(0,sb.isEmpty)(m)){let u=Object.entries(m).map(([f,g])=>g.split(",").map(h=>h===".*"||h==="="?"":`${f}:${h}`).join(",")).join(" ").trim();l[`${d}:selector`]=u}}let c=e.type===O.TESTIM_TVC?{alwaysMatch:l}:l;return{...a,desiredCapabilities:l,capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function ab(s){var g,h;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;up({nativeAppMetadata:r,appPath:o,gridInfo:t}),cI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((h=(g=l.mobile)==null?void 0:g.staticAllocation)==null?void 0:h.deviceUdid),m=await vt.getGridDirectConnection(t,d),f=nb({projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function cb(s){return up(s),ob(s)}function lb(s){var t,r;let e=Object.assign({},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 sb,aI,mp=T(()=>{"use strict";fe();ae();da();sb=require("lodash");B();le();aI=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var ga,pb=T(()=>{"use strict";ga=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 ha,db=T(()=>{"use strict";ha=class{constructor(e){this.driver=e;this._abortedSteps=[]}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 fp,ya,mb=T(()=>{"use strict";j();fp=x("mobile-frame-locator-mock"),ya=class{foundFrameCallback(){return fp.info("foundFrameCallback-mock invoked"),{}}locate(){return fp.info("locate-mock invoked"),{}}async findFrame(){return fp.info("findFrame-mock invoked"),{}}}});var TI,gb,fb,xs,gp=T(()=>{"use strict";TI=v(require("webdriverio")),gb=require("@applitools/eyes-sdk-core");pb();Zu();j();db();ep();Te();op();mb();ip();fb=x("appium-test-player"),xs=class{constructor(e,t,r,n=TI,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=se(),m=new ha(this.driver);this.stepActionFactory=new c(m),ua(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Rs(ji()),this.sessionPlayer=new a(e,{tabService:new ga,cookieUtils:void 0,FrameLocator:ya,portSelector:Fi,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:gb.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{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}=se();e.off(i.playback.RESULT),this.sessionPlayer=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function wI(s){return await Ee(`${s}/api/status`)}async function hb(s,e){return await Ee(`${s}/api/devices/${e}/status`)}async function yb(s){if((await wI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var bb=T(()=>{"use strict";Ke()});var Tb={};V(Tb,{WorkerLocalTma:()=>Tp});var ba,hp,yp,bp,Tp,wb=T(()=>{"use strict";Ke();mp();Ln();B();j();Ot();gp();Te();bb();da();ba=x("worker-appium"),hp=class extends Error{},yp=class extends Error{},bp=class extends Error{},Tp=class extends at{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new xs(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}=se(),{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 R;if(Q.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 yb(i);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{executionId:k,testResultId:_}=t,{mobileApp:$}=await vt.getMobileAppDataByAppId({appId:f,projectId:c,token:d,executionId:k,testResultId:_});t.nativeApp=$}let g=u==="android"?t.androidActivityWait:null,h=t.nativeAppMetadata,y=t.downloadableAppPublicLink,E=t.appPackageNameOrBundleId;if(!h)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!E)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},w]=await Promise.all([this.getAppStateFromDevice(i,a,E),hb(i,a)]).catch(k=>{throw this.handleDeviceNotFoundError(k),k});if(!I&&t.isAppFromDevice&&!f)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);try{let k={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(R=this.options.projectData)==null?void 0:R.name}-${this.options.project}`},_=cb({projectType:u,nativeAppMetadata:h,appPath:y,androidActivityWait:g,sessionTags:k,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),$={capabilities:{udid:a,..._}},S=await this.requestNewAppiumSessionFromTma(i,$,h);this.sessionData=S;let A=await m.attach({sessionId:S.sessionId,capabilities:_});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),ba.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:A.sessionId,testResultId:this.testResultId,nativeAppMetadata:h,sessionCaps:A.capabilities})}catch(k){throw ba.error("failed to start application",{err:k}),k}}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"}}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 bp(l):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,l=(await Ee(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 Ws(`${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 yp(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 hp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=se(),{sessionPlayer:i}=r,a=n||"runner";Q.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 ba.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw ba.error("failed to run test once",{err:c}),c}}}});var Eb={};V(Eb,{WorkerAppium:()=>wp});var vb,As,wp,Sb=T(()=>{"use strict";mp();vb=require("linkedom");Ln();j();Ot();gp();Te();da();ae();ls();As=x("worker-appium"),wp=class extends at{initPlayer(t){return new xs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){Q.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},u={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:m,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig},f;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await vt.lockDevice(o,this.options.deviceUdid),f=await ab(u)):f=ib(u),As.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:lb(f)}),this.activeSession=await i.remote(f),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,this.options);let g=`${this.getServerAddressFromGrid()}/session/${this.activeSession.sessionId}`;this.updateSlotData(g),As.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw As.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}updateSlotData(t){try{this.options.slotService==="redis"&&Yf(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){As.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.TESTIM_TVC?`https://${t}/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,f;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=se(),{sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let c;if(this.options.skipLoadBalancer){let g=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:h,hostname:y,port:E,path:I}=await vt.getHeadSpinDeviceConnection(this.options.gridData,g);c=`${h}://${y}:${E}${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:(f=this.options.company)==null?void 0:f.companyId,device:this.device},a.playbackManager.appiumApi=new o(c,this.activeSession.sessionId,vb.DOMParser),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let g=await new Promise((y,E)=>{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(E)});return await i.drain(),g.stepsResults=null,g.resultId=this.testResultId,{...g,...t.seleniumPerfStats.getStats()}}catch(g){throw As.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:g}),g}};try{return await super.runTestOnce(t,r),await m()}catch(g){throw As.error("failed to run test once",{err:g}),g}}}});var Ta,Ib=T(()=>{"use strict";B();Pn();q();Ta=class{constructor(e){this.id=e;this.driver=new Pr}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof ne&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Rb,wa,xb=T(()=>{"use strict";Rb=v(require("ws"));B();wa=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 Rb.default(this._cdpUrl,{timeout:e}),r=Yt(o=>{t.once("open",o)}),n=Yt(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 Ea,vp,va,Ab=T(()=>{"use strict";B();Ea=v(require("chrome-launcher"));xu();xb();un();vp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new wa}async init(e){var u,f,g,h;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l}=e,c=vi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l}),d=[...((u=c.desiredCapabilities)==null?void 0:u.chromeOptions.args)??[],...((h=(g=(f=c.capabilities)==null?void 0:f.alwaysMatch)==null?void 0:g["goog:chromeOptions"])==null?void 0:h.args)??[],...Ea.Launcher.defaultFlags().filter(y=>y!=="--disable-extensions")];this.chrome=await Ea.launch({chromeFlags:d,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 m=await br(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(m),rs(()=>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}},va=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new vp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Pb={};V(Pb,{WorkerExtension:()=>jn});function vI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Cb(s){return vI(s)?s:new Error(s)}var ct,jn,Ep=T(()=>{"use strict";$e();q();Ln();B();j();Ot();ae();Ib();Ab();ct=x("worker-ext"),jn=class extends at{initPlayer(){return this.options.useChromeLauncher?new va(this.id):new Ta(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})}catch(a){throw ct.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,r,n){return Q.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 ne))throw u;return ct.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw ct.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:o,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(N("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(g){throw ct.warn("failed to run test via CDP",{err:g}),g}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let g=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,g,u),l(u)]),this.options.testStartTimeout,Fe.TEST_START_TIMEOUT_MSG)}catch(E){if(!(E instanceof ne))throw E;ct.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let h=new AbortController,y=E=>{e.onCompletedCleanup(),ct.warn("on browser closed error detected",{err:E,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),E.type=Hs.BROWSER_CLOSED,h.abort(E)};m.registerToClosedBrowser(y);try{let E=ce(e.onCompleted(),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG),I=await Xa(E,h.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(I.success),I.reason)}catch(R){ct.error("Could not update the grid about the test status",{err:R})}m.isAlive()||(ct.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&&(ct.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.keepAliveIssue=b),{...I,...e.seleniumPerfStats.getStats()}}catch(E){throw ct.warn("timeout wait until test completed",{err:E,testResultId:r,executionId:n,testId:o}),Cb(E)}finally{m.unregisterToClosedBrowser(y)}}catch(g){throw ct.warn("failed to start url",{err:g}),Cb(g)}};t.driver.start();try{return await super.runTestOnce(e,t),N("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ct.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var kb={};V(kb,{WorkerExtensionSingleBrowser:()=>Sp});var EI,SI,Sp,Ob=T(()=>{"use strict";$e();B();j();Wu();Ot();Ep();EI=x("base-worker"),SI=500,Sp=class extends jn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await On(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 Q.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()&&(EI.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 oe(SI)}}});function II(s,e){e===0?s():setTimeout(s,e*Zp)}var Ip,Sa,_b=T(()=>{"use strict";Pn();le();$e();gu();Ct();Ou();q();j();ae();Ch();Ip=x("parallel-worker-manager"),Sa=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Y.SELENIUM:return(tb(),he(eb)).WorkerSelenium;case Y.APPIUM:return e.localTmaUrl?(wb(),he(Tb)).WorkerLocalTma:(Sb(),he(Eb)).WorkerAppium;default:return Si.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Ob(),he(kb)).WorkerExtensionSingleBrowser:(Ep(),he(Pb)).WorkerExtension}}createWorkers(e,t,...r){let n=r[0],o=this.getWorkerType(n),i=()=>{try{return N("before new Worker",n.mode),new o(t,...r)}finally{N("after new Worker",n.mode)}};return Array.from(new Array(e),i)}async runTests(e,t,r,n,o,i,a,l,c){if(e&&e.length===0)return;let d=!1,m=0,u=f=>new Promise(g=>{var lt,dr,P,D,F,z,ut,Pa;let h=o.project,y=new ki(r,n,e,o,i,t),E={},I=e.length,b=((lt=o.company)==null?void 0:lt.ucid)||"",w=(dr=o.company)==null?void 0:dr.companyId,R=(P=o.company)==null?void 0:P.name,k=o.source||"cli",_=o.user,$=(D=o.company)==null?void 0:D.planType,S=(F=o.company)==null?void 0:F.isStartUp,A=(z=o.projectData)==null?void 0:z.name,L=(ut=o.projectData)==null?void 0:ut.type,U=o.lightweightMode,J=(Pa=o.gridData)==null?void 0:Pa.type,H=(Lt,pt,be,ka,Wn,Oa)=>(m++,ug({executionId:r,projectId:h,testId:pt,resultId:be,ucid:b,companyId:w,companyName:R,projectName:A,companyPlan:$,source:k,user:_,lightweightMode:U,isStartUp:S,projectType:L,appSource:Oa,gridType:J}),t.testStartAndReport(Lt,r,be,ka,Wn)),X=async(Lt,pt,be,ka,Wn,Oa)=>{var Np,Up,Fp;m--;let et={...(U==null?void 0:U.onlyTestIdsNoSuite)&&{show:!0},...be.seleniumStats&&{seleniumStats:be.seleniumStats},...be.gridIssues&&{gridIssues:be.gridIssues},...be.keepAliveIssue&&{keepAliveIssue:be.keepAliveIssue},...o.host&&{gridHost:o.host}};if(be.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(be.seleniumPerfMarks),delete be.seleniumPerfMarks),o.grid||o.gridId?(et.gridName=o.grid||((Np=o.gridData)==null?void 0:Np.name),et.gridType=(Up=o.gridData)==null?void 0:Up.type,et.gridProvider=(Fp=o.gridData)==null?void 0:Fp.provider):o.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):o.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):o.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):o.browserstack?et.gridName="browserstack-from-options":o.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(Lt,be,r,ka,Wn,et).catch(RT=>Ip.error("testEndAndReport threw an error",{err:RT})),Wn)return;E[be.resultId]=be,pg({executionId:r,projectId:h,testId:pt,resultId:be.resultId,result:be,ucid:b,companyId:w,companyName:R,projectName:A,companyPlan:$,source:k,user:_,lightweightMode:U,logger:Ip,isStartUp:S,projectType:L,appSource:Oa}),c&&!be.success&&(y.stop(),d=!0),(Object.keys(E).length===I||d&&m===0)&&g(E)},de=(Lt,pt)=>{E[pt.resultId]=pt,t.onTestIgnored(Lt,pt.resultId),m--,(Object.keys(E).length===I||d&&m===0)&&g(E)},Et=(Lt,pt)=>t.onGridSlot(Lt,pt);o.userData={loginData:Object.assign({},jt(),{refreshToken:ko(),authData:jt(),token:f}),projectId:o.project,company:o.company,servicesUrl:me},N("in localStrategy before createWorker"),this.createWorkers(l,y,o,this.customExtensionLocalLocation,r,H,X,Et,de).forEach((Lt,pt)=>{N("before schedule worker.run after createWorkers"),II(()=>{N("right before worker.run"),Lt.run()},pt)})});try{let f=await Zt(),g=await u(f);if(d)throw new Kt;return g}catch(f){throw Ip.error("failed running parallel workers",{executionId:r,err:f}),f}}}});async function Db(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await zc({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function Rp(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function xp(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=Lb.difference(qs(s,e),t);if(r.length>0)throw ht("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Lb,Mb=T(()=>{"use strict";Lb=v(require("lodash"));B();ss();ye();q()});var $n,zL,Ap,Cp,Ia,Nb=T(()=>{"use strict";$n=v(require("lodash"));B();j();le();ae();$e();as();Ql();gu();ye();Ct();Ot();_g();q();_b();Mb();({testRunStatus:zL,CLI_MODE:Ap}=Ut),Cp=x("test-plan-runner"),Ia=class{constructor(e){this.startTime=Date.now();this.workerManager=new Sa(e)}async runTestAllPhases(e,t,r,n,o,i,a,l){let c={},d=jt(),m=async()=>{let h=o.beforeParallel||1,y=!0,E=await this.workerManager.runTests(e,l,i,a,o,n,d,h,y);Object.assign(c,E)},u=async()=>{let h=to||o.parallel,y=!1;N("right before this.workerManager.runTests");let E=await this.workerManager.runTests(t,l,i,a,o,n,d,h,y);N("right after this.workerManager.runTests"),Object.assign(c,E)},f=async()=>{let h=o.afterParallel||1,y=!1,E=await this.workerManager.runTests(r,l,i,a,o,n,d,h,y);Object.assign(c,E)};dg({executionId:i,projectId:o.project}),N("right before runBeforeTests");try{return await m(),N("right before runTestPlanTests"),await u(),N("right after runTestPlanTests"),await f(),c}catch(h){if(Cp.error("error running test plan",{err:h}),h instanceof Kt)return l.markAllQueuedTests(i,pe.ABORTED,"aborted",!1);throw h}finally{await g()}async function g(){var y,E,I,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===Ap.SELENIUM){let[{getSessionPlayer:w},{makeSDK:R}]=await Promise.all([Promise.resolve().then(()=>(Te(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:k}=w();await k.closeBatch(i,R);return}let h;try{if(!((b=(I=(E=o.company)==null?void 0:E.activePlan)==null?void 0:I.premiumFeatures)!=null&&b.applitools)||(h=await ul(o.project),$n.default.isEmpty(h)||!i))return;let{runKey:w,url:R}=h;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:R,apiKey:w}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,l){var b,w,R;let c=re(),d=n.project;qa(c),e.forEach(k=>Object.assign(k,{isBeforeTestPlan:!0})),r.forEach(k=>Object.assign(k,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new wi(m,n,i,a),f=$n.default.chain(m).map(k=>{var _;return((_=k.overrideTestConfig)==null?void 0:_.name)||""}).uniq().compact().value(),g=(f==null?void 0:f.length)===1?f[0]:null,h=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(k=>k.name),y=(w=n.lightweightMode)!=null&&w.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,o,h);N("before testListInfoPromise");let E=await y;(R=n.lightweightMode)!=null&&R.onlyTestIdsNoSuite||Q.onTestPlanStarted(E.beforeTests,E.tests,E.afterTests,o,c,l,g),N("before runTestAllPhases");let I=await this.runTestAllPhases(E.beforeTests,E.tests,E.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:g}}async runTestPlans(e,t){Cp.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function r(d){return $n.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await qc(i,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Ap.APPIUM&&await xp(e,r(c)),await ie(l,async d=>{var g;let m=d.testPlanId;n[m]={};let u=Object.assign({},e);u.baseUrl||=d.startUrl,u.appId||=((g=d.mobileApp)==null?void 0:g.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await Vf(e,d);let f=u.overrideExecutionName||d.name;return await ie(c[m],async h=>{let y=await this.runTestPlan(h.beforeTests,h.tests,h.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let E=Object.keys(n[m]).map(R=>({executionId:R,status:Rp(n[m][R])})),I=Object.keys(n[m]).map(R=>n[m][R]).reduce((R,k)=>Object.assign(R,k),{}),b=Rp(I);Object.assign(o,I);let w=b?E[0].executionId:E.find(R=>!R.status).executionId;return await Vc(i,m,{success:b,executions:E,executionId:w}),y})})}async runAnonymousTestPlan(e,t){var a;Cp.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),N("before getSuite");let r=await Db(e,t);if(N("after getSuite"),!((a=r==null?void 0:r.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new C("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new C("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new C("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;return N("Right before validateConfig + runAnonymousTestPlan tests map"),await ie(r.tests,async l=>{if(e.resultId){let d=l[0];d.resultId=e.resultId,l=[d]}e.mode!==Ap.APPIUM&&await xp(e,l),N("right before runTestPlan");let c=await this.runTestPlan([],l,[],e,o,null,t,i);return N("right after runTestPlan"),await Q.onTestPlanFinished(c.results,o,this.startTime,c.executionId,i),c})}async run(e){let t=vn(),r=[];zs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=$n.default.flattenDeep(r);return N("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),N("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var jb={};V(jb,{init:()=>HI,run:()=>jI});async function RI(s){let e=s.project,t=await Jc(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"),pn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Us}function xI(s,e){var i,a,l,c,d,m,u;let t=mo(e.activePlan),r=s.parallel;if(t==="free"&&r>Fb)throw new C(`The free plan allows only ${Fb} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let f=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!f)throw new C("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 g=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.runInTurboMode;s.lightweightMode&&!g&&(console.warn(`
408
+ return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Oy(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var ta,ra,Dy=T(()=>{"use strict";ta=require("url");ue();ra=class extends W{async updateBaseUrl(e){let t=new ta.URL(e),r=new ta.URL(this.context.recordedBaseUrl),n=new ta.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 sa,My=T(()=>{"use strict";ue();B();sa=class extends W{async performAction(){await oe(this.step.durationMS||0)}}});var na,Ny=T(()=>{"use strict";ue();na=class extends W{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var Un,Uy=T(()=>{"use strict";ue();Un=class extends W{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,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 oa,Fy=T(()=>{"use strict";ue();oa=class extends W{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 By,rp,sp,jy=T(()=>{"use strict";By=v(require("@applitools/spec-driver-webdriverio"));Xn();Te();rp=class{constructor(){let{EyeSdkBuilder:e}=se(),t=Vp["@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:By.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=se(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},sp=new rp});var Wy,$y,Fn,Vy=T(()=>{"use strict";Wy=v(require("lodash"));ue();j();jy();$y=x("pixel-validation-step-action"),Fn=class extends W{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 f=await l.openEyes({driver:this.driver.client,config:r,logger:n}),h={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};Wy.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(h,i.applitoolsStepSettings),$y.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await f.check({settings:h}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){$y.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await sp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var Is,np=T(()=>{"use strict";kr();q();qi();Is=class extends lr{async executeCliCode(){var g,h,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(h=(g=t.company)==null?void 0:g.activePlan)==null?void 0:h.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,f=await hs(o,i,a,m,l,c,d,u);return this.checkCodeResponse(f)}async performAction(){try{return await this.executeCliCode()}catch(e){let{stepResult:t}=this.sessionPlayerInit.commonConstants;return e instanceof ne?{success:!1,errorType:t.ACTION_TIMEOUT}:{success:!1,reason:e.message,exception:e}}}}});var ur,Gy=T(()=>{"use strict";np();ur=class extends Is{isFailedResult(e){return e===!1}}});var ia,Hy=T(()=>{"use strict";np();ia=class extends Is{isFailedResult(e){return!e}}});var aa,qy=T(()=>{"use strict";kr();ue();q();aa=class extends W{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await gs(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 ne?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var Dr,zy=T(()=>{"use strict";ue();Dr=class extends W{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ve,Ky=T(()=>{"use strict";ue();ve=class extends W{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 ca,Jy=T(()=>{"use strict";ue();ca=class extends W{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 la,Yy=T(()=>{"use strict";ue();la=class extends W{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 eI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function ua(s,e){eI(tI,e),e.registerLocateStepActionUtils(Dn.getUtils(s))}var tI,op=T(()=>{"use strict";zh();Yh();oy();iy();cy();py();fy();gy();hy();Ty();wy();vy();Iy();Ay();Ly();Dy();My();Ny();Uy();Fy();Vy();Gy();Hy();qy();zy();Ky();Jy();Yy();tI={locate:Dn,scroll:$i,mouse:Wi,submit:Ji,text:Gi,"special-key":zi,"user-code":qt,"validation-code-step":qt,"wait-for-code-step":qt,"action-code-step":qt,"condition-step":Ss,"skip-code-step":Ss,"element-code-step":Ss,"evaluate-expression":Vi,"text-validation":Nn,"wait-for-text-validation":Nn,"select-option":Ki,"drop-file":Qi,"input-file":ea,hover:Yi,navigation:ra,wheel:Xi,sleep:sa,refresh:na,"api-validation":Un,"api-action":Un,"api-code-step":qt,"extract-text":oa,"simple-ui-verification":Fn,"wait-for-simple-ui-verification":Fn,"cli-validation-download-file":Dr,"cli-wait-for-download-file":Dr,"network-validation-step":Dr,"cli-validation-code-step":ur,"cli-wait-for-code-step":ur,"cli-action-code-step":ur,"cli-api-code-step":ur,"cli-condition-step":ia,"node-package":aa,"email-code-step":qt,"cli-email-code-step":ur,"sfdc-internal-test-step":la,"sfdc-recorded-step":ca,"sfdc-step-login":ve,"sfdc-step-loginas":ve,"sfdc-step-logout":ve,"sfdc-step-sobjectcreate":ve,"sfdc-step-sobjectdelete":ve,"sfdc-step-findrecord":ve,"sfdc-step-quickaction":ve,"sfdc-step-sobjectedit":ve,"sfdc-step-sobjectvalidate":ve,"sfdc-step-launchapp":ve,"sfdc-step-wait-for-page-load":ve,"sfdc-step-closeconsoletabs":ve,"sfdc-step-relatedlistaction":ve,"sfdc-step-permission-validation":ve,"sfdc-step-convert-lead-to-opportunity":ve,"sfdc-step-quotelineeditor":ve,"sfdc-document-validation":Dr}});var Xy,rI,Rs,ip=T(()=>{"use strict";Xy=["simple-ui-verification","wait-for-simple-ui-verification"],rI=[...Xy,"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"],Rs=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=rI.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 Xy.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 Zy={};V(Zy,{SeleniumTestPlayer:()=>Bn});var Qy,Bn,ap=T(()=>{"use strict";B();Qy=require("@applitools/eyes-sdk-core");Pn();q();Ju();$h();Zu();Wh();Hh();ep();Te();op();ip();Bn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new Rs(ji());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=se();this.driver=n??new Pr;let d=new Bi(this.driver);this.stepActionFactory=new c(d),ua(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Ui(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=Gh(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new vs(this.driver),FrameLocator:m,portSelector:Fi,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Qy.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}=se(),t=1e3*60*2;try{await ce((r=this.driver)==null?void 0:r.end(),t)}catch(o){o instanceof ne&&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 n=(await this.driver.getTabIds()).at(-1);return await this.tabService.addNewTab(this.id,n,e,t),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 eb={};V(eb,{WorkerSelenium:()=>cp});function nI(s){let{playback:e}=se().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>N(`Got event ${t}`))}var pa,sI,cp,tb=T(()=>{"use strict";B();$e();Ln();j();Ot();qo();ae();zu();q();ap();Te();pa=x("worker-selenium"),sI=1e9,cp=class extends at{initPlayer(t){return new Bn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){N("in WorkerSelenium getBrowserOnce"),Q.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ws(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}),N("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),N("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,sI),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`):(pa.error("failed to navigate to page",{baseUrl:l,err:c}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=se(),{driver:i,sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),nI(a),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName,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 fn(this.options))[this.testId]);let d=async()=>ce(new Promise((u,f)=>{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(f)}),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG).catch(u=>{var f;throw u instanceof ne&&((f=a.stopPlayingOnTestTimeout)==null||f.call(a)),u}).then(async u=>{await o.drain(),u.stepsResults=null,u.resultId=this.testResultId,i.isAlive()||(pa.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.gridIssues="could not validate grid is alive");let f=i.maxKeepAliveGap();f>=3e4&&(pa.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let h={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${h.success?"passed":"failed"}`).catch(()=>{}),h});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 pa.error("failed to run test once",{err:u}),u}}}});var rb,He,oI,iI,lp,vt,da=T(()=>{"use strict";j();ae();le();ye();Ke();rb=v(require("ora")),He=x("mobile-grid-service"),oI="https://tdc.tricentis-cloud.com",iI="https://ui.headspin.io",lp=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)?`${t}/lock`:""}getBaseApiUrl(e){return e===O.TESTIM_HEADSPIN?`${ad}/devices`:e===O.TESTIM_TDC?`${ld}/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.type),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await Ge({url:r,headers:n,body:o})}catch(i){throw He.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.type)}/device_id:${t}/automation-config`;try{let o=await Ee(n,void 0,this.getHeaders(e));return this.extractHeadSpinDeviceConnection(o,e.accessToken)}catch(o){throw He.error("error while getting automation config for device",{error:o,deviceId:t}),o}}async getPCloudyAuthToken(e,t){let r=await Vs(`${ja}/access`,void 0,{Authorization:`Basic ${Buffer.from(`${e}:${t}`).toString("base64")}`});return JSON.parse(r).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){if(this.isTdcOrHeadSpinGrid(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:`/v0/${e.accessToken}/wd/hub`};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;if(t===O.TESTIM_HEADSPIN||t===O.TESTIM_TDC){let c=await gl({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=c==null?void 0:c[0])==null?void 0:a.name)||e.device}if(t===O.BROWSERSTACK)return(l=e.mobile)==null?void 0:l.version.split("-")[0];if(t===O.SAUCELABS)return e.testobject_device_name;if(t===O.P_CLOUDY){if(e.pCloudy_DeviceFullName){let c=e.pCloudy_DeviceFullName.split("_");return`${c[0]} ${c[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r){var E;let{executionId:n,testId:o,testResultId:i}=e,{project:a,projectData:{type:l}={},company:{companyId:c=""}={},gridData:{gridId:d="",type:m=""}={}}=r,u=t.capabilities,f=await this.getDeviceNameFromSessionCaps({capabilities:u,gridType:m,projectId:a,projectType:l,companyId:c,gridId:d}),g=u.platformVersion;!g&&m===O.BROWSERSTACK&&(g=(E=u.mobile)==null?void 0:E.version.split("-")[1]),!g&&m===O.TESTIM_TVC&&(g=u.os_version);let h={name:f??"",model:u.deviceModel,osVersion:g,udid:u.udid,osType:u.platformName,scaleFactor:u.pixelRatio,isVirtual:m===O.TESTIM_TVC,...m===O.TESTIM_TVC&&{model:u.deviceModel||t.capabilities.device,height:t.capabilities.screen.height,width:t.capabilities.screen.width,scaleFactor:t.capabilities.screen.scale}},y=await this.buildRemoteResultLink(r.gridData,t.sessionId,u);return await Er(a,n,o,i,"RUNNING",{device:h,...y&&{remoteResultLink:y}}),He.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:h,remoteResultLink:y,gridType:m}),h}async buildRemoteResultLink(e,t,r){return e.type===O.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Ns}/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?iI:oI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let t=await Ee(`${fd}/devices`),r=t==null?void 0:t.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,resolution:`${r.width}x${r.height}`,geo:"local",manufacturer:r.model,osVersion:r.osVersion,type:r.deviceType||"",osType:r.osType,isLandscape:r.screenMirror.orientation==="LANDSCAPE",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 Er(l,n,o,i,"RUNNING",{device:a}),He.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getMobileAppDataByAppId({appId:e,projectId:t,token:r,executionId:n,testResultId:o}){try{let i=await Kc({appId:e,projectId:t});if(!i)throw He.error("mobile app not found",{appId:e,projectId:t,executionId:n,testResultId:o}),new Error("mobile app not found");return{appUrl:`${me}/storage${i.filePath}?access_token=${r}`,mobileApp:i}}catch(i){throw He.error("error while getting app details",{error:i,appId:e,projectId:t,executionId:n,testResultId:o}),i}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(id*60))+1)*60*1e3,Math.max(od,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let i={[O.BROWSERSTACK]:{name:"Browserstack",appPath:"browserStackAppId"},[O.TESTIM_TVC]:{name:"Mobile Virtual Grid",appPath:"testimTvcAppId"},[O.P_CLOUDY]:{name:"pCloudy",appPath:"pCloudyAppId"}},a=i[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,rb.default)(`uploading app to ${a} please wait..`).start();try{He.info(`uploading app to ${a} during test run`,{mobileApp:r,projectId:e,testResultId:t.testResultId,executionId:t.executionId});let d=await hl({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});c.succeed(`app uploaded successfully to ${a}`);let m=i[o].appPath;return d[m]}catch(d){throw c.fail(`failed to upload app to ${a}`),He.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&&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:f="",host:g=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:i});let I=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d,executionId:i,testResultId:a});n=I.appUrl,o=I.mobileApp,e.nativeApp=o}else He.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,y=this.gridsAppIdGetter[f]({testRunHandler:e,mobileApp:o,gridHost:g}),E=f===O.BROWSERSTACK||f===O.TESTIM_TVC||f===O.P_CLOUDY;if(y){let I=t.projectData.type,b=await this.verifyAppStillExistsOnGrid({gridAppId:y,gridData:m,projectType:I});b&&(He.info("app exists on grid, using gridAppId",{gridAppId:y,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=y),!b&&E&&(He.info("app not exists on grid, uploading it",{gridAppId:y,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!b&&!E&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:i})}return!y&&E&&(n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),n}async verifyAppStillExistsOnGrid({gridAppId:e,gridData:t,projectType:r}){var c,d;let{accessToken:n,user:o,host:i,key:a,type:l}=t;if(l===O.BROWSERSTACK){let m=`${Ns}/recent_apps`;return(await this.fetchWithUserAndPasswordAuth({url:m,user:o,key:a})).some(f=>f.app_url===e)}if(l===O.SAUCELABS){let u=`${i.includes("eu-central-1")?md:dd}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a})).items.some(g=>g.id===e)}if(l===O.TESTIM_HEADSPIN||l===O.TESTIM_TDC){let m=l===O.TESTIM_HEADSPIN?`${cd}/apps`:`${ud}/apps`;return(await this.fetchWithTokenAuth({url:m,accessToken:n,authType:"Bearer"})).apps.some(f=>f.app_id===e)}if(l===O.TESTIM_TVC){let m=`${pd}/versions/${e}/info`,u=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:m,accessToken:u,authType:"Upload-Token"}),!0}catch(f){return f.status!==404&&He.error("error while verifying app exists on TVC",{error:f}),!1}}if(l===O.P_CLOUDY){let m=await this.getPCloudyAuthToken(o,a),u=`${ja}/drive`,f=await rc({url:u,body:{token:m,filter:"all"},headers:{contentType:null}});return(d=(c=JSON.parse(f).result)==null?void 0:c.files)==null?void 0:d.some(h=>h.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 Ee(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await Ee(e,void 0,n)}},vt=new lp});function up({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"&&!aI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function cI({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 lI(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 uI(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&&M.flags.enableBatchHeadSpin.isEnabled(),d=i&&(M.flags.enableBatchTDC.isEnabled()||M.flags.headSpinTdcEnableFlagCapability.isEnabled());return{[`${l}:capture`]:!0,...M.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...o&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:lI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n}}}function ma(s){return"id"in s?s.id:s.packageName}function pI(s,e){return{[`${e===O.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function dI({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=pI(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":ma(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":ma(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function fa({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:o=""}){switch(s){case"ios":return{...e,platformName:"iOS",[`${o}autoAcceptAlerts`]:!0,[`${o}automationName`]:"XCUITest",[`${o}fullReset`]:!0,...t&&{[`${o}bundleId`]:ma(t)},...r&&{[`${o}app`]:r}};case"android":return{...e,platformName:"Android",[`${o}autoGrantPermissions`]:!0,[`${o}automationName`]:"UiAutomator2",...n&&{[`${o}appWaitActivity`]:n},...t&&{[`${o}appPackage`]:ma(t),[`${o}appActivity`]:t.activity??".*"},...r&&{[`${o}app`]:r}};default:throw Error(`unsupported mobile project ${s}`)}}function nb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=uI(i.type,o,n);return dI({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function pp({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 dp({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?$a:o.deviceNameRegex:t==="ios"&&r===O.BROWSERSTACK?"iPhone.*":i?t==="ios"?"apple":$a:".*")}function mI(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 fI({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=mI(o,s),f=pp({osVersion:l,mobileConfig:d}),g=dp({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=qe(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y={device:g,os_version:f,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":h,"waldo:options":{token:u}};return fa({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function gI({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:f}=o,g=pp({osVersion:l,mobileConfig:d}),h=dp({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),y=/^[a-zA-Z]+$/.test(h),E={...g!==".*"&&{pCloudy_DeviceVersion:g},...y&&{pCloudy_DeviceManufacturer:h},...!y&&{pCloudy_DeviceFullName:h}},I={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...E,pCloudy_DurationInMinutes:n.duration?Number(n.duration):gd,pCloudy_ApplicationName:t,newCommandTimeout:120,fullReset:!0};return t="",fa({projectType:s,sessionCaps:I,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function hI(s,e){let t=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,r=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,n=e==="android"&&t.test(s),o=e==="ios"&&r.test(s);return n||o}function yI({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=m===O.BROWSERSTACK?"browserstack":"saucelabs",f=pp({osVersion:l,mobileConfig:d}),g=dp({deviceName:c,mobileConfig:d,projectType:s,gridType:m});if(hI(f,s)&&m===O.SAUCELABS){let y={appiumVersion:"latest",user:o.user,key:o.key,debug:!0,networkLogs:!0,tags:Object.values(i),name:i.testResultId,build:i.executionId};return fa({projectType:s,sessionCaps:{"appium:platformVersion":f,"appium:deviceName":g,"sauce:options":y},appiumPrefix:"appium:",nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let h={...m===O.BROWSERSTACK&&{os_version:f,device:g,realDevice:!0,project:i.project,buildTags:Object.values(i).join(",")},...m===O.SAUCELABS&&{platformVersion:f,deviceName:g,tags:Object.values(i)},name:i.testResultId,build:i.executionId,[`${u}.user`]:o.user,[`${u}.key`]:o.key,[`${u}.debug`]:!0,[`${u}.networkLogs`]:!0};return fa({projectType:s,sessionCaps:h,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function ob(s){return O.TESTIM_TDC===s.gridInfo.type||O.TESTIM_HEADSPIN===s.gridInfo.type?nb(s):O.TESTIM_TVC===s.gridInfo.type?fI(s):O.P_CLOUDY===s.gridInfo.type?gI(s):yI(s)}function bI(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 ib(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}`);up({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=vt.getGridConnection(e),l=ob(s);if(e.type===O.TESTIM_HEADSPIN||e.type===O.TESTIM_TDC){let d=e.type===O.TESTIM_HEADSPIN?"headspin":"tdc",m=bI(r,o==null?void 0:o.mobile);if(!(0,sb.isEmpty)(m)){let u=Object.entries(m).map(([f,g])=>g.split(",").map(h=>h===".*"||h==="="?"":`${f}:${h}`).join(",")).join(" ").trim();l[`${d}:selector`]=u}}let c=e.type===O.TESTIM_TVC?{alwaysMatch:l}:l;return{...a,desiredCapabilities:l,capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function ab(s){var g,h;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;up({nativeAppMetadata:r,appPath:o,gridInfo:t}),cI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((h=(g=l.mobile)==null?void 0:g.staticAllocation)==null?void 0:h.deviceUdid),m=await vt.getGridDirectConnection(t,d),f=nb({projectType:e,nativeAppMetadata:r,appPath:o,androidActivityWait:i,options:n,sessionTags:a,testRunConfig:l,gridInfo:t});return d&&(f["appium:udid"]=d),{...m,desiredCapabilities:f,capabilities:f,connectionRetryCount:0,logLevel:n.appiumLogLevel}}function cb(s){return up(s),ob(s)}function lb(s){var t,r;let e=Object.assign({},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 sb,aI,mp=T(()=>{"use strict";fe();ae();da();sb=require("lodash");B();le();aI=[O.BROWSERSTACK,O.SAUCELABS,O.TESTIM_HEADSPIN,O.TESTIM_TDC,O.TESTIM_TVC,O.P_CLOUDY]});var ga,pb=T(()=>{"use strict";ga=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 ha,db=T(()=>{"use strict";ha=class{constructor(e){this.driver=e;this._abortedSteps=[]}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 fp,ya,mb=T(()=>{"use strict";j();fp=x("mobile-frame-locator-mock"),ya=class{foundFrameCallback(){return fp.info("foundFrameCallback-mock invoked"),{}}locate(){return fp.info("locate-mock invoked"),{}}async findFrame(){return fp.info("findFrame-mock invoked"),{}}}});var TI,gb,fb,xs,gp=T(()=>{"use strict";TI=v(require("webdriverio")),gb=require("@applitools/eyes-sdk-core");pb();Zu();j();db();ep();Te();op();mb();ip();fb=x("appium-test-player"),xs=class{constructor(e,t,r,n=TI,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=se(),m=new ha(this.driver);this.stepActionFactory=new c(m),ua(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Rs(ji()),this.sessionPlayer=new a(e,{tabService:new ga,cookieUtils:void 0,FrameLocator:ya,portSelector:Fi,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:gb.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{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}=se();e.off(i.playback.RESULT),this.sessionPlayer=null,this.stepActionFactory=null,this.driver=null}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function wI(s){return await Ee(`${s}/api/status`)}async function hb(s,e){return await Ee(`${s}/api/devices/${e}/status`)}async function yb(s){if((await wI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var bb=T(()=>{"use strict";Ke()});var Tb={};V(Tb,{WorkerLocalTma:()=>Tp});var ba,hp,yp,bp,Tp,wb=T(()=>{"use strict";Ke();mp();Ln();B();j();Ot();gp();Te();bb();da();ba=x("worker-appium"),hp=class extends Error{},yp=class extends Error{},bp=class extends Error{},Tp=class extends at{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new xs(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}=se(),{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 R;if(Q.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 yb(i);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{executionId:k,testResultId:_}=t,{mobileApp:$}=await vt.getMobileAppDataByAppId({appId:f,projectId:c,token:d,executionId:k,testResultId:_});t.nativeApp=$}let g=u==="android"?t.androidActivityWait:null,h=t.nativeAppMetadata,y=t.downloadableAppPublicLink,E=t.appPackageNameOrBundleId;if(!h)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!E)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},w]=await Promise.all([this.getAppStateFromDevice(i,a,E),hb(i,a)]).catch(k=>{throw this.handleDeviceNotFoundError(k),k});if(!I&&t.isAppFromDevice&&!f)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);try{let k={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(R=this.options.projectData)==null?void 0:R.name}-${this.options.project}`},_=cb({projectType:u,nativeAppMetadata:h,appPath:y,androidActivityWait:g,sessionTags:k,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),$={capabilities:{udid:a,..._}},S=await this.requestNewAppiumSessionFromTma(i,$,h);this.sessionData=S;let A=await m.attach({sessionId:S.sessionId,capabilities:_});this.device=await vt.updateTmaDeviceDetails(a,this.options,t),ba.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:A.sessionId,testResultId:this.testResultId,nativeAppMetadata:h,sessionCaps:A.capabilities})}catch(k){throw ba.error("failed to start application",{err:k}),k}}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"}}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 bp(l):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,l=(await Ee(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 Ws(`${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 yp(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 hp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=se(),{sessionPlayer:i}=r,a=n||"runner";Q.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 ba.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw ba.error("failed to run test once",{err:c}),c}}}});var Eb={};V(Eb,{WorkerAppium:()=>wp});var vb,As,wp,Sb=T(()=>{"use strict";mp();vb=require("linkedom");Ln();j();Ot();gp();Te();da();ae();ls();As=x("worker-appium"),wp=class extends at{initPlayer(t){return new xs(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){Q.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},u={projectType:a,nativeAppMetadata:d,appPath:l,androidActivityWait:c,sessionTags:m,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig},f;this.options.skipLoadBalancer&&this.options.deviceUdid?(this.options.lockDevice&&await vt.lockDevice(o,this.options.deviceUdid),f=await ab(u)):f=ib(u),As.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:lb(f)}),this.activeSession=await i.remote(f),this.device=await vt.updateDeviceOnRemoteTestResult(t,this.activeSession,this.options);let g=`${this.getServerAddressFromGrid()}/session/${this.activeSession.sessionId}`;this.updateSlotData(g),As.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw As.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}updateSlotData(t){try{this.options.slotService==="redis"&&Yf(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){As.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.TESTIM_TVC?`https://${t}/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,f;let{manifestVersion:n,AppiumApi:o,localAssetService:i}=se(),{sessionPlayer:a}=r,l=n||"runner";Q.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let c;if(this.options.skipLoadBalancer){let g=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:h,hostname:y,port:E,path:I}=await vt.getHeadSpinDeviceConnection(this.options.gridData,g);c=`${h}://${y}:${E}${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:(f=this.options.company)==null?void 0:f.companyId,device:this.device},a.playbackManager.appiumApi=new o(c,this.activeSession.sessionId,vb.DOMParser),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let g=await new Promise((y,E)=>{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(E)});return await i.drain(),g.stepsResults=null,g.resultId=this.testResultId,{...g,...t.seleniumPerfStats.getStats()}}catch(g){throw As.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:g}),g}};try{return await super.runTestOnce(t,r),await m()}catch(g){throw As.error("failed to run test once",{err:g}),g}}}});var Ta,Ib=T(()=>{"use strict";B();Pn();q();Ta=class{constructor(e){this.id=e;this.driver=new Pr}async onDone(){try{await ce(this.driver.end(),12e4)}catch(t){t instanceof ne&&await this.driver.forceEnd().catch(()=>null)}this.driver=null}getSessionId(){return this.driver.getSessionId()}}});var Rb,wa,xb=T(()=>{"use strict";Rb=v(require("ws"));B();wa=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 Rb.default(this._cdpUrl,{timeout:e}),r=Yt(o=>{t.once("open",o)}),n=Yt(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 Ea,vp,va,Ab=T(()=>{"use strict";B();Ea=v(require("chrome-launcher"));xu();xb();un();vp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new wa}async init(e){var u,f,g,h;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l}=e,c=vi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l}),d=[...((u=c.desiredCapabilities)==null?void 0:u.chromeOptions.args)??[],...((h=(g=(f=c.capabilities)==null?void 0:f.alwaysMatch)==null?void 0:g["goog:chromeOptions"])==null?void 0:h.args)??[],...Ea.Launcher.defaultFlags().filter(y=>y!=="--disable-extensions")];this.chrome=await Ea.launch({chromeFlags:d,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 m=await br(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(m),rs(()=>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}},va=class{constructor(e){this.id=e;this.sessionId=re();this.driver=new vp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Pb={};V(Pb,{WorkerExtension:()=>jn});function vI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Cb(s){return vI(s)?s:new Error(s)}var ct,jn,Ep=T(()=>{"use strict";$e();q();Ln();B();j();Ot();ae();Ib();Ab();ct=x("worker-ext"),jn=class extends at{initPlayer(){return this.options.useChromeLauncher?new va(this.id):new Ta(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})}catch(a){throw ct.error("failed to get browser",{err:a,gridInfo:n,testId:e.testId,resultId:e.testResultId}),a}}async getBrowserOnce(e,t,r,n){return Q.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 ne))throw u;return ct.warn("timeout while running test using CDP. Running checkViaRestAPIIfTestStarted",{testResultId:r}),await e.checkViaRestAPIIfTestStarted()}},a=async(d,m,u)=>{try{let f=await d.url(m);return u.driverUrlFinished=!0,f}catch(f){throw ct.error("error from driver.url",{err:f,testResultId:r,executionId:n,testId:o,url:m,urlLength:m.length}),f}},l=async d=>{let m=await e.onStarted(this.options.testStartTimeout);return d.testRunHandlerOnStartedHadFinished=!0,m},c=async()=>{var f;if(N("WorkerExtension runExtTest"),((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep)||this.options.disableSockets||e.listenToRemoteStep(t.driver),this.isUsingChromeLauncher(t)){Q.onWaitToTestStart(this.id),Q.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(g){throw ct.warn("failed to run test via CDP",{err:g}),g}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let g=await e.getRunTestUrl();Q.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,g,u),l(u)]),this.options.testStartTimeout,Fe.TEST_START_TIMEOUT_MSG)}catch(E){if(!(E instanceof ne))throw E;ct.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}Q.onWaitToTestComplete(this.id);let h=new AbortController,y=E=>{e.onCompletedCleanup(),ct.warn("on browser closed error detected",{err:E,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),E.type=Hs.BROWSER_CLOSED,h.abort(E)};m.registerToClosedBrowser(y);try{let E=ce(e.onCompleted(),this.testRunTimeout,Fe.TEST_COMPLETE_TIMEOUT_MSG),I=await Xa(E,h.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(I.success),I.reason)}catch(R){ct.error("Could not update the grid about the test status",{err:R})}m.isAlive()||(ct.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&&(ct.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),I.keepAliveIssue=b),{...I,...e.seleniumPerfStats.getStats()}}catch(E){throw ct.warn("timeout wait until test completed",{err:E,testResultId:r,executionId:n,testId:o}),Cb(E)}finally{m.unregisterToClosedBrowser(y)}}catch(g){throw ct.warn("failed to start url",{err:g}),Cb(g)}};t.driver.start();try{return await super.runTestOnce(e,t),N("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ct.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var kb={};V(kb,{WorkerExtensionSingleBrowser:()=>Sp});var EI,SI,Sp,Ob=T(()=>{"use strict";$e();B();j();Wu();Ot();Ep();EI=x("base-worker"),SI=500,Sp=class extends jn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await On(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 Q.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()&&(EI.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 oe(SI)}}});function II(s,e){e===0?s():setTimeout(s,e*Zp)}var Ip,Sa,_b=T(()=>{"use strict";Pn();le();$e();gu();Ct();Ou();q();j();ae();Ch();Ip=x("parallel-worker-manager"),Sa=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case Y.SELENIUM:return(tb(),he(eb)).WorkerSelenium;case Y.APPIUM:return e.localTmaUrl?(wb(),he(Tb)).WorkerLocalTma:(Sb(),he(Eb)).WorkerAppium;default:return Si.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Ob(),he(kb)).WorkerExtensionSingleBrowser:(Ep(),he(Pb)).WorkerExtension}}createWorkers(e,t,...r){let n=r[0],o=this.getWorkerType(n),i=()=>{try{return N("before new Worker",n.mode),new o(t,...r)}finally{N("after new Worker",n.mode)}};return Array.from(new Array(e),i)}async runTests(e,t,r,n,o,i,a,l,c){if(e&&e.length===0)return;let d=!1,m=0,u=f=>new Promise(g=>{var lt,dr,P,D,F,z,ut,Pa;let h=o.project,y=new ki(r,n,e,o,i,t),E={},I=e.length,b=((lt=o.company)==null?void 0:lt.ucid)||"",w=(dr=o.company)==null?void 0:dr.companyId,R=(P=o.company)==null?void 0:P.name,k=o.source||"cli",_=o.user,$=(D=o.company)==null?void 0:D.planType,S=(F=o.company)==null?void 0:F.isStartUp,A=(z=o.projectData)==null?void 0:z.name,L=(ut=o.projectData)==null?void 0:ut.type,U=o.lightweightMode,J=(Pa=o.gridData)==null?void 0:Pa.type,H=(Lt,pt,be,ka,Wn,Oa)=>(m++,ug({executionId:r,projectId:h,testId:pt,resultId:be,ucid:b,companyId:w,companyName:R,projectName:A,companyPlan:$,source:k,user:_,lightweightMode:U,isStartUp:S,projectType:L,appSource:Oa,gridType:J}),t.testStartAndReport(Lt,r,be,ka,Wn)),X=async(Lt,pt,be,ka,Wn,Oa)=>{var Np,Up,Fp;m--;let et={...(U==null?void 0:U.onlyTestIdsNoSuite)&&{show:!0},...be.seleniumStats&&{seleniumStats:be.seleniumStats},...be.gridIssues&&{gridIssues:be.gridIssues},...be.keepAliveIssue&&{keepAliveIssue:be.keepAliveIssue},...o.host&&{gridHost:o.host}};if(be.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(be.seleniumPerfMarks),delete be.seleniumPerfMarks),o.grid||o.gridId?(et.gridName=o.grid||((Np=o.gridData)==null?void 0:Np.name),et.gridType=(Up=o.gridData)==null?void 0:Up.type,et.gridProvider=(Fp=o.gridData)==null?void 0:Fp.provider):o.localTmaUrl?(et.gridName="local-tma-from-options",et.gridType="local-tma"):o.useLocalChromeDriver?(et.gridName="local-chrome-driver-from-options",et.gridType="local-chrome"):o.useChromeLauncher?(et.gridName="chrome-launcher-from-options",et.gridType="local-chrome"):o.browserstack?et.gridName="browserstack-from-options":o.saucelabs&&(et.gridName="saucelabs-from-options"),await t.testEndAndReport(Lt,be,r,ka,Wn,et).catch(RT=>Ip.error("testEndAndReport threw an error",{err:RT})),Wn)return;E[be.resultId]=be,pg({executionId:r,projectId:h,testId:pt,resultId:be.resultId,result:be,ucid:b,companyId:w,companyName:R,projectName:A,companyPlan:$,source:k,user:_,lightweightMode:U,logger:Ip,isStartUp:S,projectType:L,appSource:Oa}),c&&!be.success&&(y.stop(),d=!0),(Object.keys(E).length===I||d&&m===0)&&g(E)},de=(Lt,pt)=>{E[pt.resultId]=pt,t.onTestIgnored(Lt,pt.resultId),m--,(Object.keys(E).length===I||d&&m===0)&&g(E)},Et=(Lt,pt)=>t.onGridSlot(Lt,pt);o.userData={loginData:Object.assign({},jt(),{refreshToken:ko(),authData:jt(),token:f}),projectId:o.project,company:o.company,servicesUrl:me},N("in localStrategy before createWorker"),this.createWorkers(l,y,o,this.customExtensionLocalLocation,r,H,X,Et,de).forEach((Lt,pt)=>{N("before schedule worker.run after createWorkers"),II(()=>{N("right before worker.run"),Lt.run()},pt)})});try{let f=await Zt(),g=await u(f);if(d)throw new Kt;return g}catch(f){throw Ip.error("failed running parallel workers",{executionId:r,err:f}),f}}}});async function Db(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:re()}))]}:await zc({projectId:s.project,labels:s.label,testIds:s.testId,testNames:s.name,testConfigNames:s.testConfigNames,suiteNames:s.suites,suiteIds:s.suiteIds,branch:e,rerunFailedByRunId:s.rerunFailedByRunId,testConfigIds:s.testConfigIds,intersections:s.intersections})}function Rp(s){let e=Object.keys(s).length,t=Object.keys(s).reduce((r,n)=>r+(s[n].success===!0?1:0),0);return e===t}async function xp(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=Lb.difference(qs(s,e),t);if(r.length>0)throw ht("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new C(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var Lb,Mb=T(()=>{"use strict";Lb=v(require("lodash"));B();ss();ye();q()});var $n,zL,Ap,Cp,Ia,Nb=T(()=>{"use strict";$n=v(require("lodash"));B();j();le();ae();$e();as();Ql();gu();ye();Ct();Ot();_g();q();_b();Mb();({testRunStatus:zL,CLI_MODE:Ap}=Ut),Cp=x("test-plan-runner"),Ia=class{constructor(e){this.startTime=Date.now();this.workerManager=new Sa(e)}async runTestAllPhases(e,t,r,n,o,i,a,l){let c={},d=jt(),m=async()=>{let h=o.beforeParallel||1,y=!0,E=await this.workerManager.runTests(e,l,i,a,o,n,d,h,y);Object.assign(c,E)},u=async()=>{let h=to||o.parallel,y=!1;N("right before this.workerManager.runTests");let E=await this.workerManager.runTests(t,l,i,a,o,n,d,h,y);N("right after this.workerManager.runTests"),Object.assign(c,E)},f=async()=>{let h=o.afterParallel||1,y=!1,E=await this.workerManager.runTests(r,l,i,a,o,n,d,h,y);Object.assign(c,E)};dg({executionId:i,projectId:o.project}),N("right before runBeforeTests");try{return await m(),N("right before runTestPlanTests"),await u(),N("right after runTestPlanTests"),await f(),c}catch(h){if(Cp.error("error running test plan",{err:h}),h instanceof Kt)return l.markAllQueuedTests(i,pe.ABORTED,"aborted",!1);throw h}finally{await g()}async function g(){var y,E,I,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===Ap.SELENIUM){let[{getSessionPlayer:w},{makeSDK:R}]=await Promise.all([Promise.resolve().then(()=>(Te(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:k}=w();await k.closeBatch(i,R);return}let h;try{if(!((b=(I=(E=o.company)==null?void 0:E.activePlan)==null?void 0:I.premiumFeatures)!=null&&b.applitools)||(h=await ul(o.project),$n.default.isEmpty(h)||!i))return;let{runKey:w,url:R}=h;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:R,apiKey:w}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,l){var b,w,R;let c=re(),d=n.project;qa(c),e.forEach(k=>Object.assign(k,{isBeforeTestPlan:!0})),r.forEach(k=>Object.assign(k,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new wi(m,n,i,a),f=$n.default.chain(m).map(k=>{var _;return((_=k.overrideTestConfig)==null?void 0:_.name)||""}).uniq().compact().value(),g=(f==null?void 0:f.length)===1?f[0]:null,h=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(k=>k.name),y=(w=n.lightweightMode)!=null&&w.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,o,h);N("before testListInfoPromise");let E=await y;(R=n.lightweightMode)!=null&&R.onlyTestIdsNoSuite||Q.onTestPlanStarted(E.beforeTests,E.tests,E.afterTests,o,c,l,g),N("before runTestAllPhases");let I=await this.runTestAllPhases(E.beforeTests,E.tests,E.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:g}}async runTestPlans(e,t){Cp.info("start to run test plan",{options:Object.assign({},e,{token:void 0,userParamsData:void 0}),branchToUse:t});function r(d){return $n.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await qc(i,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new C(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new C(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Ap.APPIUM&&await xp(e,r(c)),await ie(l,async d=>{var g;let m=d.testPlanId;n[m]={};let u=Object.assign({},e);u.baseUrl||=d.startUrl,u.appId||=((g=d.mobileApp)==null?void 0:g.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await Vf(e,d);let f=u.overrideExecutionName||d.name;return await ie(c[m],async h=>{let y=await this.runTestPlan(h.beforeTests,h.tests,h.afterTests,u,f,m,t);Q.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let E=Object.keys(n[m]).map(R=>({executionId:R,status:Rp(n[m][R])})),I=Object.keys(n[m]).map(R=>n[m][R]).reduce((R,k)=>Object.assign(R,k),{}),b=Rp(I);Object.assign(o,I);let w=b?E[0].executionId:E.find(R=>!R.status).executionId;return await Vc(i,m,{success:b,executions:E,executionId:w}),y})})}async runAnonymousTestPlan(e,t){var a;Cp.info("start to run anonymous",{options:Object.assign({},e,{token:void 0}),branchToUse:t}),N("before getSuite");let r=await Db(e,t);if(N("after getSuite"),!((a=r==null?void 0:r.tests[0])!=null&&a.length)){if(e.rerunFailedByRunId)throw new C("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new C("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new C("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;return N("Right before validateConfig + runAnonymousTestPlan tests map"),await ie(r.tests,async l=>{if(e.resultId){let d=l[0];d.resultId=e.resultId,l=[d]}e.mode!==Ap.APPIUM&&await xp(e,l),N("right before runTestPlan");let c=await this.runTestPlan([],l,[],e,o,null,t,i);return N("right after runTestPlan"),await Q.onTestPlanFinished(c.results,o,this.startTime,c.executionId,i),c})}async run(e){let t=vn(),r=[];zs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=$n.default.flattenDeep(r);return N("right before onAllTestPlansFinished"),await Q.onAllTestPlansFinished(n),N("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var jb={};V(jb,{init:()=>HI,run:()=>jI});async function RI(s){let e=s.project,t=await Jc(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"),pn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Us}function xI(s,e){var i,a,l,c,d,m,u;let t=mo(e.activePlan),r=s.parallel;if(t==="free"&&r>Fb)throw new C(`The free plan allows only ${Fb} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let f=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!f)throw new C("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 g=(c=(l=e.activePlan)==null?void 0:l.premiumFeatures)==null?void 0:c.runInTurboMode;s.lightweightMode&&!g&&(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 f=e.tvcLicense.expireAt||1;if(Date.now()>f)throw new C("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let g=Number(e.tvcLicense.maxParallel);if(r>g)throw new C(`Your license allows only ${g} parallel runs. Please contact us to upgrade your license at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`)}let n=s.retentionDays;if(!n)return;let o=(u=(m=e.activePlan)==null?void 0:m.premiumFeatures)==null?void 0:u.resultRetention;if(n>o)throw new C(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function AI(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await RI(s)}catch(t){if([C,Us].some(r=>t instanceof r))throw t;Pp.error("could not validate cli account",{err:t})}}function CI(s){let e=jt();return Km({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function PI(s,{disableResults:e=!1,disableRemoteStep:t=!1,maxNumberOfListeners:r}){if(M.flags.useNewWSCLI.isEnabled()&&!e&&!t)return Tt.connect(s);if(!t){let{remoteStepService:n}=await Promise.resolve().then(()=>(Ai(),bh));await n.init(s)}if(!e){let{testResultService:n}=await Promise.resolve().then(()=>(Ci(),vh));n.init(s,r)}}function kI(s,e){let{branch:t,autoDetect:r}=s;if(Xf(e,r),!e&&!r)throw new C(`branch ${t} does not exist, run aborted.`)}async function OI(s){let{project:e}=s,t=vn();Bb.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")&&(s.sfdcCredential=await $c({projectId:e,branch:t}))}function _I(s,e){let{onprem:t,id:r,storageBaseUrl:n,storageType:o,name:i,activePlan:a={}}=e;if(t){let{mode:m,extensionPath:u,ext:f,playerPath:g}=s;if([Y.SELENIUM].includes(m)&&!g)throw new C("in selenium on prem mode --player-path must be provided");if(m==="extension"&&!u&&!f)throw new C("In extension on prem mode --ext or --extension-path must be provided")}let l=Boolean(a.isPoc),c=Boolean(a.isStartUp),d=mo(a);d==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<Ub?Ub:s.newBrowserWaitTimeout),M.setCompanyId(r),M.setIsPOC(l),M.setIsStartUp(c),M.setPlanType(d),kt.setPlanType(d),s.company={ucid:"",companyId:r,onprem:t,storageBaseUrl:n,storageType:o,name:i,planType:d,isPOC:l,isStartUp:c,activePlan:a}}function LI(s,e){s.editorUrl=Ms||e.editorUrl}function DI(s,e){s.allGrids=e}function MI(s,e){s.authData=e}function NI(s,e){let{id:t,name:r,type:n,defaults:o}=e;M.setProjectId(t),M.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:o}}async function UI(s){s.gridData=await Gf(s)}async function FI(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(ht("user-override-file",t),s.mockNetworkRules=await Dm(s.overrideMappingFile))}async function BI(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 wf(),N("in runner.js after checkNpmVersion"),await AI(s),N("in runRunner before tunnel.connect"),await ei(s),N("in runRunner after tunnel.connect");let a=await new Ia(e).run(s);return N("before tunnel.disconnect"),await ti(s),await VI(s.slotService,t,s.company.companyId),N("after tunnel.disconnect and gridService.keepAlive.end"),a}function $I(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