@testim/testim-cli 4.103.0-beta.0 → 4.103.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 +2 -2
- package/cli.js.map +2 -2
- package/npm-shrinkwrap.json +11503 -2
- package/package.json +1 -1
package/cli.js
CHANGED
|
@@ -216,7 +216,7 @@ When running the CLI in Selenium mode, the Turbo Mode option is ignored, as they
|
|
|
216
216
|
`,u=[],f=new wh.Worker(m,{eval:!0});try{return await ce(new Promise(h=>{f.on("message",g=>{if(g.action==="finish"){let{data:y}=g,T={...y,tstConsoleLogs:u};ct.debug("Run code worker response",{messageWithLogs:T,transactionId:s}),h(T)}else g.action==="progress"&&u.push(g.data)}).on("error",g=>{g.message==="malformed data: URI"?ct.error("Run code worker error",{err:g,transactionId:s,fileDataUrl:i}):ct.error("Run code worker error",{err:g,transactionId:s}),h({tstConsoleLogs:u,status:"failed",result:{resultValue:g==null?void 0:g.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1})}).on("exit",()=>{ct.debug("Run code worker has been terminated",{transactionId:s})}),f.postMessage({incomingParams:e,context:JSON.parse(JSON.stringify(t)),code:r})}),o)}catch(h){if(!(h instanceof ne))throw h;return ct.warn("timeout to run code",{transactionId:s,err:h}),{tstConsoleLogs:u,status:"failed",result:{resultValue:h==null?void 0:h.toString(),exports:{},exportsTest:{},exportsGlobal:{}},success:!1}}finally{f==null||f.terminate()}}async function uE(s){try{await yh.promises.rm(s,{recursive:!0,force:!0})}catch(e){ct.warn("failed to remove install npm packages folder",{err:e})}}function vh(s,e,t,r){return`${e}_${t}_${s}_${r}`}async function ds(s,e,t,r,n,o){let i=vh(n,e,s,t),{data:a}=await pE(i,r,o);return a}async function ms(s,e,t,r,n,o,i,a,l,c){var g;let d=r.computePackagePathFromPackageJsonExports||L.flags.computePackagePathFromPackageJsonExports.isEnabled(),m=Object.fromEntries(((g=t.nodePackageParams)==null?void 0:g.map(y=>{if(d){let T=vm(y.testimPackageLocalLocation);return[y.paramName,ps.join(y.testimPackageLocalLocation,T)]}return[y.paramName,y.testimPackageLocalLocation]}))||[]),u=vh(i,n,e,o);if(c){let y=await cn(c);y&&(l=y)}Buffer.isBuffer(l)&&(ct.debug("runCodeWithPackages: converted a buffer to base 64 string data URI",{fileDataUrl:l}),l=l.toString());let f="data:,";return l==="data:"&&(ct.debug("runCodeWithPackages, fileDataUrl was an empty string ",{fileDataUrl:l}),l=f),{...await lE(u,t,r,s,m,a,l),nodeVersion:process.version}}async function pE(s,e,t){let r=e.map(c=>`${c.packageName}@${c.packageVersion}`),n=Sh(),i=L.flags.reuseCliPkgInstallFolder.isEnabled()?n:ps.join(n,`/${s}`),a=global.proxyUri;async function l(){let c="";try{if(c=await Sm(i,r,a,t),ct.info("npm package install finished",{transactionId:s,output:c,timeout:t}),Number(c.trim().split(" ")[1])<r.length)throw"npm package install failed, couldn't install all packages";return{data:e.map(m=>{let u=Tm(i,m.packageName);return{...m,packageFullName:`${m.packageName}@${u}`,packageLocalLocation:ps.resolve(i,"node_modules",m.packageName)}}),installFolder:i}}catch(d){throw ct.warn("npm package install failed",{transactionId:s,err:d}),d}}try{return await ce(l(),t)}catch(c){throw c instanceof ne&&ct.warn("timeout to install package",{packages:r,transactionId:s,err:c,timeout:t}),c}}function Sh(){return ps.join(bh.tmpdir(),"/testim_local_packages")}function dE(){let s=Sh();return uE(s)}var yh,bh,ps,Th,wh,ct,fs=w(()=>{"use strict";yh=S(require("fs")),bh=S(require("os")),ps=S(require("path"));F();Yr();Th=S(require("data-uri-to-buffer")),wh=require("worker_threads");K();j();he();Yr();pe();ct=C("cli-service");dE().catch(s=>ct.warn("failed to clean local package folder",{err:s}))});var ar={};G(ar,{run:()=>fE});function mE(s,e){try{let t=e.defaults.enforceMaximumJsResultSize,r=L.flags.maximumJsResultSize.getValue(),n=JSON.stringify(s).length>r;return t?n:!1}catch{return!1}}var fE,Eh=w(()=>{"use strict";fs();K();pe();fE=async(s,e,t)=>{let{code:r,stepId:n,incomingParams:o,context:i,testResultId:a,retryIndex:l,stepResultId:c,runTimeout:d,fileDataUrl:m,s3filepath:u}=e.data;try{let f=await ms(r,n,o,i,a,l,c,d,m,u);return f&&mE({result:f.result,tstConsoleLogs:f.tstConsoleLogs},t)?{code:"js-result-max-size-exceeded",success:!1}:{data:f,success:!0}}catch(f){throw f instanceof ne?new Error("Timeout while running action"):f}}});var zu={};G(zu,{run:()=>gE});var gE,Ih=w(()=>{"use strict";fs();K();gE=async(s,e)=>{let{stepId:t,testResultId:r,retryIndex:n,stepResultId:o,packageData:i,timeout:a}=e.data;try{return{data:await ds(t,r,n,i,o,a),success:!0}}catch(l){if(l instanceof At)return{success:!1,code:"invalid-node-package",message:l.message};if(l instanceof ne)return{success:!1,code:"timeout"};throw l}}});async function Ah(s,e,t,r){try{return await vl(s,e,t,r)}catch{Oi.error("failed to report remote step state",{projectId:s,resultId:e,stepId:t});return}}async function yE(s,e,t,r,n){return Oi.info("finished to run remote step",{stepId:t,sessionId:n}),await Ah(s,e,t,{status:"completed",success:!0,failureReason:null,data:r})}async function Rh(s,e,t,r,n){return Oi.info("failed to run remote step",{stepId:t,sessionId:n,failureReason:r}),await Ah(s,e,t,{status:"completed",success:!1,failureReason:r})}async function xh(s,e,t,r){if(!(t!=null&&t.type)||t.status==="completed")return;let{project:n,projectData:o}=s,i=t.type,a=e.getSessionId(),l=t.id;Oi.info("start play remote step",{stepType:i,stepId:l,sessionId:a});let c=hE[i];if(!c)return await Rh(n,r,l,`Failed to find step type ${i}`,a);try{let d=await c.run(e,t,o);return await yE(n,r,l,d,a)}catch(d){return await Rh(n,r,l,d.message,a)}}var Oi,hE,Ch=w(()=>{"use strict";Eh();he();Ih();j();Oi=C("step-playback"),hE={"cli-validation-code-step":ar,"cli-wait-for-code-step":ar,"cli-action-code-step":ar,"cli-api-code-step":ar,"cli-condition-step":ar,"cli-download-code-step":ar,"node-package":zu}});var Ku,Ph,Cr,TE,Ju,vt,Li=w(()=>{"use strict";F();Qe();Ku=S(require("ws")),Ph=require("events");j();ue();Cr=C("socket-service"),TE=5e3,Ju=class extends Ph.EventEmitter{constructor(){super(...arguments);this.clientId=se();this.ws=null;this.filterMap={};this.listeners={}}onReconnect(t){Cr.info("test result websocket re-connect"),setTimeout(()=>this.connect(t),TE)}formatUrl(t){return t.startsWith("http://")?t.replace("http://","ws://"):t.startsWith("https://")?t.replace("https://","wss://"):t}parseEvent(t){try{return JSON.parse(t)}catch(r){Cr.error("failed to parse or trigger event",{err:r})}}connect(t){let r=this.formatUrl(id);return Pt().then(n=>new Promise(o=>{let i={...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.ws=new Ku.default(`${r}?projectId=${t}&clientId=${this.clientId}&token=${n}`,i),this.ws.on("open",()=>{var a;return Cr.info("websocket opened"),this.reSendAllExistingFilters(),(a=this.onConnect)==null||a.call(this),o()}),this.ws.on("close",a=>{Cr.info("websocket closed",{event:a}),(!this.ws||this.ws.readyState===Ku.default.CLOSED)&&this.onReconnect(t)}),this.ws.on("error",a=>{Cr.info("websocket error",{event:a})}),this.ws.on("message",a=>{let l=this.parseEvent(a);l!=null&&l.type&&this.emit(l.type,l.data)})}))}sendMessage(t){if(!this.ws){Cr.warn("tried to send error when websocket was disconnected");return}try{this.ws.send(JSON.stringify(t))}catch(r){Cr.error("failed to stringify message for sending",{err:r})}}listenOnce(t,r,n){let o=i=>{r(i)&&(n(i),this.removeListener(t,o))};this.on(t,o)}listenTo(t,r,n,o){function i(l){n(l)&&o(l)}(Array.isArray(r)?r:[r]).forEach(l=>{this.listeners[`${t}:${l}`]||=[];let c=i.bind(this);this.listeners[`${t}:${l}`].push(c),this.on(l,c)})}reSendAllExistingFilters(){Object.keys(this.filterMap).forEach(t=>{let r=this.filterMap[t];this.sendMessage({type:"add-filter",filter:r})})}addFilter(t,r,n,o=!1){return new Promise(i=>{let a=se(),l={query:r,id:a,type:n,fullDocument:o};this.listenOnce("add-filter:done",c=>c.id===a,i),this.sendMessage({type:"add-filter",filter:l}),this.filterMap[t]=l})}removeListeners(t,r){Object.keys(this.listeners).length!==0&&r.forEach(n=>{let o=this.listeners[`${t}:${n}`];o&&(delete this.listeners[`${t}:${n}`],o.forEach(i=>this.removeListener(n,i)))})}removeFilter(t,r){let n=this.filterMap[t];if(!n)return;let o=Array.isArray(r)?r:[r];this.removeListeners(t,o),delete this.filterMap[t],this.sendMessage({type:"remove-filter",filter:n})}},vt=new Ju});var _h,Yu,wE,vE,SE,kh,Di,gs,Xu=w(()=>{"use strict";_h=S(require("p-retry")),Yu=S(require("socket.io-client"));ue();F();j();wE=50,vE=10,SE=5e3,kh=10*1e3,Di=C("base socket service"),gs=class{constructor(){this.attempts=0;this.rooms={};this.emitPromiseQueue=void 0}joinToMultipleResults(){let e=Object.keys(this.rooms);Di.info("re-join all existing rooms",{testResultIds:e}),e.forEach(t=>{var n;let r=this.rooms[t];(n=this.emitJoinRoom)==null||n.call(this,t,r)})}joinRoom(e,t){this.rooms[e]=t}leaveRoom(e){delete this.rooms[e]}addSocketHandlers(){let e=(t,r)=>{let n="websocket";try{n=this._socket.io.engine.transport.name}catch{}Di.error(`Error in SocketService websocket _${t}_ socket ${this._socket.id} is ${this.url} over ${n}. Reconnect attempts ${this.attempts}. Error is: ${r==null?void 0:r.message}`)};this._socket.on("reconnect_attempt",t=>{if(e("reconnect_attempt",{message:"reconnect attempt",attempt:t}),this.attempts++,this.attempts===vE&&!this.isAllowedWS&&(this._socket.io.opts.transports=["polling"],this._socket.io.opts.upgrade=!1),this.attempts>=wE)throw new Error(`Can't connect to Testim Servers.
|
|
217
217
|
Action required: Please allow opening a websockets connection to ${fe} in your firewall/proxy`)}),this._socket.on("connect_error",t=>{e("connect_error",t)}),this._socket.on("connect_timeout",t=>{e("connect_timeout",t)}),this._socket.on("error",t=>{e("error",t)}),this._socket.on("reconnect_error",t=>{this.prevErr&&this.prevErr.type===t.type||(this.prevErr=t,e("reconnect_error",t))}),this._socket.on("reconnect",()=>{Di.info("reconnect to socket and re-join to rooms"),this.joinToMultipleResults()}),this._socket.on("connect",()=>{var t;this.attempts=0,this.isAllowedWS===void 0&&(this.isAllowedWS=this._socket.io.engine.transport&&this._socket.io.engine.transport.name==="websocket"),(t=this.onConnect)==null||t.call(this)})}initNewSocket(e,t){let r={query:{projectId:e},requestTimeout:kh,transports:["websocket"],upgrade:!1,forceNew:!0,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};return new Promise(n=>{this.url=`${fe}/${t}`,this._socket=Yu.connect(this.url,r),this.addSocketHandlers(),this._socket.on("connect",n),this._socket.open()})}init(e,t){let r={query:{projectId:e},requestTimeout:kh,transports:["websocket"],upgrade:!1,rejectUnauthorized:process.env.NODE_TLS_REJECT_UNAUTHORIZED!=="0",...global.caFileContent&&{ca:global.caFileContent},...global.proxyUri&&{agent:new global.ProxyAgent(global.proxyUri)}};this.url=`${fe}/${t}`,this._socket=Yu.connect(this.url,r),this.addSocketHandlers()}emitPromise(e,t){let r={},n=()=>new Promise((o,i)=>{this._socket.emit(e,t,a=>a!=null&&a.success?o():(r[e]=t,i(new Error("bad ack"))))});return this.emitPromiseQueue=(this.emitPromiseQueue||Promise.resolve()).then(()=>(0,_h.default)(()=>ce(n(),SE),{retries:200,minTimeout:3e3,factor:1})).finally(()=>{Object.keys(r).length>0&&Di.error("Bad acknowledge from socket emit",{errorneousEvents:r})}),this.emitPromiseQueue}}});var Oh={};G(Oh,{remoteStepServiceSocketIO:()=>EE});var Qu,EE,Lh=w(()=>{"use strict";Xu();Qu=class extends gs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"remoteStep"),this.listeners={}}emitJoinRoom(t){return this.emitPromise("remoteStep:join",{resultId:t})}emitLeaveRoom(t){return this.emitPromise("remoteStep:leave",{resultId:t})}async joinToRemoteStep(t){this.rooms[t]||(this.joinRoom(t),await this.emitJoinRoom(t))}listenToRemoteStep(t,r){this.listeners[t]&&(this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=n=>{n.resultId===t&&n.remoteStep&&n.remoteStep.status==="pending"&&r(n.remoteStep)},this._socket.on("remoteStep:saved",this.listeners[t])}async unlistenToRemoteStep(t){this.listeners[t]&&(this.leaveRoom(t),this._socket.off("remoteStep:saved",this.listeners[t]),delete this.listeners[t],await this.emitLeaveRoom(t))}},EE=new Qu});var Dh={};G(Dh,{remoteStepService:()=>hs});var Zu,Ln,ep,hs,Mi=w(()=>{"use strict";Li();ae();pe();({REMOTE_STEP_SAVED:Zu}=Ct),ep=class{async init(e){L.flags.useNewWSCLI.isEnabled()||(Ln=(await Promise.resolve().then(()=>(Lh(),Oh))).remoteStepServiceSocketIO,Ln.init(e))}joinToRemoteStep(e){return L.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:remoteStep`,{resultId:e},[Zu]):Ln.joinToRemoteStep(e)}listenToRemoteStep(e,t){if(L.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:remoteStep`,[Zu],r=>r.resultId===e&&r.remoteStep&&r.remoteStep.status==="pending",r=>t(r.remoteStep));return}Ln.listenToRemoteStep(e,t)}unlistenToRemoteStep(e){return L.flags.useNewWSCLI.isEnabled()?(vt.removeFilter(`${e}:remoteStep`,[Zu]),Promise.resolve()):Ln.unlistenToRemoteStep(e)}},hs=new ep});var tp,Pr,Mh=w(()=>{"use strict";Xu();tp=class extends gs{constructor(){super(...arguments);this.listeners={}}init(t){super.init(t,"testResult"),this.listeners={}}listenToTestResult(t,r,n){this.listeners[t]&&(this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t]),this.listeners[t]=o=>{o.resultId===t&&o.testId===r&&n(o.testResult)},this._socket.on("testResult:updated",this.listeners[t])}emitJoinRoom(t,r){return this.emitPromise("testResult:join",{resultId:t,testId:r})}async joinToTestResult(t,r){this.rooms[t]||this.joinRoom(t,r),await this.emitJoinRoom(t,r)}emitLeaveRoom(t,r){return this.emitPromise("testResult:leave",{resultId:t,testId:r})}leaveTestResult(t,r){return this.listeners[t]?(this.leaveRoom(t),this._socket.off("testResult:updated",this.listeners[t]),delete this.listeners[t],this.emitLeaveRoom(t,r)):Promise.resolve()}getSocket(){return this._socket}},Pr=new tp});var Uh={};G(Uh,{testResultService:()=>Lt});var Nh,rp,Lt,Ni=w(()=>{"use strict";Nh=require("events");Li();ae();pe();Mh();rp=class extends Nh.EventEmitter{init(e){if(L.flags.useNewWSCLI.isEnabled()){vt.onConnect=()=>this.emit("socket-connected");return}Pr.init(e),Pr.onConnect=()=>this.emit("socket-connected")}joinToTestResult(e,t){return L.flags.useNewWSCLI.isEnabled()?vt.addFilter(`${e}:testResult`,{resultId:e,testId:t},[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED]):Pr.joinToTestResult(e,t)}async leaveTestResult(e,t){if(L.flags.useNewWSCLI.isEnabled()){vt.removeFilter(`${e}:testResult`,[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED]);return}await Pr.leaveTestResult(e,t)}listenToTestResult(e,t,r){if(L.flags.useNewWSCLI.isEnabled()){vt.listenTo(`${e}:testResult`,[Ct.TEST_RESULT_UPDATED,Ct.TEST_RESULT_CREATED],n=>n.resultId===e&&n.testId===t,n=>r(n));return}Pr.listenToTestResult(e,t,r)}getSocket(){if(!L.flags.useNewWSCLI.isEnabled())return Pr.getSocket()}},Lt=new rp});var Bh,jh,$h,Se,IE,Wh,Fh,Ui,Vh=w(()=>{"use strict";Bh=S(require("lodash"));F();ue();$e();ts();Qe();he();Ch();jh=S(require("p-retry")),$h=require("url");j();ei();cs();ae();Mi();Ni();Se=C("test-run-handler"),IE=3,Wh=20*1e3,Fh=s=>JSON.stringify(s).length<Wh,Ui=class{constructor(e,t,r,n,o,i){this._executionId=e;this._executionName=t;this._options=n;this._branch=o;this._testRunStatus=i;this.seleniumPerfStats=new Ir;this._totalRetryCount=1;this._retryCount=1;this._timeoutRetryCount=1;this._seleniumHubRetryCount=2;this.clearTestResultFinished=Promise.resolve(void 0);var l,c;this._testStatus=r.testStatus,this._testId=r.testId,this._testName=r.name,this._testResultId=r.resultId,this._baseUrl=n.baseUrl||r.baseUrl||r.testConfig.baseUrl,this._nativeApp=r.nativeApp,this._overrideTestConfig=r.overrideTestConfig||r.testConfig,this._overrideTestConfigId=(l=r.overrideTestConfig)==null?void 0:l.id,this._maxRetryCount=n.retries,this._remoteRunId=n.remoteRunId;let a=!((c=r.runConfig)!=null&&c.isMobileWeb)&&n.browser;this._runConfig=a?qs(n.browser,n.saucelabs,n.browserstack):r.runConfig}async waitForExecutionStartedFinished(){return await this._testRunStatus.waitForExecutionStartedFinished(),await this.clearTestResultFinished}get testStatus(){return this._testStatus}get runMode(){return this._options.mode}get runConfig(){return this._runConfig}get testResultId(){return this._testResultId}get baseUrl(){return this._baseUrl}set baseUrl(e){this._baseUrl=e}get executionId(){return this._executionId}get executionName(){return this._executionName}getSauceLabsAppPath(e,t){var r,n;return this.isAppFromDevice?null:t?e.includes("us-west-1")?t.usSauceLabsAppId:t.euSauceLabsAppId:e.includes("us-west-1")?(r=this._nativeApp)==null?void 0:r.usSauceLabsAppId:(n=this._nativeApp)==null?void 0:n.euSauceLabsAppId}getAppPath(e,t){var r;return this.isAppFromDevice?null:t?t[e]:(r=this._nativeApp)==null?void 0:r[e]}getAppPathByGridType(e,t,r){var n,o,i,a;return this.isAppFromDevice?null:r?(o=(n=r.gridData)==null?void 0:n[e])==null?void 0:o[t]:this._nativeApp&&"gridData"in this._nativeApp?(a=(i=this._nativeApp.gridData)==null?void 0:i[e])==null?void 0:a[t]:null}get appPackageNameOrBundleId(){return this.nativeAppMetadata?this.nativeAppMetadata.id||this.nativeAppMetadata.packageName:null}get androidActivityWait(){var r;let e=(r=this.nativeAppMetadata)==null?void 0:r.activity;if(!e)return null;let t=e.split(".").pop();return e.replace(t,"*")}get isAppFromDevice(){return Gs(this._nativeApp)}get isAppForIosVirtualDevice(){var t;let e=(t=this._options.gridData)==null?void 0:t.type;return Wr(this._nativeApp,e)}get getAppSource(){if(this._nativeApp)return this.isAppFromDevice?fo.FROM_DEVICE:fo.FROM_LIBRARY}get downloadableAppPublicLink(){return this._nativeApp&&"filePath"in this._nativeApp?`${fe}/storage${this._nativeApp.filePath}?access_token=${this._options.authData.token}`:null}get mobileApp(){return this._nativeApp}set nativeApp(e){this._nativeApp=e}get nativeAppMetadata(){return this._nativeApp?"appMetadata"in this._nativeApp?this._nativeApp.appMetadata:this._nativeApp:null}get branch(){return this._branch}get sfdcCredential(){return this._options.sfdcCredential}get remoteRunId(){return this._remoteRunId}get overrideTestConfig(){return this._overrideTestConfig}get overrideTestConfigId(){return this._overrideTestConfigId}markClearBrowser(){this.clearBrowser=!0}async getRunRequestParams(){var r,n;let t={tokenV3:await Pt(),refreshToken:Mo(),projectId:this._options.project,executionId:this._executionId,executionName:this._executionName,testId:this._testId,resultId:this._testResultId,baseUrl:this._baseUrl,branch:this._branch,servicesUrl:md,remoteRunId:this.remoteRunId,previousTestResultId:this.previousTestResultId,testRetryCount:this.retryCount,...this._options.shouldMonitorPerformance&&{shouldMonitorPerformance:!0},...this._options.company&&{companyId:this._options.company.companyId,storageBaseUrl:this._options.company.storageBaseUrl,storageType:this._options.company.storageType,planType:this._options.company.planType,isPOC:this._options.company.isPOC,isStartUp:this._options.company.isStartUp},...this._options.collectCodeCoverage&&{codeCoverageUrlFilter:this._options.codeCoverageUrlFilter||`${this.baseUrl}*`},...this._options.disableMockNetwork&&{disableMockNetwork:this._options.disableMockNetwork},...this._options.lightweightMode&&{lightweightMode:this._options.lightweightMode},...this.clearBrowser&&{clearBrowser:!0},...this._options.localRCASaver&&{localRCASaver:this._options.localRCASaver},...this.sfdcCredential&&{sfdcCredential:this.sfdcCredential},userAccessKey:await No()};if(this._options.disableMockNetwork&&Tt("user-disable-mock"),t.lightweightMode&&((r=this._options.lightweightMode)!=null&&r.general)){Object.assign(t,{company:this._options.company});let o=this.runData,i=Fh(o);Object.assign(t.lightweightMode,{isRunDataSentInUrl:i});let a=JSON.stringify(o).length,l=this.testId;i?(Object.assign(t,{runData:o}),Se.info(`Run data sent as URL param, test id: ${l} run data length: ${a}`)):Se.warn(`Run data is too big to be sent as a URL param. Test id: ${l}, run data size: ${a} (limit: ${Wh} characters)`),Object.assign(t,{isLocalRun:Boolean(this._options.useLocalChromeDriver||this._options.useChromeLauncher)})}if((n=this._options.lightweightMode)!=null&&n.preloadTests&&this._options.useChromeLauncher){let o=await hn(this._options);Object.assign(t,{preloadedTest:o[t.testId]})}return t}async getRunTestUrl(){let e=await this.getRunRequestParams(),t=`https://run.testim.io/?params=${encodeURIComponent(JSON.stringify(e))}`;return Se.info(`Test (${this.testId}) run URL length: ${t.length}`),t}set sessionId(e){this._sessionId=e}get sessionId(){return this._sessionId}get testId(){return this._testId}get testName(){return this._testName}get runParams(){var e;return((e=this._options.runParams)==null?void 0:e[this._testResultId])||{}}get runData(){return{userParamsData:this.runParams,overrideTestConfigId:this._overrideTestConfigId||null}}async clearTestResult(){var o;let e={...this.runData,...this._options.mockNetworkRules&&{mockNetworkRules:this._options.mockNetworkRules}},t=this._timeoutRetryCount>1||this._retryCount>1;if((o=this._options.lightweightMode)!=null&&o.disableResults&&!t&&Fh(e))return;let r=async()=>{try{return await Sl(this._options.project,this._testId,this._testResultId,e)}catch(i){return Se.error("failed to upload run data artifact (runner)",{err:i}),""}},n=async()=>{let i=await r();return await this._testRunStatus.waitForExecutionStartedFinished(),wl(this._options.project,this._testResultId,this._testId,{name:this._testName,resultId:this._testResultId,status:"pending",retryCount:this._retryCount,runDataUrl:i,runData:i?void 0:e,testRetryKey:this.retryKey})};return this.clearTestResultFinished=n(),this.clearTestResultFinished}hasMoreRetries(){return this._retryCount<this._maxRetryCount}isSeleniumHubNoMatchSessionError(e){return/Session \[([a-zA-Z0-9]+)\] not available and is not among the last \d+ terminated sessions/.test(e)}decreaseSeleniumHubRetry(){this._seleniumHubRetryCount-=1}get ignoreSeleniumHubError(){return this._seleniumHubRetryCount===0}get retryKey(){return`${this._retryCount}:${this._timeoutRetryCount}`}startNewRetry(){return this._retryCount++,this._timeoutRetryCount=1,this.onRetry()}async runTestUsingCDP(e){N("runTestUsingCDP");let{targetInfos:t}=await e.cdpCommand("Target.getTargets")||{targetInfos:[]},r=["Testim Editor","Tricentis Testim Editor"],{targetId:n}=t.find(i=>i.type==="background_page"&&r.includes(i.title))||{},{targetId:o}=t.find(i=>i.type==="page")||{};if(!n)throw new Error("Tricentis Testim extension not found");if(!o)throw new Error("AUT target not found");try{N("before Target.attachToTarget");let[i,a]=await Promise.all([e.cdpCommand("Target.attachToTarget",{targetId:n,flatten:!0}),this.getRunRequestParams()]),{sessionId:l}=i||{};N("before Runtime.evaluate"),await(0,jh.default)(async()=>{let{result:d}=await e.cdpCommand("Runtime.evaluate",{expression:"typeof runTestimTest !== 'undefined'",returnByValue:!0},l);if(!d.value)throw new Error("runTestimTest not available on global scope")},{retries:100,minTimeout:30,factor:1}),N("after wait for runTestimTest function");let{result:c}=await e.cdpCommand("Runtime.evaluate",{expression:`runTestimTest(${JSON.stringify(a)})`,awaitPromise:!0,returnByValue:!0},l);if(c.subtype==="error")throw new Error(c.description);return N("after Runtime.evaluate"),c.value}catch(i){throw Se.error("error running test using CDP",{err:i}),new Error("Error running test using CDP")}}isRetryKeyMismatch(e){return e.testRetryKey&&e.testRetryKey!==this.retryKey}validateRunConfig(){let{baseUrl:e,runConfig:{browserValue:t}}=this;if(e&&t==="safari"){let r;try{r=new $h.URL(e)}catch{return}let{username:n,password:o}=r;if(n||o)throw new Error("Basic authentication in URL is not supported in Safari")}}onStarted(e){return new Promise(t=>{let r=!1,n=o=>{if(!r){if(this.isRetryKeyMismatch(o)){Se.warn(`ignoring result update for on started due to retry key mismatch, got ${o.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}["running","completed"].includes(o.status)&&(o.resultId=this.testResultId,o.status==="completed"&&!this.isSeleniumHubNoMatchSessionError(o.reason)&&(Se.info("setting _wasCompletedOnStartedCheck to true",{testResult:o,resultId:this.testResultId,testId:this.testId,testRetryKey:this.retryKey}),this._wasCompletedOnStartedCheck=o),r=!0,t(o))}};if(this._options.disableSockets){let o=Date.now()+e,i=async()=>{if(Date.now()>o)return;let{testId:a,testResultId:l,branch:c,_options:{project:d}}=this;try{let m=await Sr(a,l,d,c);n(m),r||setTimeout(i,3e3)}catch(m){Se.error("failed to check if done",{err:m}),setTimeout(i,3e3)}};setTimeout(i,3e3)}else Lt.listenToTestResult(this._testResultId,this._testId,n)})}async checkViaRestAPIIfTestStarted(){let{testId:e,testResultId:t,_options:{project:r},branch:n}=this;try{let o=await Sr(e,t,r,n),i=["running","completed"];if(i.includes(o.status))return Se.info(`get status: ${o.status} after not get test started status`,{testId:e,testResultId:t,branch:n}),o;throw Se.error(`test not start test status: ${o.status} (expected [${i.join(", ")}])`,{testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}catch(o){throw Se.error("failed to get test result after test start timeout",{err:o,testId:e,testResultId:t,branch:n}),new Error(Ue.TEST_START_TIMEOUT_MSG)}}async onCompletedCleanup(){if(!this._options.disableSockets)return await Lt.leaveTestResult(this._testResultId,this._testId)}async onCompleted(){let e;try{let t=await new Promise(r=>{if(this._wasCompletedOnStartedCheck&&!this.isRetryKeyMismatch(this._wasCompletedOnStartedCheck)){Se.info("test was already completed in on started check",{resultId:this.testResultId,testId:this.testId}),r(this._wasCompletedOnStartedCheck);return}this._options.disableSockets||Lt.listenToTestResult(this._testResultId,this._testId,i=>{if(this.isRetryKeyMismatch(i)){Se.warn(`ignoring result update for on completed due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId});return}i.status==="completed"&&(i.resultId=this._testResultId,r(i))});let n=this._options.disableSockets?0:Math.floor(1e4+Math.random()*5e3),o=this._options.disableSockets?0:Math.floor(6e4+Math.random()*15e3);if(e=Bh.debounce(async()=>{try{let i=await Sr(this._testId,this._testResultId,this._options.project,this.branch);return this.isRetryKeyMismatch(i)?(Se.warn(`ignoring result update for on completed (in reconnect) due to retry key mismatch, got ${i.testRetryKey}, current is ${this.retryKey}`,{resultId:this.testResultId,testId:this.testId}),!1):(i==null?void 0:i.status)==="completed"?(Se.info("Socket reconnected - Test complete",{testId:this._testId,resultId:this._testResultId,projectId:this._options.project}),i.resultId=this._testResultId,r(i),!0):!1}catch(i){return Se.warn("Error while trying to check status on socket connect",i),!1}},n,{maxWait:o}),!this._options.disableSockets)Lt.on("socket-connected",async()=>{try{await Lt.joinToTestResult(this._testResultId,this.testId)}catch(i){Se.error("failed joining to test result updates after socket reconnected",{error:i})}e==null||e()});else{let i=()=>{setTimeout(async()=>{try{let{isComplete:a}=await ul(this._testResultId,this._options.project,this.retryKey);a?await e()||(Se.warn("onConnected returned false even though isComplete was true"),i()):i()}catch(a){Se.error("failed to check is complete",{err:a}),i()}},3e3)};i()}});return await this.onCompletedCleanup(),t}finally{e&&!this._options.disableSockets&&Lt.off("socket-connected",e)}}listenToRemoteStep(e){hs.listenToRemoteStep(this.testResultId,t=>{xh(this._options,e,t,this.testResultId)})}hasMoreTimeoutRetries(){let e=this._options.disableTimeoutRetry?1:IE;return this._timeoutRetryCount<e}decreaseRetryCount(){this._retryCount--,this._totalRetryCount--}startNewTimeoutRetry(){return this._timeoutRetryCount++,this.onRetry()}get retryCount(){return this._retryCount}get previousTestResultId(){return this._previousTestResultId}isAllowReportTestResultRetries(){var e,t,r;return Boolean((r=(t=(e=this._options.company)==null?void 0:e.activePlan)==null?void 0:t.premiumFeatures)==null?void 0:r.allowReportTestResultRetries)}async onRetry(){var e;this._previousTestResultId=this.testResultId,this.isAllowReportTestResultRetries()&&(this._totalRetryCount++,this._originalTestResultId||=this._previousTestResultId,this._testResultId=se(),!((e=this._options.lightweightMode)!=null&&e.onlyTestIdsNoSuite)&&await this._testRunStatus.addRetryTestResult({retryCount:this._totalRetryCount,executionId:this._executionId,projectId:this._options.project,newResultId:this._testResultId,originalTestResultId:this._originalTestResultId,previousTestResultId:this._previousTestResultId}))}}});var Fi,Gh=w(()=>{"use strict";Vh();Fi=class{constructor(e,t,r,n,o,i){this.pendingAppUploads=new Map;let a=new Set(r.map(l=>{var c;return(c=l.nativeApp)==null?void 0:c.appId}).filter(Boolean));!n.appId&&a.size>1&&a.forEach(l=>{this.pendingAppUploads.set(l,{isUploaded:!1,uploadedAppId:""})}),n.appId&&this.pendingAppUploads.set(n.appId,{isUploaded:!1,uploadedAppId:""}),this._waitingTests=r.map(l=>new Ui(e,t,l,n,o,i))}stop(){this._waitingTests=[]}getNext(){let e=this._waitingTests.shift();if(e)return e}hasMoreTests(){return Boolean(this._waitingTests.length)}}});var RE,AE,xE,Dn,sp=w(()=>{"use strict";ns();is();j();RE=C("worker-utils"),AE=async(s,e,t)=>{e&&await pu(s,t)},xE=async(s,e,t)=>{await du(s,e,t)},Dn=async(s,e,t,r,n,o)=>{RE.info("releasing player",{hasPlayer:Boolean(o)});try{await(o==null?void 0:o.onDone())}finally{n==="mongo"&&await AE(s,e,t),n==="redis"&&await xE(s,r,t)}}});function DE(s,e,t,r){return{testId:s,reason:r,name:e,resultId:t,success:!1}}var $i,Kh,ji,ip,Jh,St,Hh,qh,np,Mn,CE,op,PE,cr,kE,Bi,_E,zh,OE,LE,ME,lt,Nn=w(()=>{"use strict";$i=S(require("ms")),Kh=S(require("lodash")),ji=S(require("p-retry")),ip=S(require("dayjs")),Jh=S(require("dayjs/plugin/duration"));F();$e();ns();is();he();j();sp();Ot();ii();pe();Mi();Ni();Qe();Ge();ae();K();ip.default.extend(Jh.default);St=C("base-worker"),{GET_BROWSER_TIMEOUT_MSG:Hh,TEST_START_TIMEOUT_MSG:qh,TEST_COMPLETE_TIMEOUT_MSG:np}=Ue,{SETUP_TIMEOUT:Mn,NETWORK_ERROR:CE,GRID_ERROR:op,BROWSER_CLOSED:PE,SELENIUM_ERROR:cr,UNKNOWN_ERROR:kE,MOBILE_SESSION_ERROR:Bi}=$s,_E=(0,$i.default)("1s"),zh=(0,$i.default)("600s"),OE=(0,$i.default)("180s"),LE=1;ME=["fullLogs","locatorStats","stepsResults","setupStepResult","sharedStepClasses","revisionStatus","revisions","testData","exportsGlobal"],lt=class{constructor(e,t,r,n,o,i,a,l,c=!0){this.executionQueue=e;this.options=t;this.customExtensionLocalLocation=r;this.executionId=n;this.onTestStarted=o;this.onTestCompleted=i;this.onGridSlot=a;this.onTestIgnored=l;this.releaseSlotOnTestFinished=c;this.id=lt.getWorkerId();this.lambdatestService=new re;this.baseUrl=t.baseUrl,this.testRunTimeout=t.timeout,this.userData=t.userData}static getWorkerId(){return LE++}async getGridSlot(e,t){let r=await cg(e,t.executionId,this.options,this.id);return this.onGridSlot(t.testResultId,r),r}async getSlotOnce(e){let{browserValue:t}=this.testRunConfig;return Z.onGetSlot(this.id,t||"chrome"),await this.getGridSlot(t,e)}initPlayer(e){throw new Ds(!0)}async getBrowserOnce(e,t,r,n){throw new Ds(!0)}async runTestOnce(e,t){return e.sessionId=t.getSessionId(),St.info("Test run started",{testId:e.testId,resultId:e.testResultId,seleniumSession:t.getSessionId()}),await e.clearTestResult()}handleQuarantine(e){if(!Xe({testStatus:e.testStatus},this.options))return;let t={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus};return this.onTestIgnored(this.id,t),t}handleMobileTest(e){var n,o;if(((n=this.options.gridData)==null?void 0:n.mode)==="local")return;let t=Vr(L,(o=this.options.gridData)==null?void 0:o.type)&&e.isAppFromDevice&&!this.options.appId,r=e.isAppForIosVirtualDevice;if(t||r){let i={name:e.testName,testId:e.testId,resultId:e.testResultId,runnerStatus:de.SKIPPED,testStatus:e.testStatus,mobile:{isAppFromDevice:t,isAppForIosVirtualDevice:r}};return this.onTestIgnored(this.id,i),i}}setSessionTimeout(){var e;if(this.options.mode===ee.APPIUM){let t=(e=this.options.gridData)==null?void 0:e.type;return t===_.BROWSERSTACK?Math.max(zh,this.options.getSessionTimeout):L.flags.increaseTDCRequestTimeout.isEnabled()&&(t===_.TESTIM_TDC||t===_.TESTIM_HEADSPIN)?Math.max(zh,this.options.getSessionTimeout):Math.max(OE,this.options.getSessionTimeout)}return Math.max(this.lambdatestService.getSessionTimeout||0,this.options.getSessionTimeout)}async getGridInfoAndSlotFromMongoGridQueue(e){let t=0;return{gridInfo:await(0,ji.default)(async()=>{let n=Date.now();try{return await ce(this.getSlotOnce(e),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(o){return t++,await this.handleGetSlotError(o,n)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:t}}async getSlotFromCompanySlotManager(){let e=0;return{slotId:await(0,ji.default)(async()=>{var n,o;let r=Date.now();try{let i=(n=this.options.company)==null?void 0:n.companyId,a=(o=this.options.projectData)==null?void 0:o.projectId;return await ce(dg(i,a,this.id),this.options.getBrowserTimeout,Ue.GET_BROWSER_TIMEOUT_MSG)}catch(i){return e++,await this.handleGetSlotError(i,r)}},{retries:this.options.getBrowserRetries-1,minTimeout:0,factor:1}),failedAttemptsCount:e}}async handleGetSlotError(e,t){let r={testId:this.testId,testResultId:this.testResultId,executionId:this.executionId};throw e instanceof Yt?St.info("could not get grid slot due to concurrency issue",r):St.error("error getting grid slot",{error:e,...r}),await oe(this.options.getBrowserTimeout-(Date.now()-t)),e}async handleGetSlot(e){if(this.options.slotService==="redis"){let{failedAttemptsCount:t}=await this.getSlotFromCompanySlotManager();return{gridInfo:this.options.gridData,failedAttemptsCount:t}}return await this.getGridInfoAndSlotFromMongoGridQueue(e)}async getTestPlayer(e,t){var o;let r=(o=this.userData)==null?void 0:o.projectId,n;try{N("before getSlotOnce retries");let{failedAttemptsCount:i,gridInfo:a={}}=await this.handleGetSlot(e);N("before getBrowserOnce retries");let l=this.options.getBrowserRetries-i;if(!l)throw new Error("No free browser slots in desired grid");let c=0;n=await(0,ji.default)(async()=>{let d=Date.now(),m=this.initPlayer(e);try{let u=await lg(this.options,a,this.testRunConfig,this.lambdatestService,{maxRetries:l,currentRetry:c+1});this.options.gridData.provider=u.provider,this.options.gridData.host=u.host,this.options.gridData.failedGetBrowserAttempts=c;let f=this.setSessionTimeout();N("before getBrowserOnce");let h=await ce(this.getBrowserOnce(e,t,m,u),f,Ue.GET_BROWSER_TIMEOUT_MSG);return N("after getBrowserOnce"),Z.onGetBrowserSuccess(this.id,r),m||h}catch(u){let f={...a,failedGetBrowserAttempts:c,id:this.options.gridData.gridId},h=this.options.mode===ee.APPIUM?"device":"browser";throw St.error(`error getting ${h} from grid`,{error:u,testId:this.testId,testResultId:this.testResultId,executionId:this.executionId,grid:f,publicIps:this.options.publicIps}),Z.onGetBrowserFailure(this.id,r,++c),m.onDone(),!(u instanceof Rt)&&this.options.mode!==ee.APPIUM&&await oe(this.options.getBrowserTimeout-(Date.now()-d)),u}},{retries:l-1,minTimeout:0,factor:1}),N("after getBrowserOnce retries")}catch(i){throw await Dn(this.id,this.releaseSlotOnTestFinished,r,this.options.company.companyId,this.options.slotService,n),[Rt,Br].some(a=>i instanceof a)?i:i instanceof ze?new fr(i,op):new fr(i,cr)}return n}async runTest(e,t,r){var d;N("inside runTest");let n=(d=this.userData)==null?void 0:d.projectId,o=this.handleQuarantine(e);if(o)return o;let i=Hs(this.options)&&this.handleMobileTest(e);if(i)return i;N("before runTest onTestStarted");let a=e.getAppSource,l=await this.onTestStarted(this.id,e.testId,e.testResultId,r,e.retryKey,a);e.baseUrl=l.config.baseUrl;let c=await this.getTestPlayer(e,t);try{return this.userData.loginData.token=await Pt(),await this.runTestOnce(e,c)}finally{await Dn(this.id,this.releaseSlotOnTestFinished,n,this.options.company.companyId,this.options.slotService,c)}}async runTestCleanup(){}async onQueueCompleted(){}run(){var u,f;let e=()=>process.nextTick(()=>this.run()),t=async(h,g,y)=>{var D,U,H;if(Xe(h,this.options)||Vr(L,(D=this.options.gridData)==null?void 0:D.type)&&g.isAppFromDevice&&!this.options.appId||g.isAppForIosVirtualDevice)return e();let T=g.sessionId,R=q=>y==null?void 0:y.message.includes(q),b=y&&y instanceof fr,v=y&&(R(qh)||R(np)),O=L.flags.retryOnSeleniumHubError.isEnabled()&&!!h.reason&&g.isSeleniumHubNoMatchSessionError(h.reason)&&!g.ignoreSeleniumHubError,W=v&&g.hasMoreTimeoutRetries(),A=g.hasMoreRetries()&&!b&&!v,E=!h.success&&(A||W||O);try{let q=g.retryKey;h.testRetryKey=q;let Y=g.getAppSource;if(await this.onTestCompleted(this.id,this.testId,h,T,E,Y),this.executionQueue.hasMoreTests()&&!((U=this.options.lightweightMode)!=null&&U.general)&&await oe(_E),await this.runTestCleanup(),E){if(W&&await g.startNewTimeoutRetry(),O){St.info(`retry test id: ${this.testId} name: ${this.testName} again due to selenium hub error`,{testId:g.testId,retryReason:h.reason,testName:this.testName,testResultId:this.testResultId,executionId:this.executionId});let me=(H=this.options.projectData)==null?void 0:H.projectId,pt=g.testResultId,It=g.testId;await Wo(me,pt,It,{show:!1}),g.decreaseSeleniumHubRetry(),g.decreaseRetryCount(),await g.startNewRetry()}return A&&!O&&!W&&await g.startNewRetry(),St.info(`retry test id: ${this.testId} name: ${this.testName} again`,{testId:this.testId,testName:this.testName,isTimeoutErrors:v,testRetryKey:q,totalRetries:g._totalRetryCount}),this.testResultId=g.testResultId,await d(g,E)}return await e()}catch(q){if(q instanceof Jt)return;St.error("failed to process test result",{error:q}),e();return}},r=()=>`Due to network connectivity issues, Testim CLI has been unable to connect to the grid.
|
|
218
218
|
Please make sure the CLI has stable access to the internet. ${Tc()?"(Internal: network connectivity test failed)":""}`,n=h=>{let{DEVICE_OS_VERSION_TOO_LOW:g,APP_NOT_EXIST_ON_DEVICE:y,APP_NEVER_STARTED:T,TIMEOUT_ERROR:R,SAUCELABS_APP_IS_NOT_INSTALLED:b}=Ac,v=h instanceof Error?h.message:h;return v.replace(/(Visit\s+)?(https?:\/\/\S+)?(\s+)?(for\s+troubleshooting(\.)?)?/gi,""),v.includes(Hh)||v.includes(R)?{errorType:Mn,reason:"timeout while getting device"}:v.includes(y)||v.includes(b)?{errorType:Bi,reason:"app doesn't exist on device"}:v.includes(T)?{errorType:Bi,reason:"app never started, check app permission or app activity"}:v.includes(g)?{errorType:Bi,reason:"Unable to install app: DeviceOSVersionTooLow"}:{errorType:Bi,reason:v}},o=(h,g)=>{let y=this.options.mode===ee.APPIUM?"device":"browser";if(!g&&L.flags.errorMessageOnBadNetwork.isEnabled())return{errorType:CE,reason:r()};let T=h instanceof Error?h.message:h;if(T.includes(Hh))return{errorType:Mn,reason:`Test couldn't get ${y}`};if(T.includes(qh))return{errorType:Mn,reason:"Test couldn't be started"};if(T.includes(np)){if(!this.testRunTimeout)return{errorType:Mn,reason:"Test timeout reached: test is too long"};let R=ip.default.duration({milliseconds:this.testRunTimeout}),b=Math.floor(R.asMinutes()),v=R.asSeconds(),I=b>0?` ${b} min`:"",x=v>0?` ${v} sec`:"";return{errorType:Mn,reason:`Test timeout reached (timeout:${I}${x}): test is too long`}}if(h instanceof fr&&h.type){if(h.type===op)return{errorType:op,reason:`Test couldn't get ${y} from grid - ${h.message}`};if(h.type===cr)return{errorType:cr,reason:`Failed to create new session - ${h.message}`}}return"type"in h&&h.type===PE?{errorType:cr,reason:`Session terminated, this is often caused to connection
|
|
219
|
-
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(h.message)||/Couldn't connect to selenium server/.test(h.message)?{errorType:cr,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(h.message)?{errorType:cr,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(h.message)?{errorType:cr,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(h.message)?{errorType:cr,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:kE,reason:T}},i=async(h,g)=>{var v;let y=await bc();!y&&L.flags.warnOnBadNetwork.isEnabled()&&console.warn(r()),St.warn("error on run",{err:h});let T=(v=this.userData)==null?void 0:v.projectId,{errorType:R,reason:b}=this.options.mode===ee.APPIUM?n(h):o(h,y);Wo(T,this.testResultId,this.testId,{status:js.COMPLETED,success:!1,reason:b,errorType:R,testRetryKey:g.retryKey,setupStepResult:{status:js.COMPLETED,success:!1,reason:b,errorType:R}},g.remoteRunId),await t(DE(this.testId,this.testName,this.testResultId,b),g,h)},a=async(h,g)=>{var v;let y=this.testId,T=this.testResultId,R=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!T||!R||!b)return St.warn("Test failed. Not enough data to recover results via API",{err:h}),i(h,g);try{let I=await Sr(y,T,R,b);if(St.warn("Test failed. Got results via API",{err:h,testResult:Kh.default.omit(I,ME),resultId:T}),I&&I.status===js.COMPLETED&&!h.message.includes(np))return await t(I,g);throw h}catch(I){return I!==h&&St.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:R,branch:b,err:I}),i(h,g)}},l=this.options.disableSockets||((u=this.options.lightweightMode)==null?void 0:u.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),c=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep),d=async(h,g)=>{try{await Promise.all([!c&&hs.joinToRemoteStep(this.testResultId),!l&&Lt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==ee.APPIUM&&h.validateRunConfig();let y=await this.runTest(h,this.customExtensionLocalLocation,g),T=await t(y,h);return N("After onRunComplete"),T}catch(y){return a(y,h)}finally{c||hs.unlistenToRemoteStep(this.testResultId)}},m=this.executionQueue.getNext();return m?(this.testId=m.testId,this.testName=m.testName,this.testResultId=m.testResultId,this.overrideTestConfigId=m.overrideTestConfigId,this.testRunConfig=m.runConfig,this.branch=m.branch,d(m)):this.onQueueCompleted()}}});var ap,Yh,ys,cp=w(()=>{"use strict";F();ap=S(require("p-retry"));F();j();K();Yh=C("window-utils"),ys=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(o,i){let a=document.elementFromPoint(o,i);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(o){let i=o.message.includes("method IWebBrowser2::Navigate2() failed");if(o.seleniumStack&&i&&n>0)return Yh.warn("selenium navigation failed. retrying to navigate",{err:o}),await oe(1500),r(n-1);throw!o.seleniumStack&&i&&Yh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:o}),o}};return Promise.race([r(),oe(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),oe(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,n=document.documentElement,o=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),i=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:o,width:i}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await oe(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof location<"u")r=location;else if(typeof window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&r.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&r.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new Rt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,ap.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,ap.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var lp,bs,up=w(()=>{"use strict";j();lp=C("cookies-utils"),bs=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw lp.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw lp.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw lp.error("failed to remove cookie",{err:t}),t}}}});var pp,Wi,Xh=w(()=>{"use strict";pp=S(require("p-retry")),Wi=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[o,i]=await(0,pp.default)(n,{retries:e,minTimeout:t,factor:1}),a=i?i.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),o=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[i,a]=await(0,pp.default)(o,{retries:t,minTimeout:r,factor:1}),l=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(l.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function Qh(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let o=s.offset||{top:0,left:0};if(o.top*=r,o.left*=r,!s.elementRect)return NE.warn("missing elementRect",ey.omit(s,"image")),{};let{elementRect:i}=s,a=await Ts.default.read(Buffer.from(n[1],"base64")),l=i.left*r+o.left*r,c=i.top*r+o.top*r,d=i.width*r,m=i.height*r;l<0&&(d+=l,d=d<0?0:d,l=0),c<0&&(m+=c,m=m<0?0:m,c=0);let u=a.bitmap.width,f=a.bitmap.height;if(l+d>u&&(d=u-l),c+m>f&&(m=f-c),m<=0||d<=0)throw new dp("height or width is equal or lower than zero");return{elementImage:await a.crop(l,c,d,m).getBase64Async(Ts.default.MIME_PNG)}}async function UE(s,e){let t=await Ts.default.read(s.width,s.height);for(let n of e){let o=n.image.match(/^data:[^;]*;base64,(.*)$/),i=await Ts.default.read(Buffer.from(o[1],"base64"));await new Promise((a,l)=>{t.composite(i,n.position.left,n.position.top,c=>{if(c){l(c);return}a()})})}return await t.getBase64Async(Ts.default.MIME_PNG)}function FE(s,e){return UE(s,e)}async function BE(){}async function jE(s){function e(o){let i=s[o];return typeof i=="string"&&i.startsWith("data")}async function t(o){let i=await BE(s[o]);return{key:o,url:i}}let r=await ie(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(o=>[o.key,o.url]));return Object.assign(s,n)}function Zh(s,e){return e||=1,s||={left:0,top:0,width:0,height:0},{left:e*Math.round(s.left),top:e*Math.round(s.top),width:e*Math.round(s.width),height:e*Math.round(s.height),pixelRatio:e}}var ey,Ts,NE,dp,Vi,ty=w(()=>{"use strict";ey=S(require("lodash"));F();Ts=S(require("jimp"));j();NE=C("image-capture-utils"),dp=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Vi=class{constructor(e,t,r){this.windowUtils=t;this.screenshotUtils=r}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){let t=await this.screenshotUtils.takeScreenshot(),r=await Qh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:Zh(e.elementRect,t.devicePixelRatio)})}async takeElementImage(e){let t=await this.screenshotUtils.takeElementScreenshot({ELEMENT:e});return{elementImage:typeof t=="string"?t:t.image}}async takeArea(e){let t=await this.screenshotUtils.takeScreenshot();return jE({screenImage:t.image,absoluteScreenHighlight:Zh(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>oe(250),o=Boolean(e);async function i(u,f){o?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await Qh({elementRect:f},h);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(u){let f=[];for(let h of u){let g=await i(h.scrollPos,h.cropData);f.push(g)}return f}function l(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),T=f.height,R=Array.from({length:Math.ceil(h/g)},(v,I)=>({scrollX:Math.min(I*g,h-g),cropX:I*g-Math.min(I*g,h-g),cropW:g-(I*g-Math.min(I*g,h-g))})),b=Array.from({length:Math.ceil(y/T)},(v,I)=>({scrollY:Math.min(I*T,y-T),cropY:I*T-Math.min(I*T,y-T),cropH:T-(I*T-Math.min(I*T,y-T))}));return R.flatMap(v=>b.map(I=>({scrollPos:{x:v.scrollX,y:I.scrollY},cropData:{top:I.cropY,left:v.cropX,width:v.cropW,height:I.cropH}})))}async function c(u,f){let h=await t.getCurrentScrollPosition(),g=l(u,f),y=await a(g);return await t.scrollToPosition(h),FE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var ry,sy,Gi,Hi,ny=w(()=>{"use strict";ry=S(require("p-retry")),sy=S(require("semver"));F();j();cp();Xh();ty();we();Gi=C("tab-service"),Hi=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let n=this.getTabInfo(e,r);return`tabId=${r}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),Gi.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,o={}){let i=await this.getTabDetails(t,e,o),a=se();function l(c){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!c.getMainTabInfo(e):i.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:i.url,title:i.title,favIconUrl:i.favIconUrl,order:r,from:this.getTabInfo(e,i.openerTabId),isMain:l(this),openerStepId:n},a}async addTab(e,t,r,n,o={}){let i=await this.buildTabInfo(e,t,r,n,o),a=new ys(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Vi(t,a,new Wi(t,this.driver,{takeScreenshots:o.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(i=>r[i]).filter(i=>!i.isMain);if(n.length===1)return this._utils[n[0].infoId];let o=Object.keys(e).map(i=>e[i]).filter(i=>this.isSameTab(e,t,i));return o.length>0?this._utils[o[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(o=>o===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:o}=Q(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),l=n(i),c=n(a),d=r.map(m=>o.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=Q();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let o=this.getAllTabInfos(e),i=Object.keys(o).map(c=>o[c].url);if(this.exactUrlMatch(t,r,i))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,i,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,i,l)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(o=>o.value));try{let[o,i,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:o,url:i,isMainTab:a}}catch(o){Gi.error("failed to get url or title",{err:o})}}catch(n){Gi.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await oe(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let r=this.getAllTabInfos(e);if(Object.keys(r).find(i=>r[i].openerStepId===t))return;if(this.pendingTabs[e]){Gi.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let o=await this.waitForTabToOpen(e);await this.addNewTab(e,o,this.pendingTabs[e]),this.addFrameHandler(o),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,ry.default)(()=>{if(this.pendingTabs[e]===t)throw new Error("awaiting pending tabs")},{retries:5,factor:1,minTimeout:500,maxTimeout:500}).catch(()=>{})}async isMainTabIncognito(){return!1}isInvalidStepVersion(e){let t=sy.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(o=>o.type==="locate"&&!o.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var l,c;let{tabMatcher:r,commonConstants:n}=Q();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((l=t.useCurrentTab)!=null&&l.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let o=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,o);let i=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,i);if(!a)throw await this.tryToAddTab(e),new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var mp,qi,fp=w(()=>{"use strict";mp=class{select(){return console.log(`
|
|
219
|
+
problems between the Testim CLI and the grid running the test. Please check your network connection.`}:/SeleniumError: connect ECONNREFUSED/.test(h.message)||/Couldn't connect to selenium server/.test(h.message)?{errorType:cr,reason:"Failed to connect to the grid, please check if the grid is accessible from your network"}:/terminated due to FORWARDING_TO_NODE_FAILED/.test(h.message)?{errorType:cr,reason:"Session terminated, it is likely that the grid is out of memory or not responding, please try to rerun the test"}:/terminated due to PROXY_REREGISTRATION/.test(h.message)?{errorType:cr,reason:"Session terminated, it is likely that the grid is not responding, please try to rerun the test"}:/forwarding the new session cannot find : Capabilities/.test(h.message)?{errorType:cr,reason:`Session could not be created, please check that the ${y} you requested is supported in your plan`}:{errorType:kE,reason:T}},i=async(h,g)=>{var v;let y=await bc();!y&&L.flags.warnOnBadNetwork.isEnabled()&&console.warn(r()),St.warn("error on run",{err:h});let T=(v=this.userData)==null?void 0:v.projectId,{errorType:R,reason:b}=this.options.mode===ee.APPIUM?n(h):o(h,y);Wo(T,this.testResultId,this.testId,{status:js.COMPLETED,success:!1,reason:b,errorType:R,testRetryKey:g.retryKey,setupStepResult:{status:js.COMPLETED,success:!1,reason:b,errorType:R}},g.remoteRunId),await t(DE(this.testId,this.testName,this.testResultId,b),g,h)},a=async(h,g)=>{var v;let y=this.testId,T=this.testResultId,R=(v=this.userData)==null?void 0:v.projectId,b=this.branch;if(!y||!T||!R||!b)return St.warn("Test failed. Not enough data to recover results via API",{err:h}),i(h,g);try{let I=await Sr(y,T,R,b);if(St.warn("Test failed. Got results via API",{err:h,testResult:Kh.default.omit(I,ME),resultId:T}),I&&I.status===js.COMPLETED&&!h.message.includes(np))return await t(I,g);throw h}catch(I){return I!==h&&St.error("Failed to fetch test results from server",{testId:y,resultId:T,projectId:R,branch:b,err:I}),i(h,g)}},l=this.options.disableSockets||((u=this.options.lightweightMode)==null?void 0:u.disableResults)&&(this.options.useChromeLauncher||this.options.mode!=="extension"),c=this.options.disableSockets||((f=this.options.lightweightMode)==null?void 0:f.disableRemoteStep),d=async(h,g)=>{try{await Promise.all([!c&&hs.joinToRemoteStep(this.testResultId),!l&&Lt.joinToTestResult(this.testResultId,this.testId)]),this.options.mode!==ee.APPIUM&&h.validateRunConfig();let y=await this.runTest(h,this.customExtensionLocalLocation,g),T=await t(y,h);return N("After onRunComplete"),T}catch(y){return a(y,h)}finally{c||hs.unlistenToRemoteStep(this.testResultId)}},m=this.executionQueue.getNext();return m?(this.testId=m.testId,this.testName=m.testName,this.testResultId=m.testResultId,this.overrideTestConfigId=m.overrideTestConfigId,this.testRunConfig=m.runConfig,this.branch=m.branch,d(m)):this.onQueueCompleted()}}});var ap,Yh,ys,cp=w(()=>{"use strict";F();ap=S(require("p-retry"));F();j();K();Yh=C("window-utils"),ys=class{constructor(e,t){this.id=e;this.driver=t}async getElementFromPoint(e,t){function r(o,i){let a=document.elementFromPoint(o,i);return{testimId:a?a.getAttribute("testim_dom_element_id"):null,tagName:a?a.tagName:null}}let{value:n}=await this.driver.executeJS(r,e,t);return n}getLocation(){return this.driver.getUrl()}async stopListeningToScroll(){}async resumeListeningToScroll(){}scrollToPosition(e){return this.driver.scroll(e.x,e.y)}scrollToPositionWithoutAnimation(e){function t(r){return"scrollBehavior"in document.documentElement.style?window.scrollTo({left:r.x,top:r.y,behavior:"instant"}):window.scrollTo(r.x,r.y)}return this.driver.executeJS(t,e)}async getCurrentScrollPosition(){function e(){return{x:window.scrollX,y:window.scrollY}}let{value:t}=await this.driver.executeJS(e);return t}navigate(e,t=15e3){let r=async(n=3)=>{try{await this.driver.url(e)}catch(o){let i=o.message.includes("method IWebBrowser2::Navigate2() failed");if(o.seleniumStack&&i&&n>0)return Yh.warn("selenium navigation failed. retrying to navigate",{err:o}),await oe(1500),r(n-1);throw!o.seleniumStack&&i&&Yh.warn("selenium navigation failed. Due to wdio7 the error is unhandled",{err:o}),o}};return Promise.race([r(),oe(t)])}reloadTab(e=15e3){return Promise.race([this.driver.reloadTab(),oe(e)])}async getZoom(){function e(){return{zoomLevel:window.outerWidth/window.innerWidth}}let{value:t}=await this.driver.executeJS(e);return t}getViewportSize(){return this.driver.getViewportSize()}maximizeWithoutValidation(){return this.driver.maximizeWithoutValidation()}async getFullPageSize(){function e(){let r=document.body,n=document.documentElement,o=Math.max(r.scrollHeight,r.offsetHeight,n.clientHeight,n.scrollHeight,n.offsetHeight),i=Math.max(r.scrollWidth,r.offsetWidth,n.clientWidth,n.scrollWidth,n.offsetWidth);return{height:o,width:i}}let{value:t}=await this.driver.executeJS(e);return t}async extractToNewWindow(){}async checkSize(e){await oe(1e3);let t=await this.getViewportSize();if(t.width!==e.width||t.height!==e.height)throw Object.assign(new Error("checkSize failed"),{actualSize:t,expectedSize:e});return{actualSize:t,expectedSize:e}}async setViewportSize(e){return await this.driver.setViewportSize(e.width,e.height),await this.checkSize(e)}async validatePageIsAvailable(){function e(){let r;if(typeof location<"u")r=location;else if(typeof window<"u"&&window.location!==void 0)r=window.location;else return!1;return r.href!=="chrome-error://chromewebdata/"&&r.href!=="safari-resource:/ErrorPage.html"&&r.href.indexOf("res://ieframe.dll/http_404.htm")!==0&&r.href.indexOf("ms-appx-web://microsoft.microsoftedge/assets/errorpages/")!==0}if(!(await this.driver.executeJS(e)).value)throw new Rt("validatePageIsAvailable:PageNotAvailableError")}focusTab(){return this.driver.switchTab(this.id)}quit(){}async getOsAndBrowser(){let e=await(0,ap.default)(()=>this.driver.getBrowserAndOS(),{retries:3,factor:1});return{uaBrowserName:e.browser,uaOs:e.os,userAgent:e.userAgent,browserVersion:e.browserVersion}}getUserAgentInfo(){return(0,ap.default)(()=>this.driver.getUserAgentInfo(),{retries:3,factor:1})}}});var lp,bs,up=w(()=>{"use strict";j();lp=C("cookies-utils"),bs=class{constructor(e){this.driver=e}async set(e){let t=e.domain;!e.hostOnly&&t&&!t.startsWith(".")&&(t=`.${t}`);try{return await this.driver.setCookie(e.name,e.value,t,e.httpOnly,e.secure,e.path,e.expirationDate)}catch(r){throw lp.error("failed to set cookie",{err:r}),r}}async get(e){try{return await this.driver.getCookie(e.name)}catch(t){throw lp.error("failed to get cookie",{err:t}),t}}async remove(e){try{return await this.driver.deleteCookie(e.name)}catch(t){throw lp.error("failed to remove cookie",{err:t}),t}}}});var pp,Wi,Xh=w(()=>{"use strict";pp=S(require("p-retry")),Wi=class{constructor(e,t,r={takeScreenshots:!0}){this.tabId=e;this.driver=t;this.options=r;this.screencastHandler=void 0}base64AddPadding(e){return e+Array((4-e.length%4)%4+1).join("=")}shouldTakeScreenshots(){return typeof this.options.takeScreenshots!="boolean"?!0:this.options.takeScreenshots}async takeScreenshot(){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let e=3,t=2e3,r=this.currentDevicePixelRatio||this.getDevicePixelRatio(),n=()=>Promise.all([r,this.driver.takeScreenshot()]),[o,i]=await(0,pp.default)(n,{retries:e,minTimeout:t,factor:1}),a=i?i.value:"";return{image:`data:image/png;base64,${this.base64AddPadding(a.replace(/[\r\n]/g,""))}`,devicePixelRatio:o}}async takeElementScreenshot(e){if(!this.shouldTakeScreenshots())return{devicePixelRatio:1,image:""};let t=3,r=2e3,n=this.currentDevicePixelRatio?Promise.resolve(this.currentDevicePixelRatio):this.getDevicePixelRatio(),o=()=>Promise.all([n,this.driver.takeElementScreenshot(e)]),[i,a]=await(0,pp.default)(o,{retries:t,minTimeout:r,factor:1}),l=a||"";return{image:`data:image/png;base64,${this.base64AddPadding(l.replace(/[\r\n]/g,""))}`,devicePixelRatio:i}}async getDevicePixelRatio(){function e(){try{return window.devicePixelRatio}catch{return 1}}let{value:t}=await this.driver.executeJS(e);return t}forcePixelRatio(e=1){return this.currentDevicePixelRatio=e,Promise.resolve()}getCurrentDevicePixelRatio(){return this.currentDevicePixelRatio}}});async function Qh(s,e){let t=e.image||e,r=e.devicePixelRatio;if(!t)throw new Error("Failed to get image");let n=t.match(/^data:[^;]*;base64,(.*)$/);if(!n)throw new Error("Image is not in base64 format");let o=s.offset||{top:0,left:0};if(o.top*=r,o.left*=r,!s.elementRect)return NE.warn("missing elementRect",ey.omit(s,"image")),{};let{elementRect:i}=s,a=await Ts.default.read(Buffer.from(n[1],"base64")),l=i.left*r+o.left*r,c=i.top*r+o.top*r,d=i.width*r,m=i.height*r;l<0&&(d+=l,d=d<0?0:d,l=0),c<0&&(m+=c,m=m<0?0:m,c=0);let u=a.bitmap.width,f=a.bitmap.height;if(l+d>u&&(d=u-l),c+m>f&&(m=f-c),m<=0||d<=0)throw new dp("height or width is equal or lower than zero");return{elementImage:await a.crop(l,c,d,m).getBase64Async(Ts.default.MIME_PNG)}}async function UE(s,e){let t=await Ts.default.read(s.width,s.height);for(let n of e){let o=n.image.match(/^data:[^;]*;base64,(.*)$/),i=await Ts.default.read(Buffer.from(o[1],"base64"));await new Promise((a,l)=>{t.composite(i,n.position.left,n.position.top,c=>{if(c){l(c);return}a()})})}return await t.getBase64Async(Ts.default.MIME_PNG)}function FE(s,e){return UE(s,e)}async function BE(){}async function jE(s){function e(o){let i=s[o];return typeof i=="string"&&i.startsWith("data")}async function t(o){let i=await BE(s[o]);return{key:o,url:i}}let r=await ie(Object.keys(s).filter(e),t),n=Object.fromEntries(r.map(o=>[o.key,o.url]));return Object.assign(s,n)}function Zh(s,e){return e||=1,s||={left:0,top:0,width:0,height:0},{left:e*Math.round(s.left),top:e*Math.round(s.top),width:e*Math.round(s.width),height:e*Math.round(s.height),pixelRatio:e}}var ey,Ts,NE,dp,Vi,ty=w(()=>{"use strict";ey=S(require("lodash"));F();Ts=S(require("jimp"));j();NE=C("image-capture-utils"),dp=class extends Error{constructor(){super(...arguments);this.rectIsOutsideOfImageError=!0}};Vi=class{constructor(e,t,r){this.windowUtils=t;this.screenshotUtils=r}async takeViewPortImage(){let e=await this.screenshotUtils.takeScreenshot();return typeof e=="string"?e:e.image}takeImageForComparison(){return this.takeViewPortImage()}async takeAreaDataUrl(e){let t=await this.screenshotUtils.takeScreenshot(),r=await Qh(e,t);return Object.assign(r,{screenImage:t.image,absoluteScreenHighlight:Zh(e.elementRect,t.devicePixelRatio)})}async takeElementImage(e){let t=await this.screenshotUtils.takeElementScreenshot({ELEMENT:e});return{elementImage:typeof t=="string"?t:t.image}}async takeArea(e){let t=await this.screenshotUtils.takeScreenshot();return jE({screenImage:t.image,absoluteScreenHighlight:Zh(e.elementRect,t.devicePixelRatio)})}forcePixelRatio(e){return this.screenshotUtils.forcePixelRatio(e)}getCurrentDevicePixelRatio(){return this.screenshotUtils.getCurrentDevicePixelRatio()}async takeStitchedDataUrl(e){let{windowUtils:t,screenshotUtils:r}=this,n=()=>oe(250),o=Boolean(e);async function i(u,f){o?await t.scrollToPositionWithoutAnimation(u):await t.scrollToPosition(u),await n();let h=await r.takeScreenshot(),g=await Qh({elementRect:f},h);return{position:{left:u.x+f.left,top:u.y+f.top},size:{width:f.width,height:f.height},image:g.elementImage}}async function a(u){let f=[];for(let h of u){let g=await i(h.scrollPos,h.cropData);f.push(g)}return f}function l(u,f){let h=Math.max(u.width,f.width),g=f.width,y=Math.max(u.height,f.height),T=f.height,R=Array.from({length:Math.ceil(h/g)},(v,I)=>({scrollX:Math.min(I*g,h-g),cropX:I*g-Math.min(I*g,h-g),cropW:g-(I*g-Math.min(I*g,h-g))})),b=Array.from({length:Math.ceil(y/T)},(v,I)=>({scrollY:Math.min(I*T,y-T),cropY:I*T-Math.min(I*T,y-T),cropH:T-(I*T-Math.min(I*T,y-T))}));return R.flatMap(v=>b.map(I=>({scrollPos:{x:v.scrollX,y:I.scrollY},cropData:{top:I.cropY,left:v.cropX,width:v.cropW,height:I.cropH}})))}async function c(u,f){let h=await t.getCurrentScrollPosition(),g=l(u,f),y=await a(g);return await t.scrollToPosition(h),FE(u,y)}let[d,m]=await Promise.all([t.getFullPageSize(),t.getViewportSize()]);return await c(d,m)}}});var ry,sy,Gi,Hi,ny=w(()=>{"use strict";ry=S(require("p-retry")),sy=S(require("semver"));F();j();cp();Xh();ty();we();Gi=C("tab-service"),Hi=class{constructor(e){this.driver=e;this.sessionTabs={};this._utils={};this.pendingTabs={};this.addedTabs={}}on(){}tabCount(e){if(this.sessionTabs[e])return this.sessionTabs[e].tabCount}getAllOpenTabIds(e){let t=this.getAllTabInfos(e);return Object.keys(t).filter(r=>!t[r].isClosed)}getActiveTabInfo(e){return this.sessionTabs[e].lastActiveTabInfo}getAllTabIds(e){return Object.keys(this.getAllTabInfos(e)).map(t=>t)}isSessionTab(e,t){return this.getAllTabIds(e).includes(t)}createSesion(e){this.sessionTabs[e]||(this.addedTabs[e]=new Set,this.sessionTabs[e]={pendingInfos:{},tabCount:0,tabInfos:{}})}setAddFrameHandlerCallBack(e){this.addFrameHandler=e}getAllTabInfoStrings(e){return this.getAllTabIds(e).map(r=>{let n=this.getTabInfo(e,r);return`tabId=${r}, url=${n.url}, order=${n.order}, isMain=${n.isMain}, openerStepId=${n.openerStepId}, isClosed=${n.isClosed}, currentUrl: ${n.currentUrl}, lastUpdatedUrl: ${n.lastUpdatedUrl}`})}getAllTabInfos(e){return this.sessionTabs[e].tabInfos}async addNewTab(e,t,r,n){if(!this.addedTabs[e].has(t))return this.addedTabs[e].add(t),Gi.info(`Adding a new tab sessionId: ${e}, tabId: ${t}, openerId: ${r}`),this.addTab(e,t,this.sessionTabs[e].tabCount++,r,n)}addOpenerStepId(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r}addOpenerStep(e,t,r){this.sessionTabs[e].tabInfos[t].openerStepId=r.id,this.sessionTabs[e].tabInfos[t].openerOriginalStepId=r.originalStepId}fixMissingMainTab(e){if(this.getMainTabInfo(e))return;let r=this.getAllTabInfos(e);Object.keys(r).length!==0&&(Object.values(this.getAllTabInfos(e))[0].isMain=!0)}async buildTabInfo(e,t,r,n,o={}){let i=await this.getTabDetails(t,e,o),a=se();function l(c){return o.checkForMainTab?i.isMainTab:!i.isMainTab||i.isMainTab==="unknown"?!c.getMainTabInfo(e):i.isMainTab}return this.sessionTabs[e].tabInfos[t]={infoId:a,url:i.url,title:i.title,favIconUrl:i.favIconUrl,order:r,from:this.getTabInfo(e,i.openerTabId),isMain:l(this),openerStepId:n},a}async addTab(e,t,r,n,o={}){let i=await this.buildTabInfo(e,t,r,n,o),a=new ys(t,this.driver);this._utils[i]={attachDebugger:()=>Promise.resolve(),detachDebugger:()=>Promise.resolve(),onDebuggerDetached:()=>{},tabId:t,domUtils:{getDOM:async()=>{}},windowUtils:a,imageCaptureUtils:new Vi(t,a,new Wi(t,this.driver,{takeScreenshots:o.takeScreenshots}))}}getTabUtilsByTabIdAndSessionId(e,t){let r=this.sessionTabs[e].tabInfos[t];return this._utils[r.infoId]}getTabUtilsByTabId(e){let t=Object.keys(this._utils).find(r=>this._utils[r].tabId===e);return this._utils[t]}getTabInfo(e,t){return this.sessionTabs[e].tabInfos[t]}getTabUtils(e,t){if(!t)return this.getMainTabUtils(e);if(this._utils[t.infoId])return this._utils[t.infoId];if(t.isMain)return this.getMainTabUtils(e);let r=this.getAllTabInfos(e),n=Object.keys(r).map(i=>r[i]).filter(i=>!i.isMain);if(n.length===1)return this._utils[n[0].infoId];let o=Object.keys(e).map(i=>e[i]).filter(i=>this.isSameTab(e,t,i));return o.length>0?this._utils[o[0].infoId]:this.getMainTabUtils(e)}exactUrlMatch(e,t,r){let n=r.filter(o=>o===t.url);return!!((e.url===t.url||e.currentUrl===t.url||e.currentUrl&&e.currentUrl===t.currentUrl)&&n.length===1)}singleExactMatchForParts(e,t,r,n){let{urlUtils:o}=Q(),i=o.urlBreaker(e.url||e.currentUrl),a=o.urlBreaker(t.url||t.currentUrl),l=n(i),c=n(a),d=r.map(m=>o.urlBreaker(m)).map(m=>n(m)).filter(m=>m===l);return l===c&&d.length===1}isSameTab(e,t,r){let{tabMatcher:n}=Q();if(n){let c=this.getAllTabInfos(e),d=Object.keys(c).map(m=>c[m]);return n.isSameTab(d,t,r)}if(t.isMain&&r.isMain||t.openerStepId&&r.openerStepId&&t.openerStepId===r.openerStepId)return!0;let o=this.getAllTabInfos(e),i=Object.keys(o).map(c=>o[c].url);if(this.exactUrlMatch(t,r,i))return!0;let a=c=>`${c.domain}/${c.path.join("/")}`;if(this.singleExactMatchForParts(t,r,i,a))return!0;let l=c=>`${c.domain}/${c.path.join("/")}#${c.hash}`;return!!(this.singleExactMatchForParts(t,r,i,l)||t.order===r.order)}getMainTabInfo(e){let t=this.getAllTabInfos(e);return Object.keys(t).map(r=>t[r]).find(r=>r.isMain)}getMainTabUtils(e){let t=this.getMainTabInfo(e);return t?this.getTabUtils(e,t):{}}removeTabInfo(e,t){let n=this.getAllTabInfos(e)[t];delete this.sessionTabs[e].tabInfos[t],delete this._utils[n.infoId],this.sessionTabs[e].tabCount--}getMainTabId(e){let t=this.getAllTabInfos(e);return Object.keys(t).find(r=>t[r].isMain)}async isMainTabExists(e){let t=this.getMainTabId(e);return Boolean(t)}clearAllTabs(e){let t=this.getAllTabInfos(e);this.sessionTabs[e].tabCount=0,Object.keys(t).forEach(r=>this.removeTabInfo(e,r))}clearNonMainTabs(e){let t=this.getAllTabInfos(e);Object.keys(t).filter(r=>!t[r].isMain).forEach(r=>this.removeTabInfo(e,r)),this.sessionTabs[e].tabCount=1}async switchTab(e,t,{forceSwitch:r=!1}={}){let n=this.sessionTabs[t]?this.sessionTabs[t].tabCount:1;if(typeof n=="number"&&n>1||r)return this.driver.switchTab(e)}async getTabDetails(e,t,r={}){try{if(await this.switchTab(e,t,r),r.skipLoadInfo)return{title:"",url:""};let n=Promise.resolve("unknown");r.checkForMainTab&&(n=this.driver.executeJS("return window.__isMainTestimTab").then(o=>o.value));try{let[o,i,a]=await Promise.all([this.driver.getTitle(),this.driver.getUrl(),n]);return{title:o,url:i,isMainTab:a}}catch(o){Gi.error("failed to get url or title",{err:o})}}catch(n){Gi.error("failed to switch to tab",{tabId:e,err:n})}return{title:"",url:""}}async getUnregisteredTabId(e){return(await this.driver.getTabIds()).find(r=>!this.getAllTabIds(e).includes(r))}async waitForTabToOpen(e){let t=await this.getUnregisteredTabId(e);return t||(await oe(500),await this.waitForTabToOpen(e))}async tryToAddTab(e){if(this.pendingTabs[e])return;let t=await this.getUnregisteredTabId(e);t&&(await this.addNewTab(e,t),await this.addFrameHandler(t),Object.assign(this.sessionTabs[e],{currentTab:null}))}async addNewPopup(e,t){let r=this.getAllTabInfos(e);if(Object.keys(r).find(i=>r[i].openerStepId===t))return;if(this.pendingTabs[e]){Gi.info(`overriding opener step id from ${this.pendingTabs[e]} to ${t}`),this.pendingTabs[e]=t;return}this.pendingTabs[e]=t;let o=await this.waitForTabToOpen(e);await this.addNewTab(e,o,this.pendingTabs[e]),this.addFrameHandler(o),delete this.pendingTabs[e],Object.assign(this.sessionTabs[e],{currentTab:null})}async waitToPendingTabs(e,t){if(t)return(0,ry.default)(()=>{if(this.pendingTabs[e]===t)throw new Error("awaiting pending tabs")},{retries:5,factor:1,minTimeout:500,maxTimeout:500}).catch(()=>{})}async isMainTabIncognito(){return!1}isInvalidStepVersion(e){let t=sy.lt(e._version||e.version,"1.2.0"),r=!!e.parameterValues,n=r&&e.parameterValues.some(o=>o.type==="locate"&&!o.frameLocators);return t&&(!r||n)}async getTabIdByTabInfo(e,t){var l,c;let{tabMatcher:r,commonConstants:n}=Q();if(this.isInvalidStepVersion(t))throw Object.assign(new Error(""),{success:!1,shouldRetry:!1,errorType:n.stepResult.INVALID_TEST_VERSION});if((l=t.useCurrentTab)!=null&&l.call(t)){let d=await this.driver.getCurrentTabId();if(d)return d;let m=this.getMainTabId(e);if(m)return m;throw new Error("Current tab not found")}let o=(c=t.tabInfo)==null?void 0:c.openerStepId;await this.waitToPendingTabs(e,o),await this.tryToAddTab(e);let i=this.getAllTabIds(e).map(d=>({...this.getTabInfo(e,d),tabId:d})).filter(d=>!d.isClosed),a=r.matchTabs(t,i);if(!a)throw new Error("No tab ID found");if(this.sessionTabs[e].currentTab===a)return a;try{return await this.switchTab(a,e),Object.assign(this.sessionTabs[e],{currentTab:a}),a}catch(d){let m=["no such window","no window found","the window could not be found"];if(d.message&&m.some(u=>d.message.toLowerCase().includes(u)))return this.sessionTabs[e].tabCount--,this.sessionTabs[e].tabInfos[a].isClosed=!0,this.getTabIdByTabInfo(e,t);throw d}}}});var mp,qi,fp=w(()=>{"use strict";mp=class{select(){return console.log(`
|
|
220
220
|
internal error - cant use port selector in selenium!!!!
|
|
221
221
|
`),Promise.reject({reason:"cant use port selector in selenium!"})}prepare(){}handleLegacyDataCaching(){}},qi=new mp});var Un,zi,Ki=w(()=>{"use strict";up();F();we();Un={8:"\uE008",9:"\uE004",13:"\uE007",27:"\uE00C",33:"\uE00E",34:"\uE00F",35:"\uE010",36:"\uE011",45:"\uE016",112:"\uE031",113:"\uE032",114:"\uE033",115:"\uE034",116:"\uE035",117:"\uE036",118:"\uE037",119:"\uE038",120:"\uE039",121:"\uE03A",122:"\uE03B",123:"\uE03C"},zi=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=zs;this.getLinksFromUnescapeHTML=Ks;this.cookieUtils=new bs(this.driver)}get sessionPlayerInit(){return Q()}resetAbort(){this._abortedSteps.length=0}abort(e){this._abortedSteps.push(e)}get abortedSteps(){return this._abortedSteps}getClickOffset(e,t){let{utils:r,positionUtils:n}=this.sessionPlayerInit,o=n.calculateElementMiddlePoint(t);return e&&r.isWithinBounds(t.left,t.left+t.width,e.x)&&r.isWithinBounds(t.top,t.top+t.height,e.y)?{x:e.x-o.x,y:e.y-o.y}:{x:0,y:0}}async executeInAut(e,t){let{value:r}=await this.driver.executeJS(t);return r}extractTargetText(e){return this.driver.getTargetText(e)}extractText(e){return this.driver.getElementTextJS(e)}async markDynamicParent(e,t){await this.driver.markDynamicParent(e,t)}getCookie(e){return this.cookieUtils.get({name:e})}setCookie(e){return this.cookieUtils.set(e)}async getNextDynamicParent(e,t){let r=this.sessionPlayerInit.codeSnippets.getNextDynamicParent(t),{value:n}=await this.driver.executeJS(`return (function() { ${r} })();`);return n}}});function iy(s){class e{constructor(r,n){this.frameManager=r;this.LocateElementPlayer=n;this._cache={}}cacheResults(r,n){this._cache[r]=n}getResultsFromCache(r){return this._cache[r]}cacheFrameLocateResults(r){if(r!=null&&r.seleniumFrameElement&&r.frameLocateResultUrl){let n=oy(r.seleniumFrameElement);n&&this.cacheResults(n,r.frameLocateResultUrl)}}async foundFrameCallback(r,n,o){let{frameOffset:i,locatedElement:a}=r,{locatorBuilderUtils:l}=Q();if(l.isEmptyResult(a)){let u="got empty result in frame result, not rejected from locate element player";throw $E.error(u),new Error(u)}let c=await s.switchToLocatedFrame(a),d=oy(c.value),m=this.getResultsFromCache(d);return{url:"",frameId:-1,frameOffset:i,tabInfo:n.tabInfo,tabId:n.tabId,testimFrameId:o,testimFullFrameId:`${this.currentFrameHandler.testimFullFrameId}-${o}`,seleniumFrameElement:c.value,frameLocateResultUrl:m}}async locate(r,n,o,i,a,l){let c=new this.LocateElementPlayer(i);r.targetId=`frameLocator_${n}`;let d=await c.locate(r,o,r.targetId);d.isVisible=!0;let m=await c.handleLocateResult(d,l,r).catch(()=>{throw new Error("")}),{locatedElement:u}=i.data[r.targetId],h=(await s.getElementLocationWithPadding(u)).value||{top:0,left:0};m.frameOffset={top:o.frameOffset.top+h.top,left:o.frameOffset.left+h.left},c.addFrameDataToContext&&c.addFrameDataToContext(m.targetId,m.locateResult);let g=await this.foundFrameCallback(m,a,r.testimFrameId);return this.currentFrameHandler=g,g}async findFrame(r,n,o,i){let a=L.flags.enableFrameSwitchOptimization.isEnabled(),c=o.playback.resultsHandler.resultsByChronologicOrder.at(-1),d=1,m=c&&c.stepId===r.id&&c.results.length>d;if(a&&!m&&this.currentFrameHandler){let y=n.findIndex(T=>T.testimFrameId===this.currentFrameHandler.testimFrameId);if(y>-1){let T=n.slice(y+1),R=0;for(let b of T)R++,this.currentFrameHandler=await this.locate(b,R,this.currentFrameHandler,o,i,r);return this.currentFrameHandler}}let u=await i.getTopFrameHandler();u.frameOffset={top:0,left:0},await(a&&this.currentFrameHandler===u?this.currentFrameHandler:s.switchToTopFrame()),this.cacheFrameLocateResults(this.currentFrameHandler),this.currentFrameHandler=u;let h=0,g=u;for(let y of n)h++,g=await this.locate(y,h,g,o,i,r);return g}}return e}var $E,WE,oy,ay=w(()=>{"use strict";j();pe();we();Mr();$E=C("frame-locator"),WE="ELEMENT",oy=s=>s?s[WE]||s[Kt]:null});var Ji,gp=w(()=>{"use strict";ue();Ji=()=>{try{if(od)return!1;if(require("inspector").url())return!0}catch{}return!1}});var V,le=w(()=>{"use strict";we();V=class{constructor(e,t,r,n={},o=void 0,i=void 0,a={}){this.step=e;this.context=t;this.frameHandler=r;this.exportsGlobal=n;this.stepActionUtils=o;this.locateElementPlayer=i;this.exportsTest=a;this.frameId=0}get driver(){return this.stepActionUtils.driver}get sessionPlayerInit(){return Q()}async performAction(){throw new Error("not implemented")}getTarget(){let e=this.step.targetId||"targetId";return this.context.data[e]}async execute(){try{return{success:!0,...await this.performAction()}}catch(e){let t=e==null?void 0:e.message,r=e==null?void 0:e.displayMessage;return{success:!1,reason:t,exception:e,errorType:this.sessionPlayerInit.commonConstants.stepResult.ACTION_EXCEPTION,resultInfo:{exception:`selenium exception: ${t}`,error:r||t}}}}}});function GE(s,e,t,r){return s.opacity===0||s.isShadowed?!1:e===void 0||t===void 0?!0:L.flags.useClickimVisibilityChecks.isEnabled()?!1:r.isSafari()?L.flags.useSafariWebdriverVisibilityChecks.isEnabled():!0}function HE(s){return{getFrameIdByTestimFrameId(){},async setElementResultDataOnContext(e){let t=await s.getElement(e.locatedElement);e.seleniumElement=t.value},getElementRectangle(e){return s.getElementRect(e)},async getOffsets(e){return[e.frameOffset||{}]},htmlStringToDom(e,t){let n=new cy.DOMParser().parseFromString("<html><body></body></html>","text/html");return n.body.outerHTML=e,Object.assign(n,{TESTIM_URL:t,parsedUsingLinkedom:!0})},async isVisible(e,t,r,n,o,i,a){let{locatorBuilderUtils:l,codeSnippets:c,visibilityUtils:d,positionUtils:m}=Q();if(GE(n,d,m,s))return s.isVisible(e.seleniumElement);if(!e.seleniumElement)return{visible:!1,invisibleReason:"element not found"};try{await s.isVisible(e.seleniumElement)}catch{}if(!t||l.isEmptyResult(t))return{visible:!1,invisibleReason:"element not found"};let h=[m.calculateElementMiddlePoint(r),m.calculateClickPoint(n.clickOffset,r)].filter(Boolean),g=c.getVisibilityCode.getCompoundVisibilityInfoCode(e.locatedElement,h,!1,n),y;try{y=await s.execute(`return ${g}`)}catch(I){throw kr.error("failed to execute getVisibilityCode",{err:I}),I}let{value:T}=y||{},R=T.elementVisibilityInfo||VE,[b,v]=T.elementsFromPointResults||[null,null];return d.checkElementVisibility(R,n,v,b,a,t,!1)},async scrollToElement(e,t){let{codeSnippets:{scrollToElement:r}}=Q();await s.execute(r(t))}}}var cy,kr,VE,Fn,ly=w(()=>{"use strict";le();j();pe();we();cy=require("linkedom"),kr=C("locate-step-action"),VE={opacity:1,clientRects:{}};Fn=class extends V{execute(){return this.driver.getHTML(this.step)}static getUtils(e){return HE(e)}static getFrameIdByTestimFrameId(){throw kr.warn("Unplanned access to getFrameIdByTestimFrameId()"),new Error("Use .getUtils() instead")}static setElementResultDataOnContext(){throw kr.warn("Unplanned access to setElementResultDataOnContext()"),new Error("Use .getUtils() instead")}static getElementRectangle(){throw kr.warn("Unplanned access to getElementRectangle()"),new Error("Use .getUtils() instead")}static getOffsets(){throw kr.warn("Unplanned access to getOffsets()"),new Error("Use .getUtils() instead")}static htmlStringToDom(){throw kr.warn("Unplanned access to htmlStringToDom()"),new Error("Use .getUtils() instead")}static isVisible(){throw kr.warn("Unplanned access to isVisible()"),new Error("Use .getUtils() instead")}}});var uy={};G(uy,{scroll:()=>qE});var qE,py=w(()=>{"use strict";qE=function(s,e,t,r,n,o,i,a){function l(R,b){if(!b)return{success:!1};elementScrollTo(b,R.x,R.y);let v=b.scrollLeft,I=b.scrollTop;return{success:Math.abs(I-R.y)<1&&Math.abs(v-R.x)<1,actualX:v,actualY:I}}function c(R,b){if(!t)return{x:n,y:o};let v=getLocatedElement(b);if(r&&!v)return{x:R.scrollWidth,y:R.scrollHeight};if(!v)throw new Error("could not find target element");let I=v.getBoundingClientRect(),x=0,O=0,W=Math.max(window.innerHeight-(I.height+10),0),A=Math.max(window.innerWidth-(I.width+10),0);return x=a?R.scrollTop+I.top-Math.min(o,W):R.scrollTop,O=i?R.scrollLeft+I.left-Math.min(n,A):R.scrollLeft,{x:Math.round(O),y:Math.round(x)}}let d=!s,m=d?document.scrollingElement||document.documentElement:getLocatedElement(s);if(!m)throw new Error("could not find target to scroll on");let u={top:m.scrollTop,left:m.scrollLeft},f=c(m,e),h=l(f,m);d&&!document.scrollingElement&&!h.success&&u.top===m.scrollTop&&u.left===m.scrollLeft&&(m=document.body,f=c(m,e),h=l(f,m));let g=h.actualX,y=h.actualY,T=getLocatedElement(e);if(t&&r&&!T)return{success:!1,expectedPosition:f};if(t){if(!T)throw new Error("could not find target to scroll to");let R=T.getBoundingClientRect();g=R.left,y=R.top}return{success:h.success,actualX:g,actualY:y}}});var Yi,dy=w(()=>{"use strict";le();Yi=class extends V{getFailureString(e,t,r,n,o){if(!e.isScrollToElement)return`Scrolling limit reached. Expected:(y: ${r}, x: ${t}); Actual:(y:${o}, x: ${n})`;let i="Scrolling limit reached";return e.shouldScrollTop&&(i+=`. Expected top margin: ${r}, actual: ${o}`),e.shouldScrollLeft&&(i+=`. Expected left margin: ${t}, actual: ${n}`),i}async scroll(e,t,r){let{codeSnippets:n,commonConstants:{stepResult:o}}=this.sessionPlayerInit,i=Math.round(Number(t.isScrollToElement?t.marginTop:t.y)),a=Math.round(Number(t.isScrollToElement?t.marginLeft:t.x)),l=this.driver.isFirefox()?function(m,u,f){m.scrollTo(u,f)}:function(m,u,f){m.scrollTop=f,m.scrollLeft=u},{scroll:c}=await Promise.resolve().then(()=>(py(),uy)),d=`
|
|
222
222
|
const getLocatedElement = ${n.getLocatedElementCode};
|
|
@@ -405,7 +405,7 @@ Please make sure the CLI has stable access to the internet. ${Tc()?"(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 la.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 la.error("failed to set input file",{err:n}),n}}async uploadFiles(t,r){for(let n of t)await this.driver.elementIdValue(De(r.seleniumElement),n)}async performAction(){let t=this.getTarget(),r=L.flags.overrideAzureStorageUrl.isEnabled(),n=L.flags.downloadToBase64.isEnabled(),{sessionPlayerInit:o,context:i,step:a,stepActionUtils:l,driver:c}=this,d=await o.utils.addTokenToFileUrls(i.project.id,a.fileUrls,l.testimServicesApi,r,la);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 h=await Ut(f);return{name:u,url:`data:${h.type};base64,${Buffer.from(h.body).toString("base64")}`}}))),c.isSafari()||c.isFirefox()||c.isEdgeChromium()){await this.driver.executeJS(`
|
|
406
406
|
const getLocatedElement = ${this.sessionPlayerInit.codeSnippets.getLocatedElementCode};
|
|
407
407
|
const downloadAndUploadFile = ${cI()};
|
|
408
|
-
return downloadAndUploadFile.apply(null, arguments);`,t.locatedElement,d);return}let m=await Ky(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var pa,da,Xy=w(()=>{"use strict";pa=require("url");le();da=class extends V{async updateBaseUrl(e){let t=new pa.URL(e),r=new pa.URL(this.context.recordedBaseUrl),n=new pa.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 ma,Qy=w(()=>{"use strict";le();F();ma=class extends V{async performAction(){await oe(this.step.durationMS||0)}}});var fa,Zy=w(()=>{"use strict";le();fa=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var $n,eb=w(()=>{"use strict";le();$n=class extends V{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(r,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t,apiCallAsync:r}=this.sessionPlayerInit;return typeof r=="function"&&r.length===2?r(t,e):new Promise(n=>{t(e,n)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var ga,tb=w(()=>{"use strict";le();ga=class extends V{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var rb,yp,bp,sb=w(()=>{"use strict";rb=S(require("@applitools/spec-driver-webdriverio"));to();we();yp=class{constructor(){let{EyeSdkBuilder:e}=Q(),t=ed["@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:rb.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=Q(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},bp=new yp});var ob,nb,Wn,ib=w(()=>{"use strict";ob=S(require("lodash"));le();j();sb();nb=C("pixel-validation-step-action"),Wn=class extends V{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||o,l=await bp.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}),g={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};ob.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(g,i.applitoolsStepSettings),nb.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){nb.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await bp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var vs,Tp=w(()=>{"use strict";fs();K();ta();vs=class extends lr{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.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 ms(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,ab=w(()=>{"use strict";Tp();ur=class extends vs{isFailedResult(e){return e===!1}}});var ha,cb=w(()=>{"use strict";Tp();ha=class extends vs{isFailedResult(e){return!e}}});var ya,lb=w(()=>{"use strict";fs();le();K();ya=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await ds(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof At?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ne?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var _r,ub=w(()=>{"use strict";le();_r=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ye,pb=w(()=>{"use strict";le();ye=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var ba,db=w(()=>{"use strict";le();ba=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ta,mb=w(()=>{"use strict";le();Ta=class extends V{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function lI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function wa(s,e){lI(uI,e),e.registerLocateStepActionUtils(Fn.getUtils(s))}var uI,wp=w(()=>{"use strict";ly();dy();vy();Sy();Iy();xy();ky();_y();Oy();Ly();Ny();Uy();Fy();$y();Gy();Yy();Xy();Qy();Zy();eb();tb();ib();ab();cb();lb();ub();pb();db();mb();uI={locate:Fn,scroll:Yi,mouse:Xi,submit:oa,text:Zi,"special-key":ra,"user-code":zt,"validation-code-step":zt,"wait-for-code-step":zt,"action-code-step":zt,"condition-step":ws,"skip-code-step":ws,"element-code-step":ws,"evaluate-expression":Qi,"text-validation":jn,"wait-for-text-validation":jn,"select-option":na,"drop-file":ca,"input-file":ua,hover:ia,navigation:da,wheel:aa,sleep:ma,refresh:fa,"keyboard-shortcut-step":sa,"api-validation":$n,"api-action":$n,"api-code-step":zt,"extract-text":ga,"simple-ui-verification":Wn,"wait-for-simple-ui-verification":Wn,"cli-validation-download-file":_r,"cli-wait-for-download-file":_r,"network-validation-step":_r,"cli-validation-code-step":ur,"cli-wait-for-code-step":ur,"cli-action-code-step":ur,"cli-api-code-step":ur,"cli-condition-step":ha,"node-package":ya,"email-code-step":zt,"cli-email-code-step":ur,"sfdc-internal-test-step":Ta,"sfdc-recorded-step":ba,"sfdc-step-login":ye,"sfdc-step-loginas":ye,"sfdc-step-logout":ye,"sfdc-step-sobjectcreate":ye,"sfdc-step-sobjectdelete":ye,"sfdc-step-findrecord":ye,"sfdc-step-quickaction":ye,"sfdc-step-sobjectedit":ye,"sfdc-step-sobjectvalidate":ye,"sfdc-step-launchapp":ye,"sfdc-step-wait-for-page-load":ye,"sfdc-step-closeconsoletabs":ye,"sfdc-step-relatedlistaction":ye,"sfdc-step-permission-validation":ye,"sfdc-step-convert-lead-to-opportunity":ye,"sfdc-step-quotelineeditor":ye,"sfdc-document-validation":_r,"sfdc-step-flow-screen-completion":ye,"sfdc-step-sobjectverifyoptions":ye}});var fb,pI,Ss,vp=w(()=>{"use strict";fb=["simple-ui-verification","wait-for-simple-ui-verification"],pI=[...fb,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor","sfdc-document-validation","sfdc-step-flow-screen-completion","sfdc-step-sobjectverifyoptions"],Ss=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=pI.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 fb.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 hb={};G(hb,{SeleniumTestPlayer:()=>Vn});var gb,dI,Vn,Sp=w(()=>{"use strict";F();gb=require("@applitools/eyes-sdk-core");_n();K();j();up();ny();fp();Ki();ay();gp();we();wp();vp();dI=C("SeleniumTestPlayer"),Vn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new Ss(Ji());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Q();this.driver=n??new xr;let d=new zi(this.driver);this.stepActionFactory=new c(d),wa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Hi(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=iy(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new bs(this.driver),FrameLocator:m,portSelector:qi,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:gb.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}=Q(),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 r=await this.driver.getTabIds();if(!Array.isArray(r)){dI.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(r);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var yb={};G(yb,{WorkerSelenium:()=>Ep});function fI(s){let{playback:e}=Q().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>N(`Got event ${t}`))}var va,mI,Ep,bb=w(()=>{"use strict";F();$e();Nn();j();Ot();ei();ae();cp();K();Sp();we();Qe();va=C("worker-selenium"),mI=1e9,Ep=class extends lt{initPlayer(t){return new Vn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){N("in WorkerSelenium getBrowserOnce"),Z.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ys(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await i.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:o,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps}),N("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),N("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,mI),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 Rt||d||m?new Rt(`Page '${l}' is not available`):(va.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Uo(),initializedFromCache:Fo()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=Q(),{driver:i,sessionPlayer:a}=r,l=n||"runner";Z.onWaitToTestComplete(this.id),fI(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 hn(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,Ue.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()||(va.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&&(va.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});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 va.error("failed to run test once",{err:u}),u}}}});var Tb,wb,He,gI,hI,Ip,Et,Sa=w(()=>{"use strict";Tb=S(require("ora")),wb=S(require("jimp"));ue();Ge();he();j();ae();we();pe();He=C("mobile-grid-service"),gI="https://tdc.tricentis-cloud.com",hI="https://ui.headspin.io",Ip=class{constructor(){this.gridsAppIdGetter={[_.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[_.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[_.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[_.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[_.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[_.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===_.TESTIM_TDC||e===_.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===_.TESTIM_HEADSPIN?`${r||Ja}/${Xa}/devices`:t===_.TESTIM_TDC?`${r||Ya}/${Xa}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await Ve({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)}/device_id:${t}/automation-config`;try{let o=await Te(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,r){let n=await Bs(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===_.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===_.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([_.BROWSERSTACK,_.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:o,gridId:i}){var a,l,c;if(t===_.TESTIM_HEADSPIN||t===_.TESTIM_TDC){let d=await Pl({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===_.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===_.SAUCELABS)return e.testobject_device_name;if(t===_.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n){let{executionId:o,testId:i,testResultId:a}=e,{project:l,projectData:{type:c}={},company:{companyId:d=""}={},gridData:{gridId:m="",type:u=""}={}}=n,f=t.capabilities,h=f.platformName,g;if(u===_.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:T}=Q();g=T(t.capabilities)}else g=await this.getDeviceFromAppiumCapabilities(f,t,r,h,u,l,c,d,m);let y=await this.buildRemoteResultLink(n.gridData,t.sessionId,f);return await vr(l,o,i,a,"RUNNING",{device:g,...y&&{remoteResultLink:y}}),He.info("device details updated on testResult",{testResultId:a,executionId:o,testId:i,device:g,remoteResultLink:y,gridType:u}),g}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===_.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),i=Number(o[0]),a=Number(o[1]);return{scaleFactor:e.pixelRatio,width:i,height:a}}try{let{AppiumApi:o}=Q(),i=new o(t,r.sessionId,null),[a,l]=await Promise.all([i.getScreenshot(),i.getDeviceSize()]),c=Buffer.from(a,"base64"),d=await wb.default.read(c),m=d.getWidth(),u=d.getHeight();return{scaleFactor:m/l.width,width:m,height:u}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,o,i,a,l,c){let[d,m]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:o,projectId:i,projectType:a,companyId:l,gridId:c})]),u=this.getOsVersion(e,o);return{name:m??"",model:e.deviceModel,udid:e.udid,osVersion:u,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===_.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Os}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===_.SAUCELABS?r.testobject_test_report_url:e.type===_.TESTIM_TVC?r.replayUrl:e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC?`${e.type===_.TESTIM_HEADSPIN?hI:gI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let r=(await Te(`${Td}/devices`)).find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,geo:"local",osVersion:r.osVersion,osType:r.deviceType.toLowerCase(),scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:o,testResultId:i}=r,a=await this.getTmaDeviceDetails(e),{project:l}=t;return await vr(l,n,o,i,"RUNNING",{device:a}),He.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,o=t.mobileApp,i=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:o,gridHost:e.host});return i?(L.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:i,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await _l({gridAppId:i,gridId:e.gridId,projectId:r,gridType:n,appId:o.appId,gridHost:e.host})),i):t.getAppPathByGridType(n,e.gridId,o)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await ln({appId:e,projectId:t});return{appUrl:`${fe}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(bd*60))+1)*60*1e3,Math.max(yd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let a={[_.BROWSERSTACK]:{name:"Browserstack"},[_.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[_.P_CLOUDY]:{name:"pCloudy"}}[o].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,Tb.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 kl({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),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!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:o});return t.set(i,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",o,{executionId:i,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:i});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,o=T.mobileApp,e.nativeApp=o}else 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,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===_.BROWSERSTACK||f===_.TESTIM_TVC||f===_.P_CLOUDY;if(g){let T=t.projectData.type,R=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});R&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=g),!R&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!R&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:i})}return!g&&y&&(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 d,m;let{accessToken:n,user:o,host:i,key:a,type:l,apiUrl:c}=t;if(l===_.BROWSERSTACK){let u=`${Os}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===_.SAUCELABS){let f=`${i.includes("eu-central-1")?Sd:vd}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:f,user:o,key:a})).items.some(g=>g.id===e)}if(l===_.TESTIM_HEADSPIN||l===_.TESTIM_TDC){let u=`${c}/${Qa}/apps`;return c||(u=`${l===_.TESTIM_HEADSPIN?Ja:Ya}/${Qa}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===_.TESTIM_TVC){let u=`${wd}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token"}),!0}catch(h){return h.status!==404&&He.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===_.P_CLOUDY){let u=await this.getPCloudyAuthToken(i,o,a),f=`https://${i}/api/drive`,h=await gc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await Te(e,void 0,n)}},Et=new Ip});function vb({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"&&!yI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function bI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==_.TESTIM_TDC&&e.type!==_.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 TI(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 wI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===_.TESTIM_TDC,a=s===_.TESTIM_HEADSPIN,l=i?"tdc":"headspin",c=a&&L.flags.enableBatchHeadSpin.isEnabled(),d=i&&(L.flags.enableBatchTDC.isEnabled()||L.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=L.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture`]:!0,...L.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...o&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:TI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:300}}}function Ea(s){return"id"in s?s.id:s.packageName}function vI(s,e){return{[`${e===_.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function SI({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=vI(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":Ea(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":Ea(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Lr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:o=""}){switch(s){case"ios":return{platformName:"iOS",[`${o}autoAcceptAlerts`]:!0,[`${o}automationName`]:"XCUITest",[`${o}fullReset`]:!0,...t&&{[`${o}bundleId`]:Ea(t)},...r&&{[`${o}app`]:r},...e};case"android":return{platformName:"Android",[`${o}autoGrantPermissions`]:!0,[`${o}automationName`]:"UiAutomator2",...n&&{[`${o}appWaitActivity`]:`${n}, *`},...t&&{[`${o}appPackage`]:Ea(t),[`${o}appActivity`]:t.activity??".*"},...r&&{[`${o}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Sb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=wI(i.type,o,n);return SI({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Ra({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 Aa({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e,i=r===_.P_CLOUDY;return s||(n!=null&&n.deviceName?i?n.deviceUdid:n.deviceName:o!=null&&o.deviceNameRegex?t==="android"&&o.deviceNameRegex===".*"&&i?Za:o.deviceNameRegex:t==="ios"&&r===_.BROWSERSTACK?"iPhone.*":i?t==="ios"?"apple":Za:".*")}function EI(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 II(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Ia(s,Es)}}function Eb(s,e,t){return s?Object.entries(s).reduce((r,[n,o])=>{if(e(n)){if(!t)return r[n]=o,r;let i=n.replace(t,"");r[i]=o}return r},{}):{}}function RI(s){return Eb(s,e=>e.startsWith("browserstack."),"browserstack.")}function AI(s){return Eb(s,e=>!e.startsWith("browserstack."))}function Ib(s){return!s||!Rb(s)?"2.0.0":s}function Rb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Ab({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,o=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,i=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&o.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&i.test(s),d=l||c;if(t){let m=Rb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Ia(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let o=`${e}${r}`;t[o]=n}),t}function xI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=EI(o,s),f=Ra({osVersion:l,mobileConfig:d}),h=Aa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),g=qe(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y={device:h,os_version:f,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":g,"waldo:options":{token:u}};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function CI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=o,h=L.flags.enableAppium2pCloudy.isEnabled(),g=Ra({osVersion:l,mobileConfig:d}),y=Aa({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),R={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:i.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...R,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Ed),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=II(b)),t="",Lr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Es}})}function PI({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=Ra({osVersion:l,mobileConfig:d}),f=Aa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Or.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],Ab({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},R={user:o.user,key:o.key,name:i.testResultId,build:i.executionId,appiumVersion:Ib(g.appiumVersion),deviceName:f,tags:Object.values(i)},b={"appium:platformVersion":u,"appium:deviceName":f,...Ia(h,Es),"sauce:options":{...T,...R,...(0,Or.omit)(g,"appiumVersion")}};return Lr({projectType:s,sessionCaps:b,appiumPrefix:Es,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":o.user,"saucelabs.key":o.key,platformVersion:u,deviceName:f,tags:Object.values(i),name:i.testResultId,build:i.executionId,...h,...g};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function kI({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=Ra({osVersion:l,mobileConfig:d}),f=Aa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=RI(n.browserstack),g=(0,Or.omit)(AI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:R}=n.browserstack||{},b=L.flags.enableAppium2BrowserStack.isEnabled();if(b||Ab({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let I={userName:o.user,accessKey:o.key,appiumVersion:b?"2.0.1":Ib(h.appiumVersion),projectName:y||i.project,buildName:T||i.executionId,debug:!0,networkLogs:!0},x={"appium:platformVersion":u,"appium:deviceName":f,...Ia(g,Es),"bstack:options":{...I,...(0,Or.omit)(h,"appiumVersion")}};return Lr({projectType:s,sessionCaps:x,appiumPrefix:Es,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let v={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:R||i.testResultId,project:y||i.project,build:T||i.executionId,buildTags:Object.values(i).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...Ia(h,"browserstack.")};return Lr({projectType:s,sessionCaps:v,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function _I(s){if(_.TESTIM_TDC===s.gridInfo.type||_.TESTIM_HEADSPIN===s.gridInfo.type)return Sb(s);if(_.TESTIM_TVC===s.gridInfo.type)return xI(s);if(_.P_CLOUDY===s.gridInfo.type)return CI(s);if(_.SAUCELABS===s.gridInfo.type)return PI(s);if(_.BROWSERSTACK===s.gridInfo.type)return kI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function OI(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 xb(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}`);vb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=Et.getGridConnection(e),l=_I(s);if(e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC){let m=e.type===_.TESTIM_HEADSPIN?"headspin":"tdc",u=OI(r,o==null?void 0:o.mobile);if(!(0,Or.isEmpty)(u)){let f=Object.entries(u).map(([h,g])=>g.split(",").map(y=>y===".*"||y==="="?"":`${h}:${y}`).join(",")).join(" ").trim();l[`${m}:selector`]=f}}let c=e.type===_.TESTIM_TVC?{alwaysMatch:l}:l,d=L.flags.increaseTDCRequestTimeout.isEnabled();return{...a,desiredCapabilities:l,...d&&{connectionRetryTimeout:48e4},capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function Cb(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;vb({nativeAppMetadata:r,appPath:o,gridInfo:t}),bI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((g=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await Et.getGridDirectConnection(t,d),f=Sb({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 Pb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s;return Lr({projectType:e,sessionCaps:{dontStopAppOnReset:!0,fullReset:!1},nativeAppMetadata:t,appPath:r,androidActivityWait:n})}function kb(s){var t,r;let e={...s};return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],(t=e.capabilities["sauce:options"])==null||delete t.user,(r=e.capabilities["sauce:options"])==null||delete r.key,delete e.capabilities.key,delete e.capabilities.user,e}var Or,Es,yI,Rp=w(()=>{"use strict";pe();ae();Sa();Or=require("lodash");F();ue();Es="appium:",yI=[_.BROWSERSTACK,_.SAUCELABS,_.TESTIM_HEADSPIN,_.TESTIM_TDC,_.TESTIM_TVC,_.P_CLOUDY]});var xa,Ob=w(()=>{"use strict";xa=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 Ca,Lb=w(()=>{"use strict";F();Ca=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=zs;this.getLinksFromUnescapeHTML=Ks}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 Ap,Pa,Db=w(()=>{"use strict";j();Ap=C("mobile-frame-locator-mock"),Pa=class{foundFrameCallback(){return Ap.info("foundFrameCallback-mock invoked"),{}}locate(){return Ap.info("locate-mock invoked"),{}}async findFrame(){return Ap.info("findFrame-mock invoked"),{}}}});var LI,Nb,Mb,Is,xp=w(()=>{"use strict";LI=S(require("webdriverio")),Nb=require("@applitools/eyes-sdk-core");Ob();fp();j();Lb();gp();we();wp();Db();vp();Mb=C("appium-test-player"),Is=class{constructor(e,t,r,n=LI,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Q(),m=new Ca(this.driver);this.stepActionFactory=new c(m),wa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Ss(Ji()),this.sessionPlayer=new a(e,{tabService:new xa,cookieUtils:void 0,FrameLocator:Pa,portSelector:qi,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Nb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,o={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Mb.info("appium session deleted",{...o}))}catch(i){Mb.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=Q();e.off(i.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function DI(s){return await Te(`${s}/api/status`)}async function Ub(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function Fb(s){if((await DI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Bb=w(()=>{"use strict";Ge()});var jb={};G(jb,{WorkerLocalTma:()=>_p});var ka,Cp,Pp,kp,_p,$b=w(()=>{"use strict";Ge();Rp();Nn();F();j();Ot();xp();we();Bb();Sa();ka=C("worker-appium"),Cp=class extends Error{},Pp=class extends Error{},kp=class extends Error{},_p=class extends lt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=Q(),{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 I;if(Z.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 Fb(i);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{mobileApp:x}=await Et.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=x}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:R,version:b},v]=await Promise.all([this.getAppStateFromDevice(i,a,T),Ub(i,a)]).catch(x=>{throw this.handleDeviceNotFoundError(x),x});if(!R&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!R&&y&&await this.installApp(i,a,y);try{let x={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(I=this.options.projectData)==null?void 0:I.name}-${this.options.project}`},O=Pb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:x,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),W={capabilities:{udid:a,...O}},A=await this.requestNewAppiumSessionFromTma(i,W,g);this.sessionData=A;let E=await m.attach({sessionId:A.sessionId,capabilities:O});this.device=await Et.updateTmaDeviceDetails(a,this.options,t),ka.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:E.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:E.capabilities})}catch(x){throw ka.error("failed to start application",{err:x}),x}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await Ve({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new kp(l):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,l=(await Te(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 Ut(n);await Fs(`${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 Pp(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 Cp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=Q(),{sessionPlayer:i}=r,a=n||"runner";Z.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 ka.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw ka.error("failed to run test once",{err:c}),c}}}});var Vb={};G(Vb,{WorkerAppium:()=>Op});var Wb,Dr,Op,Gb=w(()=>{"use strict";Rp();Wb=require("linkedom");Nn();j();Ot();xp();we();Sa();ae();is();Dr=C("worker-appium"),Op=class extends lt{initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){Z.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,l=await Et.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),c=a==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.id}`},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 Et.lockDevice(o,this.options.deviceUdid),f=await Cb(u)):f=xb(u),Dr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:kb(f)});let h=this.getServerAddressFromGrid();this.activeSession=await i.remote(f),this.device=await Et.updateDeviceOnRemoteTestResult(t,this.activeSession,h,this.options);let g=`${h}/session/${this.activeSession.sessionId}`;this.updateSlotData(g),Dr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Dr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}async startKeepAlive(t){let{errors:r}=Q(),n=async()=>{try{await(t==null?void 0:t.getOrientation())}catch(o){Dr.error("failed to keep appium session alive",{err:o}),r!=null&&r.AppiumSessionTerminatedError&&o instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&mg(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Dr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===_.TESTIM_HEADSPIN||o===_.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`: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}=Q(),{sessionPlayer:a}=r,l=n||"runner";Z.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let c;if(this.options.skipLoadBalancer){let h=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:g,hostname:y,port:T,path:R}=await Et.getHeadSpinDeviceConnection(this.options.gridData,h);c=`${g}://${y}:${T}${R}`}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,Wb.DOMParser),this.startKeepAlive(a.playbackManager.appiumApi),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let h=await new Promise((y,T)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:y,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(T)});return this.stopKeepAlive(),await i.drain(),h.stepsResults=null,h.resultId=this.testResultId,{...h,...t.seleniumPerfStats.getStats()}}catch(h){throw Dr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:h}),this.stopKeepAlive(),h}};try{return await super.runTestOnce(t,r),await m()}catch(h){throw Dr.error("failed to run test once",{err:h}),h}}}});var _a,Hb=w(()=>{"use strict";F();_n();K();_a=class{constructor(e){this.id=e;this.driver=new xr}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 qb,Oa,zb=w(()=>{"use strict";qb=S(require("ws"));F();Oa=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 qb.default(this._cdpUrl,{timeout:e}),r=Xt(o=>{t.once("open",o)}),n=Xt(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 Da,Lp,La,Kb=w(()=>{"use strict";F();Da=S(require("chrome-launcher"));$u();zb();dn();Lp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Oa}async init(e){var f,h,g,y;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c}=e,d=Pi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c}),m=[...((f=d.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((y=(g=(h=d.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:g["goog:chromeOptions"])==null?void 0:y.args)??[],...Da.Launcher.defaultFlags().filter(T=>T!=="--disable-extensions")];this.chrome=await Da.launch({chromeFlags:m,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 u=await yr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(u),es(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},La=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new Lp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Yb={};G(Yb,{WorkerExtension:()=>Gn});function MI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Jb(s){return MI(s)?s:new Error(s)}var ut,Gn,Dp=w(()=>{"use strict";$e();K();Nn();F();j();Ot();ae();Hb();Kb();Qe();ut=C("worker-ext"),Gn=class extends lt{initPlayer(){return this.options.useChromeLauncher?new La(this.id):new _a(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(i=this.options.lightweightMode)==null?void 0:i.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps})}catch(a){throw ut.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Uo(),initializedFromCache:Fo(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Z.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,Ue.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ne))throw u;return ut.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 ut.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)){Z.onWaitToTestStart(this.id),Z.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw ut.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Z.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Ue.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof ne))throw T;ut.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}Z.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),ut.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),T.type=$s.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=ce(e.onCompleted(),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG),R=await uc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(R.success),R.reason)}catch(I){ut.error("Could not update the grid about the test status",{err:I})}m.isAlive()||(ut.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),R.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(ut.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),R.keepAliveIssue=b),{...R,...e.seleniumPerfStats.getStats()}}catch(T){throw ut.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:o}),Jb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw ut.warn("failed to start url",{err:h}),Jb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),N("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ut.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Xb={};G(Xb,{WorkerExtensionSingleBrowser:()=>Mp});var NI,UI,Mp,Qb=w(()=>{"use strict";$e();F();j();sp();Ot();Dp();NI=C("base-worker"),UI=500,Mp=class extends Gn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Dn(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 Z.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()&&(NI.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(UI)}}});function FI(s,e){e===0?s():setTimeout(s,e*pd)}var Np,Ma,Zb=w(()=>{"use strict";_n();ue();$e();ku();Qe();qu();K();j();ae();Gh();Np=C("parallel-worker-manager"),Ma=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case ee.SELENIUM:return(bb(),be(yb)).WorkerSelenium;case ee.APPIUM:return e.localTmaUrl?($b(),be(jb)).WorkerLocalTma:(Gb(),be(Vb)).WorkerAppium;default:return _i.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Qb(),be(Xb)).WorkerExtensionSingleBrowser:(Dp(),be(Yb)).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,h)=>new Promise(g=>{var dr,k,M,B,z,dt,ja,zp;let y=o.project,T=new Fi(r,n,e,o,i,t),R={},b=e.length,v=((dr=o.company)==null?void 0:dr.ucid)||"",I=(k=o.company)==null?void 0:k.companyId,x=(M=o.company)==null?void 0:M.name,O=o.source||"cli",W=o.user,A=(B=o.company)==null?void 0:B.planType,E=(z=o.company)==null?void 0:z.isStartUp,D=(dt=o.projectData)==null?void 0:dt.name,U=(ja=o.projectData)==null?void 0:ja.type,H=o.lightweightMode,q=(zp=o.gridData)==null?void 0:zp.type,Y=(Dt,mt,ve,$a,qn,Wa)=>(m++,xg({executionId:r,projectId:y,testId:mt,resultId:ve,ucid:v,companyId:I,companyName:x,projectName:D,companyPlan:A,source:O,user:W,lightweightMode:H,isStartUp:E,projectType:U,appSource:Wa,gridType:q}),t.testStartAndReport(Dt,r,ve,$a,qn)),me=async(Dt,mt,ve,$a,qn,Wa)=>{var Kp,Jp,Yp;m--;let tt={...(H==null?void 0:H.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...o.host&&{gridHost:o.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),o.grid||o.gridId?(tt.gridName=o.grid||((Kp=o.gridData)==null?void 0:Kp.name),tt.gridType=(Jp=o.gridData)==null?void 0:Jp.type,tt.gridProvider=(Yp=o.gridData)==null?void 0:Yp.provider):o.localTmaUrl?(tt.gridName="local-tma-from-options",tt.gridType="local-tma"):o.useLocalChromeDriver?(tt.gridName="local-chrome-driver-from-options",tt.gridType="local-chrome"):o.useChromeLauncher?(tt.gridName="chrome-launcher-from-options",tt.gridType="local-chrome"):o.browserstack?tt.gridName="browserstack-from-options":o.saucelabs&&(tt.gridName="saucelabs-from-options"),await t.testEndAndReport(Dt,ve,r,$a,qn,tt).catch(_T=>Np.error("testEndAndReport threw an error",{err:_T})),qn)return;R[ve.resultId]=ve,Cg({executionId:r,projectId:y,testId:mt,resultId:ve.resultId,result:ve,ucid:v,companyId:I,companyName:x,projectName:D,companyPlan:A,source:O,user:W,lightweightMode:H,logger:Np,isStartUp:E,projectType:U,appSource:Wa}),c&&!ve.success&&(T.stop(),d=!0),(Object.keys(R).length===b||d&&m===0)&&g(R)},pt=(Dt,mt)=>{R[mt.resultId]=mt,t.onTestIgnored(Dt,mt.resultId),m--,(Object.keys(R).length===b||d&&m===0)&&g(R)},It=(Dt,mt)=>t.onGridSlot(Dt,mt);o.userData={loginData:{...$t(),refreshToken:Mo(),authData:$t(),token:f,userAccessKey:h},projectId:o.project,company:o.company,servicesUrl:fe},N("in localStrategy before createWorker"),this.createWorkers(l,T,o,this.customExtensionLocalLocation,r,Y,me,It,pt).forEach((Dt,mt)=>{N("before schedule worker.run after createWorkers"),FI(()=>{N("right before worker.run"),Dt.run()},mt)})});try{let f=await Pt(),h=await No(),g=await u(f,h);if(d)throw new Jt;return g}catch(f){throw Np.error("failed running parallel workers",{executionId:r,err:f}),f}}}});async function tT(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:se()}))]}:await cl({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 Up(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 Fp(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=eT.difference(Ws(s,e),t);if(r.length>0)throw Tt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new P(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var eT,rT=w(()=>{"use strict";eT=S(require("lodash"));F();ts();he();K()});var Hn,Bp,jp,Na,sT=w(()=>{"use strict";Hn=S(require("lodash"));F();j();ue();ae();$e();ns();mu();ku();he();Qe();Ot();Jg();K();Zb();rT();({CLI_MODE:Bp}=Ft),jp=C("test-plan-runner"),Na=class{constructor(e){this.startTime=Date.now();this.workerManager=new Ma(e)}async runTestAllPhases(e,t,r,n,o,i,a,l){let c={},d=$t(),m=async()=>{let g=o.beforeParallel||1,y=!0,T=await this.workerManager.runTests(e,l,i,a,o,n,d,g,y);Object.assign(c,T)},u=async()=>{let g=no||o.parallel,y=!1;N("right before this.workerManager.runTests");let T=await this.workerManager.runTests(t,l,i,a,o,n,d,g,y);N("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=o.afterParallel||1,y=!1,T=await this.workerManager.runTests(r,l,i,a,o,n,d,g,y);Object.assign(c,T)};Pg({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(g){if(jp.error("error running test plan",{err:g}),g instanceof Jt)return l.markAllQueuedTests(i,de.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,R,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===Bp.SELENIUM){let[{getSessionPlayer:v},{makeSDK:I}]=await Promise.all([Promise.resolve().then(()=>(we(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:x}=v();await x.closeBatch(i,I);return}let g;try{if(!((b=(R=(T=o.company)==null?void 0:T.activePlan)==null?void 0:R.premiumFeatures)!=null&&b.applitools)||(g=await Il(o.project),Hn.default.isEmpty(g)||!i))return;let{runKey:v,url:I}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:I,apiKey:v}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,l){var b,v,I;let c=se(),d=n.project;oc(c),e.forEach(x=>Object.assign(x,{isBeforeTestPlan:!0})),r.forEach(x=>Object.assign(x,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Ci(m,n,i,a),f=Hn.default.chain(m).map(x=>{var O;return((O=x.overrideTestConfig)==null?void 0:O.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(x=>x.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,o,g);N("before testListInfoPromise");let T=await y;(I=n.lightweightMode)!=null&&I.onlyTestIdsNoSuite||Z.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,o,c,l,h),N("before runTestAllPhases");let R=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,o||"All Tests",u);return N("before executionEnd"),await u.executionEnd(c),N("after executionEnd"),{results:R,executionId:c,testPlanName:o,configName:h}}async runTestPlans(e,t){jp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Hn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await al(i,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Bp.APPIUM&&await Fp(e,r(c)),await ie(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await ig(e,d);let f=u.overrideExecutionName||d.name;return await ie(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Z.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(I=>({executionId:I,status:Up(n[m][I])})),R=Object.keys(n[m]).map(I=>n[m][I]).reduce((I,x)=>Object.assign(I,x),{}),b=Up(R);Object.assign(o,R);let v=b?T[0].executionId:T.find(I=>!I.status).executionId;return await nl(i,m,{success:b,executions:T,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var l;jp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),N("before getSuite");let r=await tT(e,t);if(N("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;N("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode==="appium"&&(a=await ln({appId:e.appId,projectId:e.project})),await ie(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==Bp.APPIUM&&await Fp(e,c),N("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,o,null,t,i);return N("right after runTestPlan"),await Z.onTestPlanFinished(d.results,o,this.startTime,d.executionId,i),d})}async run(e){let t=En(),r=[];Vs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Hn.default.flattenDeep(r);return N("right before onAllTestPlansFinished"),await Z.onAllTestPlansFinished(n),N("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var aT={};G(aT,{init:()=>oR,run:()=>eR});async function BI(s){let e=s.project,t=await ll(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"),mn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ls}function jI(s,e){var i,a,l,c,d,m,u,f;let t=bo(e.activePlan),r=s.parallel;if(t==="free"&&r>oT)throw new P(`The free plan allows only ${oT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let h=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!h)throw new P("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let 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 Ky(d,this.uploadFile);await this.uploadFilesAndForceVisibility(m,t)}}});var pa,da,Xy=w(()=>{"use strict";pa=require("url");le();da=class extends V{async updateBaseUrl(e){let t=new pa.URL(e),r=new pa.URL(this.context.recordedBaseUrl),n=new pa.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 ma,Qy=w(()=>{"use strict";le();F();ma=class extends V{async performAction(){await oe(this.step.durationMS||0)}}});var fa,Zy=w(()=>{"use strict";le();fa=class extends V{async execute(){try{return await this.driver.reloadTab(),{success:!0}}catch(e){return{success:!1,reason:e.message}}}}});var $n,eb=w(()=>{"use strict";le();$n=class extends V{async runApiInAut(e){var n;e.withCredentials=!0;let t=this.context.data.timeToPlayStep+3e3,{apiCall:r}=this.sessionPlayerInit;try{let o=await this.driver.executeCodeAsync(r,t,e);return(o==null?void 0:o.value)||{}}catch(o){throw(n=o==null?void 0:o.message)!=null&&n.includes("Javascript execution context no longer exists")?new Error('The page refreshed or changed while executing this step. Please consider unchecking "Send via web page" if this is expected.'):o}}runApiInBg(e){let{apiCall:t,apiCallAsync:r}=this.sessionPlayerInit;return typeof r=="function"&&r.length===2?r(t,e):new Promise(n=>{t(e,n)})}async performAction(){let{sessionPlayerInit:{commonConstants:e},step:t,context:r}=this,n={id:t.id,url:r.apiUrl,method:t.method,headers:r.apiHeaders,body:r.apiBody,timeout:r.data.maxTotalStepTime,omitCookies:t.omitCookies,forceUseFetch:["android","ios"].includes(r.project.type),formData:t.formData,fileUrls:r.fileUrls},o=t.sendViaWebApp?await this.runApiInAut(n):await this.runApiInBg(n),i=o.result||{},a={method:t.method,status:i.status,url:t.url};return o.success?i.status===0?{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:"Connection problem",errorType:e.stepResult.API_REQUEST_NETWORK_ERROR}:{result:i,resultInfo:a,shouldRetry:!1,success:!0}:{result:i,resultInfo:a,shouldRetry:!1,success:!1,reason:i.error||e.error.REQUEST_TIMED_OUT,errorType:i.error?e.stepResult.API_FAILURE:e.stepResult.API_REQUEST_NETWORK_ERROR}}}});var ga,tb=w(()=>{"use strict";le();ga=class extends V{async performAction(){let e=this.step.extractTextParamName,t=await this.stepActionUtils.extractTargetText(this.getTarget());return this.context.data.exports||={},this.context.data.exports[e]=t,{success:!0,data:this.context.data}}}});var rb,yp,bp,sb=w(()=>{"use strict";rb=S(require("@applitools/spec-driver-webdriverio"));to();we();yp=class{constructor(){let{EyeSdkBuilder:e}=Q(),t=ed["@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:rb.default}),this.handleApplitoolsSdkResult=e.handleApplitoolsSdkResult}async getManager(e,t,r,n){let{EyeSdkBuilder:o}=Q(),i=await this.sdk.makeManager({type:e?"ufg":"classic",concurrency:t});return o.rememberCreatedBatch(r,n),i}},bp=new yp});var ob,nb,Wn,ib=w(()=>{"use strict";ob=S(require("lodash"));le();j();sb();nb=C("pixel-validation-step-action"),Wn=class extends V{async performAction(){var m,u;let{shouldUseVisualGrid:t,applitoolsSdkConfig:r,applitoolsSdkLogger:n,testResultId:o}=this.context;this.runContext=this.context.getRunContext(void 0);let i=((m=this.runContext.incomingParams)==null?void 0:m.final)||{},a=((u=r.batch)==null?void 0:u.id)||o,l=await bp.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}),g={region:this.step.action==="element"&&c.seleniumElement||void 0,fully:this.step.action==="stitched"};ob.isPlainObject(i.applitoolsStepSettings)&&(Object.assign(g,i.applitoolsStepSettings),nb.info("Applitools SDK step executed with applitoolsStepSettings parameter",{applitoolsStepSettings:i.applitoolsStepSettings})),await f.check({settings:g}),d={isApplitoolsSdkResult:!0,success:!0,eyesResults:await f.close()}}catch(f){nb.error("Applitools SDK step failed",{err:f,info:f.info}),d={isApplitoolsSdkResult:!0,success:!1,err:f}}return await bp.handleApplitoolsSdkResult(this.context,d,this.step)}}});var vs,Tp=w(()=>{"use strict";fs();K();ta();vs=class extends lr{async executeCliCode(){var h,g,y;let{step:e,context:t}=this,r=this.stepActionUtils.driver.isMobile;if(!((y=(g=(h=t.company)==null?void 0:h.activePlan)==null?void 0:g.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 ms(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,ab=w(()=>{"use strict";Tp();ur=class extends vs{isFailedResult(e){return e===!1}}});var ha,cb=w(()=>{"use strict";Tp();ha=class extends vs{isFailedResult(e){return!e}}});var ya,lb=w(()=>{"use strict";fs();le();K();ya=class extends V{async performAction(){let{stepId:e,packageData:t,resultId:r,retryIndex:n,stepResultId:o,timeToPlayBeforeExec:i}=this.context;try{return{data:await ds(e,r,n,t,o,i),success:!0}}catch(a){return a instanceof At?{success:!1,code:"invalid-node-package",message:a.message}:a instanceof ne?{success:!1,code:"timeout"}:{success:!1,reason:a.message,exception:a}}}}});var _r,ub=w(()=>{"use strict";le();_r=class extends V{async performAction(){return{success:"skipped",reason:"This step can run only in \u2018extension\u2019 run mode with either Chrome or Edge Chromium"}}}});var ye,pb=w(()=>{"use strict";le();ye=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{let o=this.context.sfdcTestActions;if(o===void 0)throw new Error("No test actions were compiled");return{success:!0,reason:await e.sfdcExecute(t,o,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var ba,db=w(()=>{"use strict";le();ba=class extends V{async performAction(){var r,n;let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler||((o,i)=>this.context.playback.sfdcAddLog(o,i)));t.log.info(`BEGIN STEP '${(n=(r=this.step).getStepPreview)==null?void 0:n.call(r)}'`);try{return{success:!0,reason:await e.sfdcExecuteRecordedStep(t,this.step.recordedData,this.context)}}catch(o){return{success:!1,reason:o.reason||o.message,exception:o,shouldRetry:!1}}finally{t.releaseObjects()}}}});var Ta,mb=w(()=>{"use strict";le();Ta=class extends V{async performAction(){let{sfdc:e}=this.sessionPlayerInit,t=e.sfdcNewSePage(this.driver,this.context.sfdcLogHandler);try{return await e.sfdcExecuteJavascript(t,this.step.code||"",this.context),{success:!0}}catch(r){return{success:!1,reason:r.reason||r.message,exception:r,shouldRetry:!1}}finally{t.releaseObjects()}}}});function lI(s,e){Object.keys(s).forEach(t=>{e.registerStepAction(t,s[t])})}function wa(s,e){lI(uI,e),e.registerLocateStepActionUtils(Fn.getUtils(s))}var uI,wp=w(()=>{"use strict";ly();dy();vy();Sy();Iy();xy();ky();_y();Oy();Ly();Ny();Uy();Fy();$y();Gy();Yy();Xy();Qy();Zy();eb();tb();ib();ab();cb();lb();ub();pb();db();mb();uI={locate:Fn,scroll:Yi,mouse:Xi,submit:oa,text:Zi,"special-key":ra,"user-code":zt,"validation-code-step":zt,"wait-for-code-step":zt,"action-code-step":zt,"condition-step":ws,"skip-code-step":ws,"element-code-step":ws,"evaluate-expression":Qi,"text-validation":jn,"wait-for-text-validation":jn,"select-option":na,"drop-file":ca,"input-file":ua,hover:ia,navigation:da,wheel:aa,sleep:ma,refresh:fa,"keyboard-shortcut-step":sa,"api-validation":$n,"api-action":$n,"api-code-step":zt,"extract-text":ga,"simple-ui-verification":Wn,"wait-for-simple-ui-verification":Wn,"cli-validation-download-file":_r,"cli-wait-for-download-file":_r,"network-validation-step":_r,"cli-validation-code-step":ur,"cli-wait-for-code-step":ur,"cli-action-code-step":ur,"cli-api-code-step":ur,"cli-condition-step":ha,"node-package":ya,"email-code-step":zt,"cli-email-code-step":ur,"sfdc-internal-test-step":Ta,"sfdc-recorded-step":ba,"sfdc-step-login":ye,"sfdc-step-loginas":ye,"sfdc-step-logout":ye,"sfdc-step-sobjectcreate":ye,"sfdc-step-sobjectdelete":ye,"sfdc-step-findrecord":ye,"sfdc-step-quickaction":ye,"sfdc-step-sobjectedit":ye,"sfdc-step-sobjectvalidate":ye,"sfdc-step-launchapp":ye,"sfdc-step-wait-for-page-load":ye,"sfdc-step-closeconsoletabs":ye,"sfdc-step-relatedlistaction":ye,"sfdc-step-permission-validation":ye,"sfdc-step-convert-lead-to-opportunity":ye,"sfdc-step-quotelineeditor":ye,"sfdc-document-validation":_r,"sfdc-step-flow-screen-completion":ye,"sfdc-step-sobjectverifyoptions":ye}});var fb,pI,Ss,vp=w(()=>{"use strict";fb=["simple-ui-verification","wait-for-simple-ui-verification"],pI=[...fb,"custom-validation","sfdc-internal-test-step","sfdc-recorded-step","sfdc-step-login","sfdc-step-loginas","sfdc-step-logout","sfdc-step-sobjectcreate","sfdc-step-sobjectdelete","sfdc-step-findrecord","sfdc-step-quickaction","sfdc-step-sobjectvalidate","sfdc-step-launchapp","sfdc-step-wait-for-page-load","sfdc-step-closeconsoletabs","sfdc-step-sobjectedit","sfdc-step-relatedlistaction","sfdc-step-permission-validation","sfdc-step-convert-lead-to-opportunity","sfdc-step-quotelineeditor","sfdc-document-validation","sfdc-step-flow-screen-completion","sfdc-step-sobjectverifyoptions"],Ss=class{constructor(e){this.isDebuggerConnected=e;this.totalStepTime=0;this.currentRetryStart=0;this.totalStepTimesReport=[];this.currentRetryTimes=[];this.currentRetryTimesReport={};this.resetStepVariables(),this.resetRetryVariables()}resetStepVariables(e,t){this.currentRetryTimes=t||[],this.totalStepTime=e||0,this.totalStepTimesReport=[],this.currentRetryTimesReport={};let r=Date.now();this.currentRetryStart=r,this.lastUpdateTime=r}resetRetryVariables(){let e=Date.now();this.currentRetryStart=e,this.lastUpdateTime=e,this.totalStepTimesReport.push(this.currentRetryTimesReport),this.currentRetryTimesReport={}}initStepRun(e){let t=o=>{let i=this.getTotalStepTimeLeftToPlay(e,o),a=5e3;return i<=a?[a]:[Math.max(a,i/3)]};e.setStartTimestamp();let r=this.getTotalStepRunTime(e),n=pI.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 fb.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 hb={};G(hb,{SeleniumTestPlayer:()=>Vn});var gb,dI,Vn,Sp=w(()=>{"use strict";F();gb=require("@applitools/eyes-sdk-core");_n();K();j();up();ny();fp();Ki();ay();gp();we();wp();vp();dI=C("SeleniumTestPlayer"),Vn=class{constructor(e,t,r,n,o=void 0,i=void 0){this.id=e;this.playbackTimeoutCalculator=new Ss(Ji());let{SessionPlayer:a,commonConstants:l,StepActionFactory:c}=Q();this.driver=n??new xr;let d=new zi(this.driver);this.stepActionFactory=new c(d),wa(this.driver,this.stepActionFactory),this.tabService=this.driver.tabService||new Hi(this.driver),this.driver.tabService=this.tabService,this.tabService.createSesion(e);let m=iy(this.driver);this.sessionPlayer=new a(e,{tabService:this.tabService,cookieUtils:new bs(this.driver),FrameLocator:m,portSelector:qi,LocateElementPlayer:null,stepActionUtils:d,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:gb.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}=Q(),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 r=await this.driver.getTabIds();if(!Array.isArray(r)){dI.error("addTab: driver.getTabIds() returned a non-array",{ids:r});return}let n=r.at(-1);await this.tabService.addNewTab(this.id,n,e,t),await this.sessionPlayer.addPlaybackFrameHandler(n,void 0,{emptyPage:!0})}async addAllTabs(e,t={loadInfo:!0,checkForMainTab:!0,takeScreenshots:!0},r=[]){let n=await this.driver.getTabIds(),o=["app.testim.io"].concat(r);for(let i of n.reverse()){await this.tabService.addNewTab(this.id,i,e,{...t,forceSwitch:!0});let a=this.tabService.getTabInfo(this.id,i);if(o.some(l=>a.url.includes(l))){await this.tabService.removeTabInfo(this.id,i);continue}await this.sessionPlayer.addPlaybackFrameHandler(i,void 0,{emptyPage:!0})}if(this.tabService.tabCount(this.id)===1){let i=this.tabService.getMainTabInfo(this.id),a=this.tabService.getTabUtils(this.id,i);await this.tabService.switchTab(a.tabId,this.id,{forceSwitch:!0})}this.tabService.fixMissingMainTab(this.id)}getSessionId(){return this.driver.getSessionId()}}});var yb={};G(yb,{WorkerSelenium:()=>Ep});function fI(s){let{playback:e}=Q().commonConstants;for(let t of Object.values(e))s.playbackManager.on(t,()=>N(`Got event ${t}`))}var va,mI,Ep,bb=w(()=>{"use strict";F();$e();Nn();j();Ot();ei();ae();cp();K();Sp();we();Qe();va=C("worker-selenium"),mI=1e9,Ep=class extends lt{initPlayer(t){return new Vn(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){N("in WorkerSelenium getBrowserOnce"),Z.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n;this.windowUtils=new ys(this.id,i),n.clearSessionTabs();let{browserValue:a}=this.testRunConfig,l=t.baseUrl;try{let c=this.options.useLocalChromeDriver;await i.init({browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:o,customExtensionLocalLocation:r,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:t.seleniumPerfStats,fastInit:c,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps}),N("in WorkerSelenium after driver.init"),await n.addTab(void 0,{skipLoadInfo:c}),N("in WorkerSelenium after addTab"),c||await this.windowUtils.navigate(l,mI),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 Rt||d||m?new Rt(`Page '${l}' is not available`):(va.error("failed to navigate to page",{baseUrl:l,err:c,whitelistedPublicIp:Uo(),initializedFromCache:Fo()}),c)}}async runTestOnce(t,r){var m;let{manifestVersion:n,localAssetService:o}=Q(),{driver:i,sessionPlayer:a}=r,l=n||"runner";Z.onWaitToTestComplete(this.id),fI(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 hn(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,Ue.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()||(va.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&&(va.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),u.keepAliveIssue=f);let g={...u,...t.seleniumPerfStats.getStats()};return this.lambdatestService.isLambdatestRun()&&await i.executeJS(`lambda-status=${g.success?"passed":"failed"}`).catch(()=>{}),g});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 va.error("failed to run test once",{err:u}),u}}}});var Tb,wb,He,gI,hI,Ip,Et,Sa=w(()=>{"use strict";Tb=S(require("ora")),wb=S(require("jimp"));ue();Ge();he();j();ae();we();pe();He=C("mobile-grid-service"),gI="https://tdc.tricentis-cloud.com",hI="https://ui.headspin.io",Ip=class{constructor(){this.gridsAppIdGetter={[_.TESTIM_TDC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTdcAppId",t),[_.TESTIM_TVC]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("testimTvcAppId",t),[_.P_CLOUDY]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("pCloudyAppId",t),[_.TESTIM_HEADSPIN]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("headSpinAppId",t),[_.BROWSERSTACK]:({testRunHandler:e,mobileApp:t})=>e.getAppPath("browserStackAppId",t),[_.SAUCELABS]:({testRunHandler:e,mobileApp:t,gridHost:r})=>e.getSauceLabsAppPath(r,t)}}isTdcOrHeadSpinGrid(e){return e===_.TESTIM_TDC||e===_.TESTIM_HEADSPIN}getLockDeviceApiUrl(e){let t=this.getBaseApiUrl(e);return this.isTdcOrHeadSpinGrid(e.type)?`${t}/lock`:""}getBaseApiUrl(e){let{type:t,apiUrl:r}=e;return t===_.TESTIM_HEADSPIN?`${r||Ja}/${Xa}/devices`:t===_.TESTIM_TDC?`${r||Ya}/${Xa}/devices`:""}getHeaders(e){return{...this.isTdcOrHeadSpinGrid(e.type)&&{"Content-Type":"application/json",Authorization:`Bearer ${e.accessToken}`}}}buildRequestBody(e,t){return{...this.isTdcOrHeadSpinGrid(e.type)&&{device_id:t}}}async lockDevice(e,t){let r=this.getLockDeviceApiUrl(e),n=this.getHeaders(e),o=this.buildRequestBody(e,t);try{await Ve({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)}/device_id:${t}/automation-config`;try{let o=await Te(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,r){let n=await Bs(`https://${e}/api/access`,void 0,{Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`});return JSON.parse(n).result.token}extractHeadSpinDeviceConnection(e,t){let r=Object.keys(e)[0],n=e[r].driver_url,o=new URL(n);return{hostname:o.hostname,port:Number(o.port),protocol:o.protocol.slice(0,-1),path:`/v0/${t}/wd/hub`}}async getGridDirectConnection(e,t){let r={};return this.isTdcOrHeadSpinGrid(e.type)&&(r=await this.getHeadSpinDeviceConnection(e,t)),r}getGridConnection(e){var r;if(this.isTdcOrHeadSpinGrid(e.type)){let n=(r=e.host)!=null&&r.includes("ulb.tdc.tricentis-cloud.com")?`/ulb/appium/v0/${e.accessToken}/wd/hub`:`/v0/${e.accessToken}/wd/hub`;return{protocol:e.protocol||"https",hostname:e.host,port:e.port,path:n}}if(e.type===_.TESTIM_TVC)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub"};if(e.type===_.P_CLOUDY)return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/appiumcloud/wd/hub",user:e.user,key:e.key};if([_.BROWSERSTACK,_.SAUCELABS].includes(e.type))return{protocol:e.protocol||"https",hostname:e.host,port:443,path:"/wd/hub",user:e.user,key:e.key}}async getDeviceNameFromSessionCaps({capabilities:e,gridType:t,projectId:r,projectType:n,companyId:o,gridId:i}){var a,l,c;if(t===_.TESTIM_HEADSPIN||t===_.TESTIM_TDC){let d=await Pl({projectId:r,projectType:n,companyId:o,gridId:i,selectors:`device_id:${e.udid}`});return((a=d==null?void 0:d[0])==null?void 0:a.name)||e.device}if(t===_.BROWSERSTACK)return((l=e.mobile)==null?void 0:l.version.split("-")[0])||((c=e.desired)==null?void 0:c.deviceName);if(t===_.SAUCELABS)return e.testobject_device_name;if(t===_.P_CLOUDY){if(e.pCloudy_DeviceFullName){let d=e.pCloudy_DeviceFullName.split("_");return`${d[0]} ${d[1]}`}return e.deviceModel}return e.device}async updateDeviceOnRemoteTestResult(e,t,r,n){let{executionId:o,testId:i,testResultId:a}=e,{project:l,projectData:{type:c}={},company:{companyId:d=""}={},gridData:{gridId:m="",type:u=""}={}}=n,f=t.capabilities,h=f.platformName,g;if(u===_.TESTIM_TVC){let{getTvcDeviceInfoFromSessionCaps:T}=Q();g=T(t.capabilities)}else g=await this.getDeviceFromAppiumCapabilities(f,t,r,h,u,l,c,d,m);let y=await this.buildRemoteResultLink(n.gridData,t.sessionId,f);return await vr(l,o,i,a,"RUNNING",{device:g,...y&&{remoteResultLink:y}}),He.info("device details updated on testResult",{testResultId:a,executionId:o,testId:i,device:g,remoteResultLink:y,gridType:u}),g}getOsVersion(e,t){var n;let r=e.platformVersion;return!r&&t===_.BROWSERSTACK?(n=e.mobile)==null?void 0:n.version.split("-")[1]:r}async getScaleFactorAndSize(e,t,r,n){if(e.pixelRatio&&typeof e.deviceScreenSize=="string"){let o=e.deviceScreenSize.split("x"),i=Number(o[0]),a=Number(o[1]);return{scaleFactor:e.pixelRatio,width:i,height:a}}try{let{AppiumApi:o}=Q(),i=new o(t,r.sessionId,null),[a,l]=await Promise.all([i.getScreenshot(),i.getDeviceSize()]),c=Buffer.from(a,"base64"),d=await wb.default.read(c),m=d.getWidth(),u=d.getHeight();return{scaleFactor:m/l.width,width:m,height:u}}catch(o){return He.warn("failed to get device scale factor from appium, applying default scale factor",{err:o}),{scaleFactor:n==="android"?1:2}}}async getDeviceFromAppiumCapabilities(e,t,r,n,o,i,a,l,c){let[d,m]=await Promise.all([this.getScaleFactorAndSize(e,r,t,n),this.getDeviceNameFromSessionCaps({capabilities:e,gridType:o,projectId:i,projectType:a,companyId:l,gridId:c})]),u=this.getOsVersion(e,o);return{name:m??"",model:e.deviceModel,udid:e.udid,osVersion:u,osType:n,isVirtual:!1,...d}}async buildRemoteResultLink(e,t,r){return e.type===_.BROWSERSTACK?(await this.fetchWithUserAndPasswordAuth({url:`${Os}/sessions/${t}.json`,user:e.user,key:e.key})).automation_session.public_url:e.type===_.SAUCELABS?r.testobject_test_report_url:e.type===_.TESTIM_TVC?r.replayUrl:e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC?`${e.type===_.TESTIM_HEADSPIN?hI:gI}/sessions/${t}/waterfall`:""}async getTmaDeviceDetails(e){let r=(await Te(`${Td}/devices`)).find(n=>n.udid===e);if(!r)throw new Error(`device ${e} not found`);return{udid:r.udid,name:r.name,model:r.model,height:r.height,width:r.width,geo:"local",osVersion:r.osVersion,osType:r.deviceType.toLowerCase(),scaleFactor:r.scaleFactor??0,isVirtual:r.virtual??!1,minApiVersion:r.minApiVersion}}async updateTmaDeviceDetails(e,t,r){let{executionId:n,testId:o,testResultId:i}=r,a=await this.getTmaDeviceDetails(e),{project:l}=t;return await vr(l,n,o,i,"RUNNING",{device:a}),He.info("device details updated on testResult",{testResultId:i,executionId:n,testId:o,device:a}),a}async getGridAppId({gridData:e,testRunHandler:t,projectId:r}){let n=e.type,o=t.mobileApp,i=this.gridsAppIdGetter[n]({testRunHandler:t,mobileApp:o,gridHost:e.host});return i?(L.flags.allowFixingAppIdStructure.isEnabled()&&(He.info("fixing gridAppId structure",{gridAppId:i,projectId:r,testResultId:t.testResultId,executionId:t.executionId}),await _l({gridAppId:i,gridId:e.gridId,projectId:r,gridType:n,appId:o.appId,gridHost:e.host})),i):t.getAppPathByGridType(n,e.gridId,o)}async getMobileAppDataByAppId({appId:e,projectId:t,token:r}){let n=await ln({appId:e,projectId:t});return{appUrl:`${fe}/storage${n.filePath}?access_token=${r}`,mobileApp:n}}calculateUploadRequestTimeOut(e){let t=0,r=Math.ceil(e/1024);return t=(Math.ceil(r/(bd*60))+1)*60*1e3,Math.max(yd,t)}async uploadAppToGrid({projectId:e,testRunHandler:t,mobileApp:r,gridId:n,gridType:o}){let a={[_.BROWSERSTACK]:{name:"Browserstack"},[_.TESTIM_TVC]:{name:"Mobile Virtual Grid"},[_.P_CLOUDY]:{name:"pCloudy"}}[o].name;if(t.isAppFromDevice)throw new Error(`Application from your device, ${a} grid dose not support application from device. Please choose a compatible application for testing.`);let l=r||t.mobileApp,c=(0,Tb.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 kl({projectId:e,gridId:n,app:l,timeout:this.calculateUploadRequestTimeOut(l.fileSize)});return c.succeed(`app uploaded successfully to ${a}`),d.gridAppId}catch(d){throw c.fail(`failed to upload app to ${a}`),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!=null&&a.isUploaded)return a.uploadedAppId;let l=await this.uploadAppToGrid({projectId:r,testRunHandler:e,gridId:n,gridType:o});return t.set(i,{isUploaded:!0,uploadedAppId:l}),l}async getAppIdFromGridOrTestimPublicLink({testRunHandler:e,options:t,pendingAppUploads:r}){let n="",o,{executionId:i,testResultId:a}=e,{appId:l="",project:c,authData:{token:d=""}={},gridData:m={}}=t,{gridId:u="",type:f=""}=m;if(!l&&e.isAppFromDevice)return n;if(l){He.info("getting appData by appId",{appId:l,projectId:c,testResultId:a,executionId:i});let T=await this.getMobileAppDataByAppId({appId:l,projectId:c,token:d});n=T.appUrl,o=T.mobileApp,e.nativeApp=o}else 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,g=await this.getGridAppId({projectId:c,gridData:m,testRunHandler:e}),y=f===_.BROWSERSTACK||f===_.TESTIM_TVC||f===_.P_CLOUDY;if(g){let T=t.projectData.type,R=await this.verifyAppStillExistsOnGrid({gridAppId:g,gridData:m,projectType:T});R&&(He.info("app exists on grid, using gridAppId",{gridAppId:g,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=g),!R&&y&&(He.info("app not exists on grid, uploading it",{gridAppId:g,projectId:c,testResultId:a,executionId:i,mobileAppId:h}),n=await this.verifyAppAlreadyUploaded({testRunHandler:e,pendingAppUploads:r,projectId:c,gridId:u,gridType:f,mobileAppId:h})),!R&&!y&&He.info("app not exists on grid, using testimStorage url",{projectId:c,testResultId:a,executionId:i})}return!g&&y&&(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 d,m;let{accessToken:n,user:o,host:i,key:a,type:l,apiUrl:c}=t;if(l===_.BROWSERSTACK){let u=`${Os}/recent_apps`,f=await this.fetchWithUserAndPasswordAuth({url:u,user:o,key:a});return Array.isArray(f)?f.some(h=>h.app_url===e):!1}if(l===_.SAUCELABS){let f=`${i.includes("eu-central-1")?Sd:vd}/storage/files`;return(await this.fetchWithUserAndPasswordAuth({url:f,user:o,key:a})).items.some(g=>g.id===e)}if(l===_.TESTIM_HEADSPIN||l===_.TESTIM_TDC){let u=`${c}/${Qa}/apps`;return c||(u=`${l===_.TESTIM_HEADSPIN?Ja:Ya}/${Qa}/apps`),(await this.fetchWithTokenAuth({url:u,accessToken:n,authType:"Bearer"})).apps.some(h=>h.app_id===e)}if(l===_.TESTIM_TVC){let u=`${wd}/versions/${e}/info`,f=t[`${r}Token`];try{return await this.fetchWithTokenAuth({url:u,accessToken:f,authType:"Upload-Token"}),!0}catch(h){return h.status!==404&&He.error("error while verifying app exists on TVC",{error:h}),!1}}if(l===_.P_CLOUDY){let u=await this.getPCloudyAuthToken(i,o,a),f=`https://${i}/api/drive`,h=await gc({url:f,body:{token:u,filter:"all"},headers:{contentType:null}});return(m=(d=JSON.parse(h).result)==null?void 0:d.files)==null?void 0:m.some(y=>y.file===e)}throw new Error(`grid type ${l} is not supported`)}async fetchWithUserAndPasswordAuth({url:e,user:t,key:r}){let n={Authorization:`Basic ${Buffer.from(`${t}:${r}`).toString("base64")}`};return await Te(e,void 0,n)}async fetchWithTokenAuth({url:e,accessToken:t,authType:r}){let n={Authorization:`${r} ${t}`};return await Te(e,void 0,n)}},Et=new Ip});function vb({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"&&!yI.includes(t.type))throw Error(`unsupported grid was detected please make sure to select supported mobile grid (${t.type})`)}function bI({deviceUdid:s,gridInfo:e,testRunConfig:t}){let{staticAllocation:r}=(t==null?void 0:t.mobile)||{};if(e.type!==_.TESTIM_TDC&&e.type!==_.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 TI(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 wI(s,e,t){let{fullReset:r,setNoReset:n,skipLoadBalancer:o}=e,i=s===_.TESTIM_TDC,a=s===_.TESTIM_HEADSPIN,l=i?"tdc":"headspin",c=a&&L.flags.enableBatchHeadSpin.isEnabled(),d=i&&(L.flags.enableBatchTDC.isEnabled()||L.flags.headSpinTdcEnableFlagCapability.isEnabled()),m=L.flags.increaseTDCRequestTimeout.isEnabled();return{[`${l}:capture`]:!0,...L.flags.tdcHsPreventNetworkCapture.isEnabled()&&{[`${l}:capture.network`]:!1},...o&&{[`${l}:controlLock`]:!0},[`${l}:retryNewSessionFailure`]:!1,[`${l}:sessionTags`]:TI(t),[`${l}:enableBatch`]:c||d,...!r&&{"appium:noReset":n},...m&&{[`${l}:newCommandTimeout`]:300}}}function Ea(s){return"id"in s?s.id:s.packageName}function vI(s,e){return{[`${e===_.TESTIM_TDC?"tdc":"headspin"}:app.id`]:s}}function SI({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=vI(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":Ea(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":Ea(r),"appium:appActivity":r.activity??".*"},...n&&l};default:throw Error(`unsupported mobile project ${s}`)}}function Lr({projectType:s,sessionCaps:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n,appiumPrefix:o=""}){switch(s){case"ios":return{platformName:"iOS",[`${o}autoAcceptAlerts`]:!0,[`${o}automationName`]:"XCUITest",[`${o}fullReset`]:!0,...t&&{[`${o}bundleId`]:Ea(t)},...r&&{[`${o}app`]:r},...e};case"android":return{platformName:"Android",[`${o}autoGrantPermissions`]:!0,[`${o}automationName`]:"UiAutomator2",...n&&{[`${o}appWaitActivity`]:`${n}, *`},...t&&{[`${o}appPackage`]:Ea(t),[`${o}appActivity`]:t.activity??".*"},...r&&{[`${o}app`]:r},...e};default:throw Error(`unsupported mobile project ${s}`)}}function Sb({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,sessionTags:n,options:o,gridInfo:i}){let a=wI(i.type,o,n);return SI({projectType:s,sessionCaps:a,options:o,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function Ra({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 Aa({deviceName:s,mobileConfig:e,projectType:t,gridType:r}){let{staticAllocation:n,dynamicAllocation:o}=e,i=r===_.P_CLOUDY;return s||(n!=null&&n.deviceName?i?n.deviceUdid:n.deviceName:o!=null&&o.deviceNameRegex?t==="android"&&o.deviceNameRegex===".*"&&i?Za:o.deviceNameRegex:t==="ios"&&r===_.BROWSERSTACK?"iPhone.*":i?t==="ios"?"apple":Za:".*")}function EI(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 II(s){return{"appium:appiumVersion":"2.0.0","appium:platformVersion":"10",...Ia(s,Es)}}function Eb(s,e,t){return s?Object.entries(s).reduce((r,[n,o])=>{if(e(n)){if(!t)return r[n]=o,r;let i=n.replace(t,"");r[i]=o}return r},{}):{}}function RI(s){return Eb(s,e=>e.startsWith("browserstack."),"browserstack.")}function AI(s){return Eb(s,e=>!e.startsWith("browserstack."))}function Ib(s){return!s||!Rb(s)?"2.0.0":s}function Rb(s){return s.split(".")[0]==="2"||s.includes("appium2")||s==="latest"}function Ab({osVersion:s,projectType:e,appiumVersion:t,isBrowserStack:r=!1}){let n=/^(1[4-9](\.\d+){0,2})$|^\^\(\?=1[4-9]((\.\d+){0,2})\.\*\)\.\*$/,o=/^(10(\.\d+){0,2})$|^\^\(\?=10((\.\d+){0,2})\.\*\)\.\*$/,i=/^(1[7-9](\.\d+){0,2})$|^\^\(\?=1[7-9]((\.\d+){0,2})\.\*\)\.\*$/,a=r&&o.test(s),l=e==="android"&&(n.test(s)||a),c=e==="ios"&&i.test(s),d=l||c;if(t){let m=Rb(t);return!m&&d?(console.warn(`Appium 2 is required for version: ${s}, forcing appium 2 for current session.`),!0):m}return d}function Ia(s,e){let t={};return Object.entries(s).forEach(([r,n])=>{let o=`${e}${r}`;t[o]=n}),t}function xI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{type:m}=o,u=EI(o,s),f=Ra({osVersion:l,mobileConfig:d}),h=Aa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),g=qe(n.editorUrl,n.project,i.testId,i.testResultId,i.branch),y={device:h,os_version:f,"waldo:displayName":`${i.testName}-${i.executionId}-${i.testResultId}`,"waldo:externalUrl":g,"waldo:options":{token:u}};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function CI({projectType:s,nativeAppMetadata:e,appPath:t,androidActivityWait:r,options:n,gridInfo:o,sessionTags:i,testRunConfig:a}){let{osVersion:l,deviceName:c}=n,d=(a==null?void 0:a.mobile)||{},{user:m,key:u,type:f}=o,h=L.flags.enableAppium2pCloudy.isEnabled(),g=Ra({osVersion:l,mobileConfig:d}),y=Aa({deviceName:c,mobileConfig:d,projectType:s,gridType:f}),T=/^[a-zA-Z]+$/.test(y),R={...g!==".*"&&{pCloudy_DeviceVersion:g},...T&&{pCloudy_DeviceManufacturer:y},...!T&&{pCloudy_DeviceFullName:y}},b={pCloudy_Username:m,pCloudy_ApiKey:u,pCloudy_Individual:i.pCloudyIndividual,pCloudy_EnableVideo:!0,pCloudy_EnablePerformanceData:!0,pCloudy_EnableDeviceLogs:!0,...R,pCloudy_DurationInMinutes:n.duration?Number(n.duration):Number(Ed),pCloudy_ApplicationName:t,appiumVersion:"1.21.0",newCommandTimeout:600,lunchTimeout:"90000",uiautomator2ServerInstallTimeout:15e4,uiautomator2ServerLaunchTimeout:2e5};return h&&(b=II(b)),t="",Lr({projectType:s,sessionCaps:b,nativeAppMetadata:e,appPath:t,androidActivityWait:r,...h&&{appiumPrefix:Es}})}function PI({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=Ra({osVersion:l,mobileConfig:d}),f=Aa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=(0,Or.omit)({...n.saucelabs},["automationName","platformName"]),g={...h["sauce:options"]};if(delete h["sauce:options"],Ab({osVersion:h.platformVersion||u,projectType:s,appiumVersion:g.appiumVersion})){let T={debug:!0,networkLogs:!0},R={user:o.user,key:o.key,name:i.testResultId,build:i.executionId,appiumVersion:Ib(g.appiumVersion),deviceName:f,tags:Object.values(i)},b={"appium:platformVersion":u,"appium:deviceName":f,...Ia(h,Es),"sauce:options":{...T,...R,...(0,Or.omit)(g,"appiumVersion")}};return Lr({projectType:s,sessionCaps:b,appiumPrefix:Es,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let y={"saucelabs.user":o.user,"saucelabs.key":o.key,platformVersion:u,deviceName:f,tags:Object.values(i),name:i.testResultId,build:i.executionId,...h,...g};return Lr({projectType:s,sessionCaps:y,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function kI({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=Ra({osVersion:l,mobileConfig:d}),f=Aa({deviceName:c,mobileConfig:d,projectType:s,gridType:m}),h=RI(n.browserstack),g=(0,Or.omit)(AI(n.browserstack),["automationName","platformName","project","build","name"]),{project:y,build:T,name:R}=n.browserstack||{},b=L.flags.enableAppium2BrowserStack.isEnabled();if(b||Ab({osVersion:g.platformVersion||u,projectType:s,isBrowserStack:!0,appiumVersion:h.appiumVersion})){let I={userName:o.user,accessKey:o.key,appiumVersion:b?"2.0.1":Ib(h.appiumVersion),projectName:y||i.project,buildName:T||i.executionId,debug:!0,networkLogs:!0},x={"appium:platformVersion":u,"appium:deviceName":f,...Ia(g,Es),"bstack:options":{...I,...(0,Or.omit)(h,"appiumVersion")}};return Lr({projectType:s,sessionCaps:x,appiumPrefix:Es,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}let v={os_version:g.platformVersion||u,device:g.deviceName||f,realDevice:!0,name:R||i.testResultId,project:y||i.project,build:T||i.executionId,buildTags:Object.values(i).join(","),"browserstack.user":o.user,"browserstack.key":o.key,"browserstack.debug":!0,"browserstack.networkLogs":!0,...g,...Ia(h,"browserstack.")};return Lr({projectType:s,sessionCaps:v,nativeAppMetadata:e,appPath:t,androidActivityWait:r})}function _I(s){if(_.TESTIM_TDC===s.gridInfo.type||_.TESTIM_HEADSPIN===s.gridInfo.type)return Sb(s);if(_.TESTIM_TVC===s.gridInfo.type)return xI(s);if(_.P_CLOUDY===s.gridInfo.type)return CI(s);if(_.SAUCELABS===s.gridInfo.type)return PI(s);if(_.BROWSERSTACK===s.gridInfo.type)return kI(s);throw new Error(`unsupported grid type ${s.gridInfo.type}`)}function OI(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 xb(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}`);vb({nativeAppMetadata:t,appPath:n,gridInfo:e});let a=Et.getGridConnection(e),l=_I(s);if(e.type===_.TESTIM_HEADSPIN||e.type===_.TESTIM_TDC){let m=e.type===_.TESTIM_HEADSPIN?"headspin":"tdc",u=OI(r,o==null?void 0:o.mobile);if(!(0,Or.isEmpty)(u)){let f=Object.entries(u).map(([h,g])=>g.split(",").map(y=>y===".*"||y==="="?"":`${h}:${y}`).join(",")).join(" ").trim();l[`${m}:selector`]=f}}let c=e.type===_.TESTIM_TVC?{alwaysMatch:l}:l,d=L.flags.increaseTDCRequestTimeout.isEnabled();return{...a,desiredCapabilities:l,...d&&{connectionRetryTimeout:48e4},capabilities:c,connectionRetryCount:0,logLevel:r.appiumLogLevel}}async function Cb(s){var h,g;let{projectType:e,gridInfo:t,nativeAppMetadata:r,options:n,appPath:o,androidActivityWait:i,sessionTags:a,testRunConfig:l}=s,{deviceUdid:c}=n;vb({nativeAppMetadata:r,appPath:o,gridInfo:t}),bI({deviceUdid:c,gridInfo:t,testRunConfig:l});let d=c||((g=(h=l.mobile)==null?void 0:h.staticAllocation)==null?void 0:g.deviceUdid),m=await Et.getGridDirectConnection(t,d),f=Sb({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 Pb(s){let{projectType:e,nativeAppMetadata:t,appPath:r,androidActivityWait:n}=s;return Lr({projectType:e,sessionCaps:{},nativeAppMetadata:t,appPath:r,androidActivityWait:n})}function kb(s){var t,r;let e={...s};return delete e.path,delete e.user,delete e.key,delete e.desiredCapabilities,delete e.capabilities["saucelabs.user"],delete e.capabilities["saucelabs.key"],delete e.capabilities["browserstack.user"],delete e.capabilities["browserstack.key"],(t=e.capabilities["sauce:options"])==null||delete t.user,(r=e.capabilities["sauce:options"])==null||delete r.key,delete e.capabilities.key,delete e.capabilities.user,e}var Or,Es,yI,Rp=w(()=>{"use strict";pe();ae();Sa();Or=require("lodash");F();ue();Es="appium:",yI=[_.BROWSERSTACK,_.SAUCELABS,_.TESTIM_HEADSPIN,_.TESTIM_TDC,_.TESTIM_TVC,_.P_CLOUDY]});var xa,Ob=w(()=>{"use strict";xa=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 Ca,Lb=w(()=>{"use strict";F();Ca=class{constructor(e){this.driver=e;this._abortedSteps=[];this.unescapeHTML=zs;this.getLinksFromUnescapeHTML=Ks}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 Ap,Pa,Db=w(()=>{"use strict";j();Ap=C("mobile-frame-locator-mock"),Pa=class{foundFrameCallback(){return Ap.info("foundFrameCallback-mock invoked"),{}}locate(){return Ap.info("locate-mock invoked"),{}}async findFrame(){return Ap.info("findFrame-mock invoked"),{}}}});var LI,Nb,Mb,Is,xp=w(()=>{"use strict";LI=S(require("webdriverio")),Nb=require("@applitools/eyes-sdk-core");Ob();fp();j();Lb();gp();we();wp();Db();vp();Mb=C("appium-test-player"),Is=class{constructor(e,t,r,n=LI,o=void 0,i=void 0){this.id=e;this.driver=n;let{SessionPlayer:a,commonConstants:l,StepActionFactory:c,MobileLocateElementPlayer:d}=Q(),m=new Ca(this.driver);this.stepActionFactory=new c(m),wa(this.driver,this.stepActionFactory),this.playbackTimeoutCalculator=new Ss(Ji()),this.sessionPlayer=new a(e,{tabService:new xa,cookieUtils:void 0,FrameLocator:Pa,portSelector:qi,LocateElementPlayer:d,stepActionUtils:m,stepActionFactory:this.stepActionFactory,playbackTimeoutCalculator:this.playbackTimeoutCalculator,makeSDK:Nb.makeSDK}),this.sessionPlayer.setShouldMonitorPerformance(Boolean(r)),this.sessionPlayer.playbackManager.isRemoteSession=!0,this.sessionPlayer.playbackManager.isLocalRun=!1,this.sessionPlayer.playbackManager.testRetryCount=o,this.sessionPlayer.playbackManager.previousTestResultId=i,this.sessionPlayer.playbackManager.userParamsData=t||{},this.onStepCompleted=this.onStepCompleted.bind(this),this.sessionPlayer.playbackManager.on(l.playback.RESULT,this.onStepCompleted)}onStepCompleted(e,t,r,n){}async onDone(){let{playbackManager:e}=this.sessionPlayer,{executionId:t,testResult:{resultId:r}={},appiumApi:n}=e,o={executionId:t,testResultId:r,sessionId:n==null?void 0:n.sessionId};try{n!=null&&n.sessionId&&(await(n==null?void 0:n.endSession()),Mb.info("appium session deleted",{...o}))}catch(i){Mb.error("error while deleting appium session",{...o,error:i})}finally{let{commonConstants:i}=Q();e.off(i.playback.RESULT)}}getSessionId(){var e;return(e=this.sessionPlayer.playbackManager.appiumApi)==null?void 0:e.sessionId}}});async function DI(s){return await Te(`${s}/api/status`)}async function Ub(s,e){return await Te(`${s}/api/devices/${e}/status`)}async function Fb(s){if((await DI(s)).fsmState!=="Ready")throw new Error("TMA is not ready")}var Bb=w(()=>{"use strict";Ge()});var jb={};G(jb,{WorkerLocalTma:()=>_p});var ka,Cp,Pp,kp,_p,$b=w(()=>{"use strict";Ge();Rp();Nn();F();j();Ot();xp();we();Bb();Sa();ka=C("worker-appium"),Cp=class extends Error{},Pp=class extends Error{},kp=class extends Error{},_p=class extends lt{constructor(){super(...arguments);this.baseDevicePath=(t,r)=>`${t}/api/devices/${r}`}initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async initAndGetAppiumAPI(t){if(t.sessionPlayer.playbackManager.appiumApi)return t.sessionPlayer.playbackManager.appiumApi;let{AppiumApi:r}=Q(),{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 I;if(Z.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 Fb(i);let{project:c,authData:{token:d=""}={}}=this.options,{driver:m}=n,u=l.type,f=this.options.appId;if(f){let{mobileApp:x}=await Et.getMobileAppDataByAppId({appId:f,projectId:c,token:d});t.nativeApp=x}let h=u==="android"?t.androidActivityWait:null,g=t.nativeAppMetadata,y=t.downloadableAppPublicLink,T=t.appPackageNameOrBundleId;if(!g)throw new Error("Application not specified. Please provide the required application for execution and try again.");if(!T)throw new Error("The application appears to be corrupted. Please ensure the application is in a valid state before running the test.");let[{appInstalled:R,version:b},v]=await Promise.all([this.getAppStateFromDevice(i,a,T),Ub(i,a)]).catch(x=>{throw this.handleDeviceNotFoundError(x),x});if(!R&&t.isAppFromDevice&&!f)throw new Error("The application is not installed on the target device. Please ensure the application is installed and try again.");!R&&y&&await this.installApp(i,a,y);try{let x={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${(I=this.options.projectData)==null?void 0:I.name}-${this.options.project}`},O=Pb({projectType:u,nativeAppMetadata:g,appPath:y,androidActivityWait:h,sessionTags:x,gridInfo:o,options:this.options,testRunConfig:this.testRunConfig}),W={capabilities:{udid:a,...O}},A=await this.requestNewAppiumSessionFromTma(i,W,g);this.sessionData=A;let E=await m.attach({sessionId:A.sessionId,capabilities:O});this.device=await Et.updateTmaDeviceDetails(a,this.options,t),ka.info(`init new appium session with local TMA testName: ${this.testName}`,{sessionId:E.sessionId,testResultId:this.testResultId,nativeAppMetadata:g,sessionCaps:E.capabilities})}catch(x){throw ka.error("failed to start application",{err:x}),x}}async requestNewAppiumSessionFromTma(t,r,n){var o,i;try{let a=await Ve({url:`${t}/api/session`,headers:{"Content-Type":"application/json"},body:r,timeout:6e4}),l={name:n.name,version:n.version};return{...a,appInfo:l,env:"local-tma"}}catch(a){this.handleDeviceNotFoundError(a);let l=(i=(o=a.response)==null?void 0:o.body)==null?void 0:i.message;throw a.status===500&&typeof l=="string"&&l.startsWith("Failed to create driver session")?new kp(l):a}}async getAppStateFromDevice(t,r,n){let o=this.options.projectData.type==="ios"?"bundles":"apps",i=`${this.baseDevicePath(t,r)}/${o}`,l=(await Te(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 Ut(n);await Fs(`${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 Pp(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 Cp(`Device Unavailable: Please ensure that the specified device ${this.options.deviceUdid} is currently connected`)}async runTestOnce(t,r){let{manifestVersion:n,localAssetService:o}=Q(),{sessionPlayer:i}=r,a=n||"runner";Z.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 ka.error("error while running appium tests",{err:c}),c}};try{return await super.runTestOnce(t,r),await l()}catch(c){throw ka.error("failed to run test once",{err:c}),c}}}});var Vb={};G(Vb,{WorkerAppium:()=>Op});var Wb,Dr,Op,Gb=w(()=>{"use strict";Rp();Wb=require("linkedom");Nn();j();Ot();xp();we();Sa();ae();is();Dr=C("worker-appium"),Op=class extends lt{initPlayer(t){return new Is(this.id,t.runParams,this.options.shouldMonitorPerformance,void 0,t.retryCount,t.previousTestResultId)}async getBrowserOnce(t,r,n,o){Z.onGetSession(this.id,this.testName,t.runMode);let{driver:i}=n,a=this.options.projectData.type,l=await Et.getAppIdFromGridOrTestimPublicLink({testRunHandler:t,options:this.options,pendingAppUploads:this.executionQueue.pendingAppUploads}),c=a==="android"?t.androidActivityWait:null,d=t.nativeAppMetadata;if(!d)throw new Error("Application not specified. Please provide the required application for execution and try again.");try{let m={testName:this.testName,executionId:this.executionId,testResultId:this.testResultId,project:`${this.options.projectData.name}-${this.options.project}`,...this.options.customTag&&{customTag:this.options.customTag},testId:this.testId,branch:this.branch,pCloudyIndividual:`${this.executionId}-${this.id}`},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 Et.lockDevice(o,this.options.deviceUdid),f=await Cb(u)):f=xb(u),Dr.info("starting appium session",{testResultId:this.testResultId,executionId:this.executionId,sessionTags:m,nativeAppMetadata:d,capabilities:kb(f)});let h=this.getServerAddressFromGrid();this.activeSession=await i.remote(f),this.device=await Et.updateDeviceOnRemoteTestResult(t,this.activeSession,h,this.options);let g=`${h}/session/${this.activeSession.sessionId}`;this.updateSlotData(g),Dr.info("appium session started successfully",{sessionId:this.activeSession.sessionId,testResultId:this.testResultId,executionId:this.executionId,sessionCaps:this.activeSession.capabilities})}catch(m){throw Dr.error("failed to start application",{testResultId:this.testResultId,executionId:this.executionId,err:m}),m}}async startKeepAlive(t){let{errors:r}=Q(),n=async()=>{try{await(t==null?void 0:t.getOrientation())}catch(o){Dr.error("failed to keep appium session alive",{err:o}),r!=null&&r.AppiumSessionTerminatedError&&o instanceof r.AppiumSessionTerminatedError&&this.stopKeepAlive()}};this.keepAliveIndex=setInterval(n,25e3)}stopKeepAlive(){this.keepAliveIndex&&clearTimeout(this.keepAliveIndex)}updateSlotData(t){try{this.options.slotService==="redis"&&mg(this.options.company.companyId,this.options.projectData.projectId,{testResultId:this.testResultId,executionId:this.executionId,type:"execution",source:this.options.source,sessionUrl:t},this.id)}catch(r){Dr.error("failed to update slot data",{err:r})}}getServerAddressFromGrid(){let{host:t,port:r,accessToken:n,type:o}=this.options.gridData;return o===_.TESTIM_HEADSPIN||o===_.TESTIM_TDC?`https://${t}:${r}/v0/${n}/wd/hub`: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}=Q(),{sessionPlayer:a}=r,l=n||"runner";Z.onWaitToTestComplete(this.id),a.playbackManager.executionId=t.executionId,a.playbackManager.executionName=t.executionName;let c;if(this.options.skipLoadBalancer){let h=this.options.deviceUdid||((u=this.testRunConfig.mobile)==null?void 0:u.staticAllocation.deviceUdid),{protocol:g,hostname:y,port:T,path:R}=await Et.getHeadSpinDeviceConnection(this.options.gridData,h);c=`${g}://${y}:${T}${R}`}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,Wb.DOMParser),this.startKeepAlive(a.playbackManager.appiumApi),i.initialize({serverUrl:this.options.localRCASaver});let m=async()=>{try{let h=await new Promise((y,T)=>{a.playByTestId({testId:this.testId,executionId:this.executionId,resultId:this.testResultId,baseUrl:this.baseUrl,userData:this.userData,version:l,resolve:y,isLocalRun:!1,overrideTestConfigId:this.overrideTestConfigId,branch:this.branch,remoteRunId:t.remoteRunId}).catch(T)});return this.stopKeepAlive(),await i.drain(),h.stepsResults=null,h.resultId=this.testResultId,{...h,...t.seleniumPerfStats.getStats()}}catch(h){throw Dr.error("error while running appium tests",{testResultId:this.testResultId,executionId:this.executionId,err:h}),this.stopKeepAlive(),h}};try{return await super.runTestOnce(t,r),await m()}catch(h){throw Dr.error("failed to run test once",{err:h}),h}}}});var _a,Hb=w(()=>{"use strict";F();_n();K();_a=class{constructor(e){this.id=e;this.driver=new xr}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 qb,Oa,zb=w(()=>{"use strict";qb=S(require("ws"));F();Oa=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 qb.default(this._cdpUrl,{timeout:e}),r=Xt(o=>{t.once("open",o)}),n=Xt(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 Da,Lp,La,Kb=w(()=>{"use strict";F();Da=S(require("chrome-launcher"));$u();zb();dn();Lp=class{constructor(e){this.sessionId=e;this._isAlive=!1;this.cdpTestRunner=new Oa}async init(e){var f,h,g,y;let{browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c}=e,d=Pi({browserOptions:t,testName:r,testRunConfig:n,gridInfo:o,customExtensionLocalLocation:i,executionId:a,testResultId:l,printFinalCaps:c}),m=[...((f=d.desiredCapabilities)==null?void 0:f.chromeOptions.args)??[],...((y=(g=(h=d.capabilities)==null?void 0:h.alwaysMatch)==null?void 0:g["goog:chromeOptions"])==null?void 0:y.args)??[],...Da.Launcher.defaultFlags().filter(T=>T!=="--disable-extensions")];this.chrome=await Da.launch({chromeFlags:m,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 u=await yr(`localhost:${this.chrome.port}`);await this.cdpTestRunner.initSession(u),es(()=>this.chrome.kill())}isAlive(){return this._isAlive}start(){}async stop(){await this.cdpTestRunner.stopSession(),this.chrome&&await this.chrome.kill(),this._isAlive=!1}getSessionId(){return this.sessionId}},La=class{constructor(e){this.id=e;this.sessionId=se();this.driver=new Lp(this.sessionId)}async onDone(){return this.driver.stop()}getSessionId(){return this.sessionId}}});var Yb={};G(Yb,{WorkerExtension:()=>Gn});function MI(s){return s instanceof Error&&"type"in s&&typeof s.type=="string"}function Jb(s){return MI(s)?s:new Error(s)}var ut,Gn,Dp=w(()=>{"use strict";$e();K();Nn();F();j();Ot();ae();Hb();Kb();Qe();ut=C("worker-ext"),Gn=class extends lt{initPlayer(){return this.options.useChromeLauncher?new La(this.id):new _a(this.id)}async _getBrowserOnce(e,t,r,n){var i;let{driver:o}=r;try{return await o.init({overrideConfiguration:e.overrideTestConfig,browserOptions:this.options,testName:this.testName,testRunConfig:this.testRunConfig,gridInfo:n,customExtensionLocalLocation:t,executionId:this.executionId,testResultId:this.testResultId,seleniumPerfStats:e.seleniumPerfStats,fastInit:(i=this.options.lightweightMode)==null?void 0:i.general,lambdatestService:this.lambdatestService,printFinalCaps:this.options.printFinalCaps})}catch(a){throw ut.error("failed to get browser",{err:a,gridInfo:n,whitelistedPublicIp:Uo(),initializedFromCache:Fo(),testId:e.testId,resultId:e.testResultId,publicIps:this.options.publicIps}),a}}async getBrowserOnce(e,t,r,n){return Z.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,Ue.TEST_START_TIMEOUT_MSG)}catch(u){if(!(u instanceof ne))throw u;return ut.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 ut.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)){Z.onWaitToTestStart(this.id),Z.onWaitToTestComplete(this.id);try{return{...await i(t.driver),...e.seleniumPerfStats.getStats()}}catch(h){throw ut.warn("failed to run test via CDP",{err:h}),h}}let{driver:m}=t,u={driverUrlFinished:!1,testRunHandlerOnStartedHadFinished:!1};try{let h=await e.getRunTestUrl();Z.onWaitToTestStart(this.id);try{await ce(Promise.all([a(t.driver,h,u),l(u)]),this.options.testStartTimeout,Ue.TEST_START_TIMEOUT_MSG)}catch(T){if(!(T instanceof ne))throw T;ut.warn("timeout occurred (see log's payload). Running checkViaRestAPIIfTestStarted",{testResultId:r,executionId:n,testId:o,...u}),await e.checkViaRestAPIIfTestStarted()}Z.onWaitToTestComplete(this.id);let g=new AbortController,y=T=>{e.onCompletedCleanup(),ut.warn("on browser closed error detected",{err:T,testResultId:r,executionId:n,testId:o}),m.unregisterToClosedBrowser(y),T.type=$s.BROWSER_CLOSED,g.abort(T)};m.registerToClosedBrowser(y);try{let T=ce(e.onCompleted(),this.testRunTimeout,Ue.TEST_COMPLETE_TIMEOUT_MSG),R=await uc(T,g.signal);m.unregisterToClosedBrowser(y);try{await this.updateTestStatusOnGrid(m,Boolean(R.success),R.reason)}catch(I){ut.error("Could not update the grid about the test status",{err:I})}m.isAlive()||(ut.warn(`possible grid unresponsive for test ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),R.gridIssues="could not validate grid is alive");let b=m.maxKeepAliveGap();return b>=3e4&&(ut.warn(`possible browser keep alive issue ${this.testId}, result ${this.testResultId} (execution: ${this.executionId})`),R.keepAliveIssue=b),{...R,...e.seleniumPerfStats.getStats()}}catch(T){throw ut.warn("timeout wait until test completed",{err:T,testResultId:r,executionId:n,testId:o}),Jb(T)}finally{m.unregisterToClosedBrowser(y)}}catch(h){throw ut.warn("failed to start url",{err:h}),Jb(h)}};t.driver.start();try{return await super.runTestOnce(e,t),N("WorkerExtension super.runTestOnce"),await c()}catch(d){throw ut.error("failed to run test",{err:d,testId:e.testId,resultId:e.testResultId}),d}}}});var Xb={};G(Xb,{WorkerExtensionSingleBrowser:()=>Mp});var NI,UI,Mp,Qb=w(()=>{"use strict";$e();F();j();sp();Ot();Dp();NI=C("base-worker"),UI=500,Mp=class extends Gn{async _releasePlayer(){if(!this.testPlayer)return;let{projectId:t}=this.userData||{};await Dn(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 Z.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()&&(NI.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(UI)}}});function FI(s,e){e===0?s():setTimeout(s,e*pd)}var Np,Ma,Zb=w(()=>{"use strict";_n();ue();$e();ku();Qe();qu();K();j();ae();Gh();Np=C("parallel-worker-manager"),Ma=class{constructor(e){this.customExtensionLocalLocation=e}getWorkerType(e){switch(e.mode){case ee.SELENIUM:return(bb(),be(yb)).WorkerSelenium;case ee.APPIUM:return e.localTmaUrl?($b(),be(jb)).WorkerLocalTma:(Gb(),be(Vb)).WorkerAppium;default:return _i.isFeatureAvailableForProject("useSameBrowserForMultiTests")?(Qb(),be(Xb)).WorkerExtensionSingleBrowser:(Dp(),be(Yb)).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,h)=>new Promise(g=>{var dr,k,M,B,z,dt,ja,zp;let y=o.project,T=new Fi(r,n,e,o,i,t),R={},b=e.length,v=((dr=o.company)==null?void 0:dr.ucid)||"",I=(k=o.company)==null?void 0:k.companyId,x=(M=o.company)==null?void 0:M.name,O=o.source||"cli",W=o.user,A=(B=o.company)==null?void 0:B.planType,E=(z=o.company)==null?void 0:z.isStartUp,D=(dt=o.projectData)==null?void 0:dt.name,U=(ja=o.projectData)==null?void 0:ja.type,H=o.lightweightMode,q=(zp=o.gridData)==null?void 0:zp.type,Y=(Dt,mt,ve,$a,qn,Wa)=>(m++,xg({executionId:r,projectId:y,testId:mt,resultId:ve,ucid:v,companyId:I,companyName:x,projectName:D,companyPlan:A,source:O,user:W,lightweightMode:H,isStartUp:E,projectType:U,appSource:Wa,gridType:q}),t.testStartAndReport(Dt,r,ve,$a,qn)),me=async(Dt,mt,ve,$a,qn,Wa)=>{var Kp,Jp,Yp;m--;let tt={...(H==null?void 0:H.onlyTestIdsNoSuite)&&{show:!0},...ve.seleniumStats&&{seleniumStats:ve.seleniumStats},...ve.gridIssues&&{gridIssues:ve.gridIssues},...ve.keepAliveIssue&&{keepAliveIssue:ve.keepAliveIssue},...o.host&&{gridHost:o.host}};if(ve.seleniumPerfMarks&&(t.concatSeleniumPerfMarks(ve.seleniumPerfMarks),delete ve.seleniumPerfMarks),o.grid||o.gridId?(tt.gridName=o.grid||((Kp=o.gridData)==null?void 0:Kp.name),tt.gridType=(Jp=o.gridData)==null?void 0:Jp.type,tt.gridProvider=(Yp=o.gridData)==null?void 0:Yp.provider):o.localTmaUrl?(tt.gridName="local-tma-from-options",tt.gridType="local-tma"):o.useLocalChromeDriver?(tt.gridName="local-chrome-driver-from-options",tt.gridType="local-chrome"):o.useChromeLauncher?(tt.gridName="chrome-launcher-from-options",tt.gridType="local-chrome"):o.browserstack?tt.gridName="browserstack-from-options":o.saucelabs&&(tt.gridName="saucelabs-from-options"),await t.testEndAndReport(Dt,ve,r,$a,qn,tt).catch(_T=>Np.error("testEndAndReport threw an error",{err:_T})),qn)return;R[ve.resultId]=ve,Cg({executionId:r,projectId:y,testId:mt,resultId:ve.resultId,result:ve,ucid:v,companyId:I,companyName:x,projectName:D,companyPlan:A,source:O,user:W,lightweightMode:H,logger:Np,isStartUp:E,projectType:U,appSource:Wa}),c&&!ve.success&&(T.stop(),d=!0),(Object.keys(R).length===b||d&&m===0)&&g(R)},pt=(Dt,mt)=>{R[mt.resultId]=mt,t.onTestIgnored(Dt,mt.resultId),m--,(Object.keys(R).length===b||d&&m===0)&&g(R)},It=(Dt,mt)=>t.onGridSlot(Dt,mt);o.userData={loginData:{...$t(),refreshToken:Mo(),authData:$t(),token:f,userAccessKey:h},projectId:o.project,company:o.company,servicesUrl:fe},N("in localStrategy before createWorker"),this.createWorkers(l,T,o,this.customExtensionLocalLocation,r,Y,me,It,pt).forEach((Dt,mt)=>{N("before schedule worker.run after createWorkers"),FI(()=>{N("right before worker.run"),Dt.run()},mt)})});try{let f=await Pt(),h=await No(),g=await u(f,h);if(d)throw new Jt;return g}catch(f){throw Np.error("failed running parallel workers",{executionId:r,err:f}),f}}}});async function tT(s,e){var t;return(t=s.lightweightMode)!=null&&t.onlyTestIdsNoSuite&&s.testId?{tests:[s.testId.map(n=>({testId:n,testConfig:{},resultId:se()}))]}:await cl({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 Up(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 Fp(s,e){let t=s.mode==="extension"?["edge-chromium","chrome"]:["firefox","chrome","edge-chromium","safari","safari technology preview","browser","android","ios","iphone","ipad"],r=eT.difference(Ws(s,e),t);if(r.length>0)throw Tt("invalid-config-run",{browser:r.join(", "),mode:"runner"}),new P(`browser type <${r}> is not supported in ${s.mode} mode.`);return e}var eT,rT=w(()=>{"use strict";eT=S(require("lodash"));F();ts();he();K()});var Hn,Bp,jp,Na,sT=w(()=>{"use strict";Hn=S(require("lodash"));F();j();ue();ae();$e();ns();mu();ku();he();Qe();Ot();Jg();K();Zb();rT();({CLI_MODE:Bp}=Ft),jp=C("test-plan-runner"),Na=class{constructor(e){this.startTime=Date.now();this.workerManager=new Ma(e)}async runTestAllPhases(e,t,r,n,o,i,a,l){let c={},d=$t(),m=async()=>{let g=o.beforeParallel||1,y=!0,T=await this.workerManager.runTests(e,l,i,a,o,n,d,g,y);Object.assign(c,T)},u=async()=>{let g=no||o.parallel,y=!1;N("right before this.workerManager.runTests");let T=await this.workerManager.runTests(t,l,i,a,o,n,d,g,y);N("right after this.workerManager.runTests"),Object.assign(c,T)},f=async()=>{let g=o.afterParallel||1,y=!1,T=await this.workerManager.runTests(r,l,i,a,o,n,d,g,y);Object.assign(c,T)};Pg({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(g){if(jp.error("error running test plan",{err:g}),g instanceof Jt)return l.markAllQueuedTests(i,de.ABORTED,"aborted",!1);throw g}finally{await h()}async function h(){var y,T,R,b;if((y=o.lightweightMode)!=null&&y.disablePixelValidation)return;if(o.mode===Bp.SELENIUM){let[{getSessionPlayer:v},{makeSDK:I}]=await Promise.all([Promise.resolve().then(()=>(we(),tr)),import("@applitools/eyes-sdk-core")]),{EyeSdkBuilder:x}=v();await x.closeBatch(i,I);return}let g;try{if(!((b=(R=(T=o.company)==null?void 0:T.activePlan)==null?void 0:R.premiumFeatures)!=null&&b.applitools)||(g=await Il(o.project),Hn.default.isEmpty(g)||!i))return;let{runKey:v,url:I}=g;await require("@applitools/eyes-sdk-core").makeSDK({name:"Testim.io",version:"4.0.0",spec:{}}).closeBatches({settings:{batchIds:[i],serverUrl:I,apiKey:v}})}catch{}}}async runTestPlan(e,t,r,n,o,i,a,l){var b,v,I;let c=se(),d=n.project;oc(c),e.forEach(x=>Object.assign(x,{isBeforeTestPlan:!0})),r.forEach(x=>Object.assign(x,{isAfterTestPlan:!0}));let m=[...e,...t,...r],u=new Ci(m,n,i,a),f=Hn.default.chain(m).map(x=>{var O;return((O=x.overrideTestConfig)==null?void 0:O.name)||""}).uniq().compact().value(),h=(f==null?void 0:f.length)===1?f[0]:null,g=(b=n.lightweightMode)!=null&&b.onlyTestIdsNoSuite?[]:m.map(x=>x.name),y=(v=n.lightweightMode)!=null&&v.onlyTestIdsNoSuite?{beforeTests:e,tests:t,afterTests:r}:u.executionStart(c,d,this.startTime,o,g);N("before testListInfoPromise");let T=await y;(I=n.lightweightMode)!=null&&I.onlyTestIdsNoSuite||Z.onTestPlanStarted(T.beforeTests,T.tests,T.afterTests,o,c,l,h),N("before runTestAllPhases");let R=await this.runTestAllPhases(T.beforeTests,T.tests,T.afterTests,a,n,c,o||"All Tests",u);return N("before executionEnd"),await u.executionEnd(c),N("after executionEnd"),{results:R,executionId:c,testPlanName:o,configName:h}}async runTestPlans(e,t){jp.info("start to run test plan",{options:{...e,token:void 0,userParamsData:void 0},branchToUse:t});function r(d){return Hn.default.flattenDeep(Object.values(d)).reduce((m,u)=>m.concat(u.beforeTests,u.tests,u.afterTests),[])}let n={},o={},i=e.project,a=await al(i,e.testPlan,e.testPlanIds,t,e.intersections),l=a.testPlans,c=a.testPlansData;if(!l||l.length===0)throw new P(`no test plan to run ${e.testPlan}`);if(!c||Object.keys(c).length===0){if(e.passZeroTests)return[];throw new P(`no test to run in test plan ${e.testPlan}`)}return e.mode!==Bp.APPIUM&&await Fp(e,r(c)),await ie(l,async d=>{var h;let m=d.testPlanId;n[m]={};let u={...e};u.baseUrl||=d.startUrl,u.appId||=((h=d.mobileApp)==null?void 0:h.appId)||void 0,u.gridId||=d.gridId,e.grid&&delete u.gridId,u.gridData=await ig(e,d);let f=u.overrideExecutionName||d.name;return await ie(c[m],async g=>{let y=await this.runTestPlan(g.beforeTests,g.tests,g.afterTests,u,f,m,t);Z.onTestPlanFinished(y.results,d.name,this.startTime,y.executionId,!1),n[m][y.executionId]=y.results;let T=Object.keys(n[m]).map(I=>({executionId:I,status:Up(n[m][I])})),R=Object.keys(n[m]).map(I=>n[m][I]).reduce((I,x)=>Object.assign(I,x),{}),b=Up(R);Object.assign(o,R);let v=b?T[0].executionId:T.find(I=>!I.status).executionId;return await nl(i,m,{success:b,executions:T,executionId:v}),y})})}async runAnonymousTestPlan(e,t){var l;jp.info("start to run anonymous",{options:{...e,token:void 0},branchToUse:t}),N("before getSuite");let r=await tT(e,t);if(N("after getSuite"),!((l=r==null?void 0:r.tests[0])!=null&&l.length)){if(e.rerunFailedByRunId)throw new P("No failed tests found in the provided run");if(e.passZeroTests)return[];throw new P("No tests to run")}t="branch"in r&&r.branch||t;let n=r;if(e.rerunFailedByRunId&&!n.runName){if(!n.runExists)throw new P("Invalid run ID - no such run.");n.runName===""&&(n.runName=`rerun-${e.rerunFailedByRunId}`)}let o=e.overrideExecutionName||n.runName||[].concat(e.label,e.name,e.suites).join(" "),i=!0;N("Right before validateConfig + runAnonymousTestPlan tests map");let a;return e.appId&&e.mode==="appium"&&(a=await ln({appId:e.appId,projectId:e.project})),await ie(r.tests,async c=>{if(a&&c.forEach(m=>{"nativeApp"in m&&(m.nativeApp=a)}),e.resultId){let m=c[0];m.resultId=e.resultId,c=[m]}e.mode!==Bp.APPIUM&&await Fp(e,c),N("right before runTestPlan");let d=await this.runTestPlan([],c,[],e,o,null,t,i);return N("right after runTestPlan"),await Z.onTestPlanFinished(d.results,o,this.startTime,d.executionId,i),d})}async run(e){let t=En(),r=[];Vs(e)?r=await this.runTestPlans(e,t):r=await this.runAnonymousTestPlan(e,t);let n=Hn.default.flattenDeep(r);return N("right before onAllTestPlansFinished"),await Z.onAllTestPlansFinished(n),N("right after onAllTestPlansFinished"),n.map(o=>o.results).reduce((o,i)=>Object.assign(o,i),{})}}});var aT={};G(aT,{init:()=>oR,run:()=>eR});async function BI(s){let e=s.project,t=await ll(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"),mn(s.authData.uid,"execution-quota-surpassed",{projectId:e}),new Ls}function jI(s,e){var i,a,l,c,d,m,u,f;let t=bo(e.activePlan),r=s.parallel;if(t==="free"&&r>oT)throw new P(`The free plan allows only ${oT} parallel runs, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted`);if(e.followL2CPlan){let h=(a=(i=e.activePlan)==null?void 0:i.premiumFeatures)==null?void 0:a.tunnel;if(s.tunnel&&!h)throw new P("Tunnel is not allowed for your current plan, please upgrade your plan at https://www.testim.io/upgrade-contact-us?source=cli. Run aborted");let 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)===_.TESTIM_TVC){let h=e.tvcLicense.expireAt||1;if(Date.now()>h)throw new P("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted");let g=Number(e.tvcLicense.maxParallel);if(r>g)throw new P(`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`)}if(e.tdcLicense&&((m=s.gridData)==null?void 0:m.type)===_.TESTIM_TDC){let h=e.tdcLicense.expireAt||1;if(Date.now()>h)throw new P("Your license has expired. Please contact us at https://www.testim.io/upgrade-contact-us?source=cli to renew your license. Run aborted")}let n=s.retentionDays;if(!n)return;let o=(f=(u=e.activePlan)==null?void 0:u.premiumFeatures)==null?void 0:f.resultRetention;if(n>o)throw new P(`Retention days (${n}) cannot be greater than the company's retention days (${o}). Run aborted`)}async function $I(s){var e;if(!((e=s.lightweightMode)!=null&&e.disableQuotaBlocking))try{await BI(s)}catch(t){if([P,Ls].some(r=>t instanceof r))throw t;$p.error("could not validate cli account",{err:t})}}function WI(s){let e=$t();return pf({userId:e.uid,name:e.uid,traits:{projectId:s,company:{id:s,lastCIRun:Math.floor(Date.now()/1e3)}}})}async function VI(s,{disableResults:e=!1,disableRemoteStep:t=!1}){if(L.flags.useNewWSCLI.isEnabled()&&!e&&!t)return vt.connect(s);if(!t){let{remoteStepService:r}=await Promise.resolve().then(()=>(Mi(),Dh));await r.init(s)}if(!e){let{testResultService:r}=await Promise.resolve().then(()=>(Ni(),Uh));r.init(s)}}function GI(s,e){let{branch:t,autoDetect:r}=s;if(fg(e,r),!e&&!r)throw new P(`branch ${t} does not exist, run aborted.`)}async function HI(s,e){let{id:t,type:r}=e,o=iT.get(s,"company.activePlan.premiumFeatures.ttaForSalesforce")||r==="sfdc"||r==="desktopWeb"&&L.flags.sfdcHybridCompany.isEnabled(),i=En();o&&(s.sfdcCredential=await rl({projectId:t,branch:i}))}function qI(s,e){let{id:t,storageBaseUrl:r,storageType:n,name:o,activePlan:i={}}=e,a=Boolean(i.isPoc),l=Boolean(i.isStartUp),c=bo(i);c==="free"&&(s.newBrowserWaitTimeout=s.newBrowserWaitTimeout<nT?nT:s.newBrowserWaitTimeout),L.setCompanyId(t),L.setIsPOC(a),L.setIsStartUp(l),L.setPlanType(c),_t.setPlanType(c),s.company={ucid:"",companyId:t,storageBaseUrl:r,storageType:n,name:o,planType:c,isPOC:a,isStartUp:l,activePlan:i}}function zI(s,e){s.editorUrl=_s||e.editorUrl}function KI(s,e){s.allGrids=e}function JI(s,e){s.authData=e}function YI(s,e){let{id:t,name:r,type:n,defaults:o}=e;L.setProjectId(t),L.setProjectType(n),s.projectData={projectId:t,type:n,name:r,defaults:o}}async function XI(s){var e;s.gridData=await ag(s),(e=s.gridData)!=null&&e.name&&(s.grid=s.gridData.name)}async function QI(s){let{project:e}=s,t={projectId:e};s.overrideMappingFile&&(Tt("user-override-file",t),s.mockNetworkRules=await Qm(s.overrideMappingFile))}async function ZI(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 Uf(),N("in runner.js after checkNpmVersion"),await $I(s),N("in runRunner before tunnel.connect"),await ci(s),N("in runRunner after tunnel.connect");let a=await new Na(e).run(s);return N("before tunnel.disconnect"),await li(s),await sR(s.slotService,t,s.company.companyId),N("after tunnel.disconnect and gridService.keepAlive.end"),a}function tR(s){var e;_t.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
|